file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/5/0x999512dC124371E6B9ff43CE8D1AF83252F0C851/sources/src/BaseVault.sol
Calculate the effective amounts to take from the user and mint the shares. Will not transfer the tokens from the user. amountX The amount of token X to be deposited. amountY The amount of token Y to be deposited. return strategy The address of the strategy. return shares The amount of shares to be minted. return effectiveX The amount of token X to be deposited. return effectiveY The amount of token Y to be deposited./ Check that at least one token is being deposited Verify that the strategy is set Calculate the effective amounts to take from the user and the amount of shares to mint Avoid exploit when very little shares, min of total shares will always be _SHARES_PRECISION (1e6)
function _deposit(uint256 amountX, uint256 amountY) internal virtual depositsAllowed returns (IStrategy strategy, uint256 shares, uint256 effectiveX, uint256 effectiveY) { if (amountX == 0 && amountY == 0) revert BaseVault__ZeroAmount(); strategy = _strategy; if (address(strategy) == address(0)) revert BaseVault__InvalidStrategy(); (shares, effectiveX, effectiveY) = _previewShares(strategy, amountX, amountY); if (shares == 0) revert BaseVault__ZeroShares(); if (totalSupply() == 0) { shares -= _SHARES_PRECISION; _mint(address(this), _SHARES_PRECISION); } emit Deposited(msg.sender, effectiveX, effectiveY, shares); }
1,894,082
./full_match/1/0x18da757144EC3443cF9C26446235bA0489d72Da8/sources/contracts/ERC721S.sol
Private function to invoke {IERC721Receiver-onERC721Received} on a target contract. `from` - Previous owner of the given token ID. `to` - Target address that will receive the token. `tokenId` - Token ID to be transferred. `_data` - Optional data to send along with the call. Returns whether the call correctly returned the expected magic value./
function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns ( bytes4 retval ) { return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert MintToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } }
4,918,009
//Address: 0x08cdcf9ba0a4b5667f5a59b78b60fbefb145e64c //Contract name: WorldCupToken //Balance: 0.035250000000000002 Ether //Verification Date: 3/24/2018 //Transacion Count: 7 // CODE STARTS HERE pragma solidity ^0.4.18; 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; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); } contract WorldCupToken is ERC721 { /*****------ EVENTS -----*****/ // @dev whenever a token is sold. event WorldCupTokenWereSold(address indexed curOwner, uint256 indexed tokenId, uint256 oldPrice, uint256 newPrice, address indexed prevOwner, uint256 traddingTime);//indexed // @dev whenever Share Bonus. event ShareBonus(address indexed toOwner, uint256 indexed tokenId, uint256 indexed traddingTime, uint256 remainingAmount); // @dev Present. event Present(address indexed fromAddress, address indexed toAddress, uint256 amount, uint256 presentTime); // @dev Transfer event as defined in ERC721. event Transfer(address from, address to, uint256 tokenId); /*****------- CONSTANTS -------******/ mapping (uint256 => address) public worldCupIdToOwnerAddress; //@dev A mapping from world cup team id to the address that owns them. mapping (address => uint256) private ownerAddressToTokenCount; //@dev A mapping from owner address to count of tokens that address owns. mapping (uint256 => address) public worldCupIdToAddressForApproved; // @dev A mapping from token id to an address that has been approved to call. mapping (uint256 => uint256) private worldCupIdToPrice; // @dev A mapping from token id to the price of the token. //mapping (uint256 => uint256) private worldCupIdToOldPrice; // @dev A mapping from token id to the old price of the token. string[] private worldCupTeamDescribe; uint256 private SHARE_BONUS_TIME = uint256(now); address public ceoAddress; address public cooAddress; /*****------- MODIFIERS -------******/ modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } function destroy() public onlyCEO { selfdestruct(ceoAddress); } function payAllOut() public onlyCLevel { ceoAddress.transfer(this.balance); } /*****------- CONSTRUCTOR -------******/ function WorldCupToken() public { ceoAddress = msg.sender; cooAddress = msg.sender; for (uint256 i = 0; i < 32; i++) { uint256 newWorldCupTeamId = worldCupTeamDescribe.push("I love world cup!") - 1; worldCupIdToPrice[newWorldCupTeamId] = 0 ether;//SafeMath.sub(uint256(3.2 ether), SafeMath.mul(uint256(0.1 ether), i)); //worldCupIdToOldPrice[newWorldCupTeamId] = 0 ether; _transfer(address(0), msg.sender, newWorldCupTeamId); } } /*****------- PUBLIC FUNCTIONS -------******/ function approve(address _to, uint256 _tokenId) public { require(_isOwner(msg.sender, _tokenId)); worldCupIdToAddressForApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account function balanceOf(address _owner) public view returns (uint256 balance) { return ownerAddressToTokenCount[_owner]; } /// @notice Returns all the world cup team information by token id. function getWorlCupByID(uint256 _tokenId) public view returns (string wctDesc, uint256 sellingPrice, address owner) { wctDesc = worldCupTeamDescribe[_tokenId]; sellingPrice = worldCupIdToPrice[_tokenId]; owner = worldCupIdToOwnerAddress[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return "WorldCupToken"; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return "WCT"; } // @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = worldCupIdToOwnerAddress[_tokenId]; require(owner != address(0)); return owner; } function setWorldCupTeamDesc(uint256 _tokenId, string descOfOwner) public { if(ownerOf(_tokenId) == msg.sender){ worldCupTeamDescribe[_tokenId] = descOfOwner; } } /// Allows someone to send ether and obtain the token ///function PresentToCEO() public payable { /// ceoAddress.transfer(msg.value); /// Present(msg.sender, ceoAddress, msg.value, uint256(now)); ///} // Allows someone to send ether and obtain the token function buyWorldCupTeamToken(uint256 _tokenId) public payable { address oldOwner = worldCupIdToOwnerAddress[_tokenId]; address newOwner = msg.sender; require(oldOwner != newOwner); // Make sure token owner is not sending to self require(_addressNotNull(newOwner)); //Safety check to prevent against an unexpected 0x0 default. uint256 oldSoldPrice = worldCupIdToPrice[_tokenId];//worldCupIdToOldPrice[_tokenId]; uint256 diffPrice = SafeMath.sub(msg.value, oldSoldPrice); uint256 priceOfOldOwner = SafeMath.add(oldSoldPrice, SafeMath.div(diffPrice, 2)); uint256 priceOfDevelop = SafeMath.div(diffPrice, 4); worldCupIdToPrice[_tokenId] = msg.value;//SafeMath.add(msg.value, SafeMath.div(msg.value, 10)); //worldCupIdToOldPrice[_tokenId] = msg.value; _transfer(oldOwner, newOwner, _tokenId); if (oldOwner != address(this)) { oldOwner.transfer(priceOfOldOwner); } ceoAddress.transfer(priceOfDevelop); if(this.balance >= uint256(3.2 ether)){ if((uint256(now) - SHARE_BONUS_TIME) >= 86400){ for(uint256 i=0; i<32; i++){ worldCupIdToOwnerAddress[i].transfer(0.1 ether); ShareBonus(worldCupIdToOwnerAddress[i], i, uint256(now), this.balance); } SHARE_BONUS_TIME = uint256(now); //ShareBonus(SHARE_BONUS_TIME, this.balance); } } WorldCupTokenWereSold(newOwner, _tokenId, oldSoldPrice, msg.value, oldOwner, uint256(now)); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return worldCupIdToPrice[_tokenId]; } /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = worldCupIdToOwnerAddress[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCars = totalSupply(); uint256 resultIndex = 0; uint256 carId; for (carId = 0; carId <= totalCars; carId++) { if (worldCupIdToOwnerAddress[carId] == _owner) { result[resultIndex] = carId; resultIndex++; } } return result; } } function getCEO() public view returns (address ceoAddr) { return ceoAddress; } //Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return worldCupTeamDescribe.length; } //return BonusPool $ function getBonusPool() public view returns (uint256) { return this.balance; } function getTimeFromPrize() public view returns (uint256) { return uint256(now) - SHARE_BONUS_TIME; } /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _tokenId) public { require(_isOwner(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) public { require(_isOwner(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /********----------- PRIVATE FUNCTIONS ------------********/ function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } function _approved(address _to, uint256 _tokenId) private view returns (bool) { return worldCupIdToAddressForApproved[_tokenId] == _to; } function _isOwner(address checkAddress, uint256 _tokenId) private view returns (bool) { return checkAddress == worldCupIdToOwnerAddress[_tokenId]; } function _transfer(address _from, address _to, uint256 _tokenId) private { ownerAddressToTokenCount[_to]++; worldCupIdToOwnerAddress[_tokenId] = _to; //transfer ownership if (_from != address(0)) { ownerAddressToTokenCount[_from]--; delete worldCupIdToAddressForApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } }
Required for ERC-721 compliance.
function transferFrom(address _from, address _to, uint256 _tokenId) public { require(_isOwner(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); }
6,428,882
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol"; import {ReentrancyGuard} from "openzeppelin-contracts/security/ReentrancyGuard.sol"; /** * @title DamnValuableToken * @author Damn Vulnerable DeFi (https://damnvulnerabledefi.xyz) */ contract UnstoppableLender is ReentrancyGuard { IERC20 public immutable damnValuableToken; uint256 public poolBalance; error MustDepositOneTokenMinimum(); error TokenAddressCannotBeZero(); error MustBorrowOneTokenMinimum(); error NotEnoughTokensInPool(); error FlashLoanHasNotBeenPaidBack(); constructor(address tokenAddress) { if (tokenAddress == address(0)) revert TokenAddressCannotBeZero(); damnValuableToken = IERC20(tokenAddress); } function depositTokens(uint256 amount) external nonReentrant { if (amount == 0) revert MustDepositOneTokenMinimum(); // Transfer token from sender. Sender must have first approved them. damnValuableToken.transferFrom(msg.sender, address(this), amount); poolBalance = poolBalance + amount; } function flashLoan(uint256 borrowAmount) external nonReentrant { if (borrowAmount == 0) revert MustBorrowOneTokenMinimum(); uint256 balanceBefore = damnValuableToken.balanceOf(address(this)); if (balanceBefore < borrowAmount) revert NotEnoughTokensInPool(); // Ensured by the protocol via the `depositTokens` function assert(poolBalance == balanceBefore); damnValuableToken.transfer(msg.sender, borrowAmount); IReceiver(msg.sender).receiveTokens( address(damnValuableToken), borrowAmount ); uint256 balanceAfter = damnValuableToken.balanceOf(address(this)); if (balanceAfter < balanceBefore) revert FlashLoanHasNotBeenPaidBack(); } } interface IReceiver { function receiveTokens(address tokenAddress, uint256 amount) external; }
Transfer token from sender. Sender must have first approved them.
function depositTokens(uint256 amount) external nonReentrant { if (amount == 0) revert MustDepositOneTokenMinimum(); damnValuableToken.transferFrom(msg.sender, address(this), amount); poolBalance = poolBalance + amount; }
12,753,503
./full_match/1/0x44f26a7b2b58621D97240b09350B66803Faa1E1a/sources/contracts/interfaces/ITreasuryManager.sol
A contract that manages fee-related functionality.
interface ITreasuryManager { function setFee(uint256 newFee) external; function setTreasury(address payable newTreasury) external; function fee() external view returns (uint256 fee); function getFeeData() external view returns (uint256 tokenFee, address payable treasuryAddress); function treasury() external view returns (address payable); event FeeChanged(uint256 newFee); event TreasuryChanged(address newTreasury); pragma solidity ^0.8.0; }
4,822,256
./full_match/8453/0x762eb51D2e779EeEc9B239FFB0B2eC8262848f3E/sources/contracts/OptionTokenV3.sol
burn callers tokens Take team fee Create Lp for users Stake the LP in the gauge with lock notify gauge reward with payment token
function _exerciseLp( address _recipient, uint256 _discount ) internal returns (uint256 paymentAmount, uint256 lpAmount) { if (isPaused) revert OptionToken_Paused(); if (_discount > minLPDiscount || _discount < maxLPDiscount) revert OptionToken_InvalidDiscount(); _burn(msg.sender, _amount); (uint256 paymentAmount,uint256 paymentAmountToAddLiquidity) = getPaymentTokenAmountForExerciseLp(_amount,_discount); if (paymentAmount > _maxPaymentAmount) revert OptionToken_SlippageTooHigh(); uint256 paymentGaugeRewardAmount = _takeFees( paymentToken, paymentAmount ); _safeTransferFrom( paymentToken, msg.sender, address(this), paymentGaugeRewardAmount + paymentAmountToAddLiquidity ); _safeApprove(underlyingToken, router, _amount); _safeApprove(paymentToken, router, paymentAmountToAddLiquidity); (, , lpAmount) = IRouter(router).addLiquidity( underlyingToken, paymentToken, false, _amount, paymentAmountToAddLiquidity, 1, 1, address(this), block.timestamp ); address _gauge = gauge; _safeApprove(address(pair), _gauge, lpAmount); IGaugeV2(_gauge).depositWithLock( _recipient, lpAmount, getLockDurationForLpDiscount(_discount) ); _transferRewardToGauge(); emit ExerciseLp( msg.sender, _recipient, _amount, paymentAmount, lpAmount ); }
11,552,903
pragma solidity 0.5.4; import {Ownable} from "./ownable.sol"; import {Editable} from "./editable.sol"; import {Content} from "./content.sol"; import {Container} from "./container.sol"; import {AccessIndexor} from "./access_indexor.sol"; import "./user_space.sol"; import "./meta_object.sol"; /* -- Revision history -- BaseContent20190221101600ML: First versioned released BaseContent20190301121900ML: Adds support for getAccessInfo, to replace getAccessCharge (not deprecated yet) BaseContent20190315175100ML: Migrated to 0.4.24 BaseContent20190321122100ML: accessRequest returns requestID, removed ml_hash from access_complete event BaseContent20190510151500ML: creation via ContentSpace factory, modified getAccessInfo API BaseContent20190510151500ML: creation via ContentSpace factory, modified getAccessInfo API BaseContent20190522154000SS: Changed hash bytes32 to string BaseContent20190528193400ML: Modified to support non-library containers BaseContent20190605203200ML: Splits publish and confirm logic BaseContent20190724203300ML: Enforces access rights in access request BaseContent20190801141600ML: Fixes the access rights grant for paid content BaseContent20191029161700ML: Removed debug statements for accessRequest BaseContent20191219135200ML: Made content object updatable by non-owner BaseContent20200102165900ML: Enforce visibility driven rights to edit BaseContent20200107175100ML: Moved Visibility filter from BaseContentObject to Accessible, default it to 0 BaseContent20200129211300ML: Restricts deletion to owner (not editor) or library owner, unless changed by custom contract BaseContent20200131120200ML: Adds support for default finalize behavior in runFinalize BaseContent20200205101900ML: Adds support for non-0 runkill codes in contract swap, allows library editors to delete objects BaseContent20200205142000ML: Closes vulnerability allowing alien external objects to kill a custom contract BaseContent20200211163800ML: Modified to conform to authV3 API BaseContent20200212101200ML: Disambiguatea getAccessInfo vs getAccessInfoV3 to reflect API changes BaseContent20200316135000ML: Leverages inherited hasAccess BaseContent20200422180500ML: Version update to reflect changes made to editable to fix deletion BaseContent20200803130000PO: Authv3 changes BaseContent20200928110000PO: Replace tx.origin with msg.sender in some cases */ contract BaseContent is MetaObject, Editable { bytes32 public version ="BaseContent20200928110000PO"; //class name (max 16), date YYYYMMDD, time HHMMSS and Developer initials XX address payable public contentType; address public addressKMS; address payable public contentContractAddress; address payable public libraryAddress; uint256 public accessCharge; //bool refundable; int public statusCode; // 0: accessible, - in draft, + in review // application have discretion to make up their own status codes to represent their workflow // bytes32 public constant STATUS_PUBLISHED = "Published"; // bytes32 public constant STATUS_DRAFT = "Draft"; // bytes32 public constant STATUS_REVIEW = "Draft in review"; uint256 public requestID = 0; struct RequestData { address payable originator; // client address requesting uint256 amountPaid; // number of token received int8 status; //0 access requested, 1 access granted, -1 access refused, 2 access completed, -2 access error uint256 settled; //Amount of the escrowed money (amountPaid) that has been settled (paid to owner or refunded) } mapping(uint256 => RequestData) public requestMap; event ContentObjectCreate(address containingLibrary); event SetContentType(address contentType, address contentContractAddress); event LogPayment(uint256 requestNonce, string label, address payee, uint256 amount); event AccessRequestValue(bytes32 customValue); event AccessRequestStakeholder(address stakeholder); event AccessRequest( //For backward compatibility uint256 requestID, uint8 level, string contentHash, string pkeRequestor, string pkeAFGH ); event AccessComplete(uint256 requestID, uint256 scorePct, bool customContractResult); event AccessCompleteV3( uint256 requestNonce, bool customContractResult, address parentAddress, bytes32 contextHash, address accessor, // I've called this 'userAddress' - don't care too much but ideally it's the same name wherever it means the same thing! uint256 request_timestamp // always millis - either set from context or with blockchain now() ); event SetContentContract(address contentContractAddress); event SetAccessCharge(uint256 accessCharge); event InsufficientFunds(uint256 accessCharge, uint256 amountProvided); event SetStatusCode(int statusCode); event Publish(bool requestStatus, int statusCode, string objectHash); // Debug events // event InvokeCustomPreHook(address custom_contract); // event ReturnCustomHook(address custom_contract, uint256 result); // event InvokeCustomPostHook(address custom_contract); modifier onlyFromLibrary() { require(msg.sender == libraryAddress); _; } constructor(address payable content_space, address payable lib, address payable content_type) public payable { contentSpace = content_space; libraryAddress = lib; statusCode = -1; contentType = content_type; visibility = 0; //default could be made a function of the library. indexCategory = 1; // AccessIndexor CATEGORY_CONTENT_OBJECT emit ContentObjectCreate(libraryAddress); } // function statusDescription() public view returns (bytes32) { // return statusCodeDescription(statusCode); // } function setVisibility(uint8 _visibility_code) public onlyEditor { visibility = _visibility_code; emit VisibilityChanged(contentSpace, libraryAddress, visibility); } // function statusCodeDescription(int status_code) public view returns (bytes32) { // bytes32 codeDescription = 0x0; // if (contentContractAddress != 0x0) { // Content c = Content(contentContractAddress); // codeDescription = c.runDescribeStatus(status_code); // } // if (codeDescription != 0x0) { // return codeDescription; // } // if (status_code == 0) { // return STATUS_PUBLISHED; // } // if (status_code < 0) { // return STATUS_DRAFT; // } // if (status_code > 0) { // return STATUS_REVIEW; // } // return 0; // } function setStatusCode(int status_code) public returns (int) { if ((msg.sender == owner) && ((status_code < 0) || ((status_code > 0) && (statusCode < 0)))) { //Owner can revert content to draft mode regardless of status (debatable for published, viewable content) // and owner can move status from draft to in review statusCode = status_code; } if (msg.sender == libraryAddress) { // Library has full authority to change status, it is assumed entitlement is done there statusCode = status_code; } emit SetStatusCode(statusCode); return statusCode; } function setAddressKMS(address address_KMS) public onlyEditor { addressKMS = address_KMS; } function getKMSInfo(bytes memory prefix) public view returns (string memory, string memory) { IKmsSpace kmsSpaceObj = IKmsSpace(contentSpace); if (addressKMS == address(0x0) || kmsSpaceObj.checkKMSAddr(addressKMS) == 0) { return ("", ""); } return kmsSpaceObj.getKMSInfo(kmsSpaceObj.getKMSID(addressKMS), prefix); } //Owner can change this, unless the contract they are already set it prevent them to do so. function setContentContractAddress(address payable addr) public onlyEditor { Content c; if (contentContractAddress != address(0x0)) { c = Content(contentContractAddress); uint killStatus = c.runKillExt(); if ((killStatus == 100) || (killStatus == 1100)) { c.commandKill(); } else { require((killStatus == 0) || (killStatus == 1000)); } } contentContractAddress = addr; if (addr != address(0x0)) { c = Content(addr); uint createStatus = c.runCreate(); require(createStatus == 0); } emit SetContentContract(contentContractAddress); } // Visibility codes // 0 -> visible // 10 -> content not published // 100 -> calculation of price exceeds specified cap (accessCharge) // 255 -> unset // Access codes // 0 -> paid for // 10 -> content not published // 100 -> content available if paid for // 255 -> unset function getWIPAccessInfo(address accessor) private view returns (uint8, uint8, uint256) { if ((accessor == owner) || (visibility >= CAN_ACCESS) ){ return (0, 0, accessCharge); } IUserSpace userSpaceObj = IUserSpace(contentSpace); address userWallet = userSpaceObj.userWallets(accessor); if (userWallet != address(0x0)) { /* AccessIndexor wallet = AccessIndexor(userWallet); if (wallet.checkContentObjectRights(address(this), wallet.TYPE_ACCESS()) == true) { return (0, 0, accessCharge); } */ if (hasAccess(accessor) == true) { return (0, 0, accessCharge); } } if (Container(libraryAddress).canReview(accessor) == true) { //special case of pre-publish review return (0, 0, accessCharge); } return (10, 10, accessCharge); } function getCustomInfo(address accessor, bytes32[] memory customValues, address payable[] memory stakeholders) public view returns (uint8, uint8, uint256) { uint256 calculatedCharge = accessCharge; uint8[2] memory codes; codes[0] = (visibility >= CAN_SEE) ? 0 : 255; // visibilityCode codes[1] = (visibility >= CAN_ACCESS) ? 0 :255; //accessCode if (contentContractAddress != address(0x0)) { uint8 customMask; uint8 customVisibility; uint8 customAccess; uint256 customCharge; (customMask, customVisibility, customAccess, customCharge) = Content(contentContractAddress).runAccessInfo(customValues, stakeholders, accessor); if (customCharge > accessCharge) { codes[0] = 100; } else { if ((customMask & 1 /*DEFAULT_SEE*/) == 0) { codes[0] = customVisibility; } if ((customMask & 2 /*DEFAULT_ACCESS*/) == 0) { codes[1] = customAccess; } if ((customMask & 4 /*DEFAULT_CHARGE*/) == 0) { calculatedCharge = customCharge; } } } return (codes[0], codes[1], calculatedCharge); } function getAccessInfo(uint8, bytes32[] memory customValues, address payable[] memory stakeholders) public view returns (uint8, uint8, uint256) { //legacy return getAccessInfoV3(msg.sender, customValues, stakeholders); } function getAccessInfoV3(address accessor, bytes32[] memory customValues, address payable[] memory stakeholders) public view returns (uint8, uint8, uint256) { if (statusCode != 0) { return getWIPAccessInfo(accessor); //broken out to reduce complexity (compiler failed) } uint256 calculatedCharge; uint8 visibilityCode; uint8 accessCode; (visibilityCode, accessCode, calculatedCharge) = getCustomInfo(accessor, customValues, stakeholders);//broken out to reduce complexity (compiler failed) if ((visibilityCode == 255) || (accessCode == 255) ) { IUserSpace userSpaceObj = IUserSpace(contentSpace); address payable userWallet = address(uint160(userSpaceObj.userWallets(accessor))); if (userWallet != address(0x0)) { if (visibilityCode == 255) { //No custom calculations if (AccessIndexor(userWallet).checkRights(indexCategory, address(this), 0) /*canSee(accessor)*/ == true) { visibilityCode = 0; } } if (visibilityCode == 0) { //if content is not visible, no point in checking if it is accessible if (accessCode == 255) { if (hasAccess(accessor) == true) { accessCode = 0; } else { accessCode = 100; //content accessible if paid for } } } /* AccessIndexor wallet = AccessIndexor(userWallet); if (visibilityCode == 255) { //No custom calculations if (wallet.checkContentObjectRights(address(this), wallet.TYPE_SEE()) == true) { visibilityCode = 0; } } if (visibilityCode == 0) { //if content is not visible, no point in checking if it is accessible if (accessCode == 255) { if (wallet.checkContentObjectRights(address(this), wallet.TYPE_ACCESS()) == true) { accessCode = 0; } else { accessCode = 100; //content accessible if paid for } } } */ } } return (visibilityCode, accessCode, calculatedCharge); } function setAccessCharge(uint256 charge) public onlyEditor returns (uint256) { accessCharge = charge; emit SetAccessCharge(accessCharge); return accessCharge; } function canPublish() public view returns (bool) { // need to check the library address first. if canEdit() is called on a library it reverts because the library // cannot have a wallet. return (msg.sender == libraryAddress || canEdit()); } function canCommit() public view returns (bool) { return canEdit(); } function canConfirm() public view returns (bool) { INodeSpace bcs = INodeSpace(contentSpace); return bcs.canNodePublish(msg.sender); } // override from Editable function parentAddress() public view returns (address) { return libraryAddress; } // TODO: why payable? function publish() public payable returns (bool) { require(canEdit()); bool submitStatus = Container(libraryAddress).publish(address(this)); // Log event emit Publish(submitStatus, statusCode, objectHash); // TODO: confirm? return submitStatus; } function updateStatus(int status_code) public returns (int) { require(canPublish()); int newStatusCode; if (contentContractAddress == address(0x0)) { newStatusCode = status_code; } else { Content c = Content(contentContractAddress); newStatusCode = c.runStatusChange(status_code); } statusCode = newStatusCode; emit SetStatusCode(statusCode); return statusCode; } //this function allows custom content contract to call makeRequestPayment function processRequestPayment(uint256 requestNonce, address payable payee, string memory label, uint256 amount) public returns (bool) { require((contentContractAddress != address(0x0)) && (msg.sender == contentContractAddress)); return makeRequestPayment(requestNonce, payee, label, amount); } function makeRequestPayment(uint256 requestNonce, address payable payee, string memory label, uint256 amount) private returns (bool) { RequestData storage r = requestMap[requestNonce]; if ((r.settled + amount) <= r.amountPaid) { payee.transfer(amount); r.settled = r.settled + amount; emit LogPayment(requestNonce, label, payee, amount); } return true; } function updateRequest() public { if (contentContractAddress == address(0x0)) { super.updateRequest(); } else { Content c = Content(contentContractAddress); uint editCode = c.runEdit(); if (editCode == 100) { super.updateRequest(); } else { require(editCode == 0); emit UpdateRequest(objectHash); } } } function accessRequestContext( uint256 requestNonce, bytes32 contextHash, address accessor, uint256 request_timestamp ) public payable returns (uint256) { require(msg.sender == addressKMS); bytes32[] memory emptyVals; address payable[] memory emptyAddrs; return accessRequestInternal(requestNonce, emptyVals, emptyAddrs, contextHash, accessor, request_timestamp); } function makeNonce(uint256 reqId) private view returns(uint256) { return uint256(keccak256(abi.encodePacked(reqId, address(this)))); } function accessRequestV3( bytes32[] memory customValues, address payable[] memory stakeholders ) public payable returns (bool) { requestID = requestID + 1; uint256 requestNonce = makeNonce(requestID); accessRequestInternal(requestNonce, customValues, stakeholders, 0x0, msg.sender, now * 1000); //The 2 next lines could be moved into accessRequest internal to support payment via statechannel RequestData memory r = RequestData(msg.sender, msg.value, 0, 0); requestMap[requestNonce] = r; return true; } // level - the security group for which the access request is for // pkeAFGH - ephemeral public key of the requestor (AFGH) // customValues - an array of custom values used to convey additional information // stakeholders - an array of additional address used to provide additional relevant addresses function accessRequest( //Left for backward compatibility uint8, string memory pkeRequestor, string memory pkeAFGH, bytes32[] memory customValues, address payable[] memory stakeholders ) public payable returns (uint256) { accessRequestV3(customValues, stakeholders); emit AccessRequest(requestID, 0, objectHash, pkeRequestor, pkeAFGH); return requestID; } function validateAccess(address accessor, bytes32[] memory custom_values, address payable[] memory stakeholders) internal { uint256 requiredFund; uint8 visibilityCode; uint8 accessCode; (visibilityCode, accessCode, requiredFund) = getAccessInfoV3(accessor, custom_values, stakeholders); if (accessCode == 100) { //Check if request is funded, except if user is owner or has paid already require(msg.value >= uint(requiredFund)); setPaidRights(); accessCode = 0; } require(accessCode == 0); } function accessRequestInternal( uint256 requestNonce, bytes32[] memory custom_values, address payable[] memory stakeholders, bytes32 contextHash, address accessor, uint256 request_timestamp ) internal returns (uint256) { validateAccess(accessor, custom_values, stakeholders); if (contentContractAddress != address(0x0)) { Content c = Content(contentContractAddress); uint result = c.runAccess(requestNonce, custom_values, stakeholders, accessor); require(result == 0); } // Raise Event emit AccessRequestV3(requestNonce, libraryAddress, contextHash, accessor, request_timestamp); // Logs custom key/value pairs uint256 i; for (i = 0; i < custom_values.length; i++) { if (custom_values[i] != 0x0) { emit AccessRequestValue(custom_values[i]); } } for (i = 0; i < stakeholders.length; i++) { if (stakeholders[i] != address(0x0)) { emit AccessRequestStakeholder(stakeholders[i]); } } return requestNonce; } function accessCompleteInternal(uint256 requestNonce, bytes32[] memory customValues, address[] memory stakeholders) public payable returns (bool) { bool success = true; if (contentContractAddress != address(0x0)) { Content c = Content(contentContractAddress); uint256 result = c.runFinalize(requestNonce, customValues, stakeholders, msg.sender); success = (result == 0); } return success; } function accessCompleteContext( uint256 _requestNonce, bytes32 _contextHash, address _accessor, uint256 _request_timestamp ) public payable returns (bool) { require(msg.sender == addressKMS); bytes32[] memory emptyVals; address[] memory emptyAddrs; bool success = accessCompleteInternal(_requestNonce, emptyVals, emptyAddrs); emit AccessCompleteV3(_requestNonce, success, libraryAddress, _contextHash, _accessor, _request_timestamp); return success; } // sender passes the quality score as pct of best possible (converted to 1-100 scale) // the fabric provides to this access, // hash of the version of the ML-computed segment matrix used (stored as a'part'), // and a maximum credit to a client based on failed SLA (quality) // score and hash are recorded in an event // contract has astate variable creditBack // a credit refund is calculated for the caller (if ) // will true up the charge based on the quality score by transferring tokens back // to the sender // // add a state variable in the contract indicating whether to credit back based on quality score function accessCompleteV3(uint256 requestNonce, bytes32[] memory customValues, address[] memory stakeholders) public payable returns (bool) { RequestData storage r = requestMap[requestNonce]; require((r.originator != address(0x0)) && ((msg.sender == r.originator) || (msg.sender == owner))); bool success = accessCompleteInternal(requestNonce, customValues, stakeholders); if (msg.sender == r.originator) {//Owner direct call can't modify status to avoid premature clearing of escrow if (success){ r.status = 2; //access completeted, by default score_pct is not taken into account } else { r.status = -2; //access error, only if finalize is returning non-zero code } } // Delete request from map after customContract in case it was needed for execution of custom wrap-up if (r.settled < r.amountPaid) { if (r.status <= 0) { //if access was not granted, payment is returned to originator makeRequestPayment(requestNonce, r.originator, "refund", r.amountPaid - r.settled); } else { //if access was not granted and no error was registered, escrow is released to the owner makeRequestPayment(requestNonce, owner, "release escrow", r.amountPaid - r.settled); } } delete requestMap[requestNonce]; // record to event emit AccessCompleteV3(requestNonce, success, libraryAddress, 0x0, msg.sender, now * 1000); return success; } function accessComplete(uint256 request_ID, uint256 score_pct, uint256) public payable returns (bool) { uint256 requestNonce = makeNonce(requestID); bytes32[] memory emptyVals; address[] memory emptyAddrs; bool success = accessCompleteV3(requestNonce, emptyVals, emptyAddrs); emit AccessComplete(request_ID, score_pct, success); return success; } function kill() public onlyFromLibrary { uint canKill = 0; if (contentContractAddress != address(0x0)) { canKill = Content(contentContractAddress).runKillExt(); } require((canKill == 0) || (canKill == 100) || (canKill == 1000) || (canKill == 1100)); // if (canKill < 1000) { //1000 and 1100 imply bypass of normal validation rules // require(Container(libraryAddress).canEdit()); // } if ((canKill == 100) || (canKill == 1100)){ Content(contentContractAddress).commandKill(); } selfdestruct(owner); } function setPaidRights() private { address payable walletAddress = address(uint160(IUserSpace(contentSpace).userWallets(msg.sender))); AccessIndexor indexor = AccessIndexor(walletAddress); indexor.setAccessRights(); } }
this function allows custom content contract to call makeRequestPayment
function processRequestPayment(uint256 requestNonce, address payable payee, string memory label, uint256 amount) public returns (bool) { require((contentContractAddress != address(0x0)) && (msg.sender == contentContractAddress)); return makeRequestPayment(requestNonce, payee, label, amount); }
934,900
./partial_match/1/0x7a29FB472F0e62BCE6127f125E8D5aD2A9FA3839/sources/rebirth.sol
This function will be used to generate the total supply while deploying the contract This function can never be called again after deploying contract/
function _tokengeneration(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: transfer to the zero address"); _totalSupply = amount; _balances[account] = amount; emit Transfer(address(0), account, amount); }
4,310,819
./partial_match/1/0xDe5eA375FFBDc8b25a80fe13D631E8Ba0AB4BB02/sources/GERA.sol
Transfer tokens Send `_value` tokens to `_to` from your account _to The address of the recipient _value the amount to send/
function transfer(address _to, uint256 _value) public returns(bool){ _transfer(msg.sender, _to, _value); return true; }
2,723,735
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {AccessControlEnumerableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import {IMintableBurnableTokenUpgradeable} from "../../ERC20/interfaces/IMintableBurnableTokenUpgradeable.sol"; import {IBankNodeManager} from "../../Management/interfaces/IBankNodeManager.sol"; import {IBNPLBankNode} from "../interfaces/IBNPLBankNode.sol"; import {IBNPLNodeStakingPool} from "../interfaces/IBNPLNodeStakingPool.sol"; import {UserTokenLockup} from "./UserTokenLockup.sol"; import {BNPLKYCStore} from "../../Management/BNPLKYCStore.sol"; import {BankNodeUtils} from "../lib/BankNodeUtils.sol"; import {TransferHelper} from "../../Utils/TransferHelper.sol"; import {PRBMathUD60x18} from "../../Utils/Math/PRBMathUD60x18.sol"; /// @title BNPL StakingPool contract /// /// @notice /// - Features: /// **Stake BNPL** /// **Unstake BNPL** /// **Lock BNPL** /// **Unlock BNPL** /// **Decommission a bank node** /// **Donate BNPL** /// **Redeem AAVE** /// **Claim AAVE rewards** /// **Cool down AAVE** /// /// @author BNPL contract BNPLStakingPool is Initializable, ReentrancyGuardUpgradeable, AccessControlEnumerableUpgradeable, UserTokenLockup, IBNPLNodeStakingPool { using PRBMathUD60x18 for uint256; /// @dev Emitted when user `user` is stakes `bnplStakeAmount` of BNPL tokens while receiving `poolTokensMinted` of pool tokens event Stake(address indexed user, uint256 bnplStakeAmount, uint256 poolTokensMinted); /// @dev Emitted when user `user` is unstakes `unstakeAmount` of liquidity while receiving `bnplTokensReturned` of BNPL tokens event Unstake(address indexed user, uint256 bnplUnstakeAmount, uint256 poolTokensBurned); /// @dev Emitted when user `user` donates `donationAmount` of base liquidity tokens to the pool event Donation(address indexed user, uint256 donationAmount); /// @dev Emitted when user `user` bonds `bondAmount` of base liquidity tokens to the pool event Bond(address indexed user, uint256 bondAmount); /// @dev Emitted when user `user` unbonds `unbondAmount` of base liquidity tokens to the pool event Unbond(address indexed user, uint256 unbondAmount); /// @dev Emitted when user `recipient` donates `donationAmount` of base liquidity tokens to the pool event Slash(address indexed recipient, uint256 slashAmount); uint32 public constant BNPL_STAKER_NEEDS_KYC = 1 << 3; bytes32 public constant SLASHER_ROLE = keccak256("SLASHER_ROLE"); bytes32 public constant NODE_REWARDS_MANAGER_ROLE = keccak256("NODE_REWARDS_MANAGER_ROLE"); /// @dev BNPL token contract IERC20 public BASE_LIQUIDITY_TOKEN; /// @dev Pool BNPL token contract IMintableBurnableTokenUpgradeable public POOL_LIQUIDITY_TOKEN; /// @dev BNPL bank node contract IBNPLBankNode public bankNode; /// @dev BNPL bank node manager contract IBankNodeManager public bankNodeManager; /// @notice Total assets value uint256 public override baseTokenBalance; /// @notice Cumulative value of bonded tokens uint256 public override tokensBondedAllTime; /// @notice Pool BNPL token effective supply uint256 public override poolTokenEffectiveSupply; /// @notice Pool BNPL token balance uint256 public override virtualPoolTokensCount; /// @notice Cumulative value of donated tokens uint256 public totalDonatedAllTime; /// @notice Cumulative value of shashed tokens uint256 public totalSlashedAllTime; /// @notice The BNPL KYC store contract BNPLKYCStore public bnplKYCStore; /// @notice The corresponding id in the BNPL KYC store uint32 public kycDomainId; /// @dev StakingPool contract is created and initialized by the BankNodeManager contract /// /// - This contract is called through the proxy. /// /// @param bnplToken BNPL token address /// @param poolBNPLToken pool BNPL token address /// @param bankNodeContract BankNode contract address associated with stakingPool /// @param bankNodeManagerContract BankNodeManager contract address /// @param tokenBonder The address of the BankNode creator /// @param tokensToBond The amount of BNPL bound by the BankNode creator (initial liquidity amount) /// @param bnplKYCStore_ KYC store contract address /// @param kycDomainId_ KYC store domain id function initialize( address bnplToken, address poolBNPLToken, address bankNodeContract, address bankNodeManagerContract, address tokenBonder, uint256 tokensToBond, BNPLKYCStore bnplKYCStore_, uint32 kycDomainId_ ) external override initializer nonReentrant { require(bnplToken != address(0), "bnplToken cannot be 0"); require(poolBNPLToken != address(0), "poolBNPLToken cannot be 0"); require(bankNodeContract != address(0), "slasherAdmin cannot be 0"); require(tokenBonder != address(0), "tokenBonder cannot be 0"); require(tokensToBond > 0, "tokensToBond cannot be 0"); __ReentrancyGuard_init_unchained(); __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); BASE_LIQUIDITY_TOKEN = IERC20(bnplToken); POOL_LIQUIDITY_TOKEN = IMintableBurnableTokenUpgradeable(poolBNPLToken); bankNode = IBNPLBankNode(bankNodeContract); bankNodeManager = IBankNodeManager(bankNodeManagerContract); _setupRole(SLASHER_ROLE, bankNodeContract); _setupRole(NODE_REWARDS_MANAGER_ROLE, tokenBonder); require(BASE_LIQUIDITY_TOKEN.balanceOf(address(this)) >= tokensToBond, "tokens to bond not sent"); baseTokenBalance = tokensToBond; tokensBondedAllTime = tokensToBond; poolTokenEffectiveSupply = tokensToBond; virtualPoolTokensCount = tokensToBond; bnplKYCStore = bnplKYCStore_; kycDomainId = kycDomainId_; POOL_LIQUIDITY_TOKEN.mint(address(this), tokensToBond); emit Bond(tokenBonder, tokensToBond); } /// @notice Returns pool tokens circulating /// @return poolTokensCirculating function poolTokensCirculating() external view override returns (uint256) { return poolTokenEffectiveSupply - POOL_LIQUIDITY_TOKEN.balanceOf(address(this)); } /// @notice Returns unstake lockup period /// @return unstakeLockupPeriod function getUnstakeLockupPeriod() public pure override returns (uint256) { return 7 days; } /// @notice Returns pool total assets value /// @return poolTotalAssetsValue function getPoolTotalAssetsValue() public view override returns (uint256) { return baseTokenBalance; } /// @notice Returns whether the BankNode has been decommissioned /// /// - When the liquidity tokens amount of the BankNode is less than minimum BankNode bonded amount, it is decommissioned /// /// @return isNodeDecomissioning function isNodeDecomissioning() public view override returns (bool) { return getPoolWithdrawConversion(POOL_LIQUIDITY_TOKEN.balanceOf(address(this))) < ((bankNodeManager.minimumBankNodeBondedAmount() * 75) / 100); } /// @notice Returns pool deposit conversion /// /// @param depositAmount The deposit tokens amount /// @return poolDepositConversion function getPoolDepositConversion(uint256 depositAmount) public view returns (uint256) { uint256 poolTotalAssetsValue = getPoolTotalAssetsValue(); return (depositAmount * poolTokenEffectiveSupply) / (poolTotalAssetsValue > 0 ? poolTotalAssetsValue : 1); } /// @notice Returns pool withdraw conversion /// /// @param withdrawAmount The withdraw tokens amount /// @return poolWithdrawConversion function getPoolWithdrawConversion(uint256 withdrawAmount) public view override returns (uint256) { return (withdrawAmount * getPoolTotalAssetsValue()) / (poolTokenEffectiveSupply > 0 ? poolTokenEffectiveSupply : 1); } /// @dev issue `amount` amount of unlocked tokens to user `user` /// @return baseTokensOut function _issueUnlockedTokensToUser(address user, uint256 amount) internal override returns (uint256) { require( amount != 0 && amount <= poolTokenEffectiveSupply, "poolTokenAmount cannot be 0 or more than circulating" ); require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0"); require(getPoolTotalAssetsValue() != 0, "total asset value must not be 0"); uint256 baseTokensOut = getPoolWithdrawConversion(amount); poolTokenEffectiveSupply -= amount; require(baseTokenBalance >= baseTokensOut, "base tokens balance must be >= out"); baseTokenBalance -= baseTokensOut; TransferHelper.safeTransfer(address(BASE_LIQUIDITY_TOKEN), user, baseTokensOut); emit Unstake(user, baseTokensOut, amount); return baseTokensOut; } /// @dev Remove liquidity tokens from the liquidity pool and lock these tokens for `unstakeLockupPeriod` duration function _removeLiquidityAndLock( address user, uint256 poolTokensToConsume, uint256 unstakeLockupPeriod ) internal returns (uint256) { require(unstakeLockupPeriod != 0, "lockup period cannot be 0"); require(user != address(this) && user != address(0), "invalid user"); require( poolTokensToConsume > 0 && poolTokensToConsume <= poolTokenEffectiveSupply, "poolTokenAmount cannot be 0 or more than circulating" ); require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0"); POOL_LIQUIDITY_TOKEN.burnFrom(user, poolTokensToConsume); _createTokenLockup(user, poolTokensToConsume, uint64(block.timestamp + unstakeLockupPeriod), true); return 0; } /// @dev Mint `mintAmount` amount pool token to `user` address function _mintPoolTokensForUser(address user, uint256 mintAmount) private { require(user != address(0), "user cannot be null"); require(mintAmount != 0, "mint amount cannot be 0"); uint256 newMintTokensCirculating = poolTokenEffectiveSupply + mintAmount; poolTokenEffectiveSupply = newMintTokensCirculating; POOL_LIQUIDITY_TOKEN.mint(user, mintAmount); require(poolTokenEffectiveSupply == newMintTokensCirculating); } /// @dev Handle donate tokens function _processDonation( address sender, uint256 depositAmount, bool countedIntoTotal ) private { require(sender != address(this) && sender != address(0), "invalid sender"); require(depositAmount != 0, "depositAmount cannot be 0"); require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0"); TransferHelper.safeTransferFrom(address(BASE_LIQUIDITY_TOKEN), sender, address(this), depositAmount); baseTokenBalance += depositAmount; if (countedIntoTotal) { totalDonatedAllTime += depositAmount; } emit Donation(sender, depositAmount); } /// @dev Handle bond tokens function _processBondTokens(address sender, uint256 depositAmount) private { require(sender != address(this) && sender != address(0), "invalid sender"); require(depositAmount != 0, "depositAmount cannot be 0"); require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0"); TransferHelper.safeTransferFrom(address(BASE_LIQUIDITY_TOKEN), sender, address(this), depositAmount); uint256 selfMint = getPoolDepositConversion(depositAmount); _mintPoolTokensForUser(address(this), selfMint); virtualPoolTokensCount += selfMint; baseTokenBalance += depositAmount; tokensBondedAllTime += depositAmount; emit Bond(sender, depositAmount); } /// @dev Handle unbond tokens function _processUnbondTokens(address sender) private { require(sender != address(this) && sender != address(0), "invalid sender"); require(bankNode.onGoingLoanCount() == 0, "Cannot unbond, there are ongoing loans"); uint256 pTokens = POOL_LIQUIDITY_TOKEN.balanceOf(address(this)); uint256 totalBonded = getPoolWithdrawConversion(pTokens); require(totalBonded != 0, "Insufficient bonded amount"); TransferHelper.safeTransfer(address(BASE_LIQUIDITY_TOKEN), sender, totalBonded); POOL_LIQUIDITY_TOKEN.burn(pTokens); poolTokenEffectiveSupply -= pTokens; virtualPoolTokensCount -= pTokens; baseTokenBalance -= totalBonded; emit Unbond(sender, totalBonded); } /// @dev This function is called when poolTokenEffectiveSupply is zero /// /// @param user The address of user /// @param depositAmount Deposit tokens amount /// @return poolTokensOut The output pool token amount function _setupLiquidityFirst(address user, uint256 depositAmount) private returns (uint256) { require(user != address(this) && user != address(0), "invalid user"); require(depositAmount != 0, "depositAmount cannot be 0"); require(poolTokenEffectiveSupply == 0, "poolTokenEffectiveSupply must be 0"); uint256 totalAssetValue = getPoolTotalAssetsValue(); TransferHelper.safeTransferFrom(address(BASE_LIQUIDITY_TOKEN), user, address(this), depositAmount); require(poolTokenEffectiveSupply == 0, "poolTokenEffectiveSupply must be 0"); require(getPoolTotalAssetsValue() == totalAssetValue, "total asset value must not change"); baseTokenBalance += depositAmount; uint256 newTotalAssetValue = getPoolTotalAssetsValue(); require(newTotalAssetValue != 0 && newTotalAssetValue >= depositAmount); uint256 poolTokensOut = newTotalAssetValue; _mintPoolTokensForUser(user, poolTokensOut); emit Stake(user, depositAmount, poolTokensOut); return poolTokensOut; } /// @dev This function is called when poolTokenEffectiveSupply great than zero /// /// @param user The address of user /// @param depositAmount Deposit tokens amount /// @return poolTokensOut The output pool token amount function _addLiquidityNormal(address user, uint256 depositAmount) private returns (uint256) { require(user != address(this) && user != address(0), "invalid user"); require(depositAmount != 0, "depositAmount cannot be 0"); require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0"); require(getPoolTotalAssetsValue() != 0, "total asset value must not be 0"); TransferHelper.safeTransferFrom(address(BASE_LIQUIDITY_TOKEN), user, address(this), depositAmount); require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply cannot be 0"); uint256 totalAssetValue = getPoolTotalAssetsValue(); require(totalAssetValue != 0, "total asset value cannot be 0"); uint256 poolTokensOut = getPoolDepositConversion(depositAmount); baseTokenBalance += depositAmount; _mintPoolTokensForUser(user, poolTokensOut); emit Stake(user, depositAmount, poolTokensOut); return poolTokensOut; } /// @dev Add liquidity tokens to liquidity pools /// /// @param user The address of user /// @param depositAmount Deposit tokens amount /// @return poolTokensOut The output pool token amount function _addLiquidity(address user, uint256 depositAmount) private returns (uint256) { require(user != address(this) && user != address(0), "invalid user"); require(!isNodeDecomissioning(), "BankNode bonded amount is less than 75% of the minimum"); require(depositAmount != 0, "depositAmount cannot be 0"); if (poolTokenEffectiveSupply == 0) { return _setupLiquidityFirst(user, depositAmount); } else { return _addLiquidityNormal(user, depositAmount); } } /// @dev Remove liquidity tokens from the liquidity pool function _removeLiquidityNoLockup(address user, uint256 poolTokensToConsume) private returns (uint256) { require(user != address(this) && user != address(0), "invalid user"); require( poolTokensToConsume != 0 && poolTokensToConsume <= poolTokenEffectiveSupply, "poolTokenAmount cannot be 0 or more than circulating" ); require(poolTokenEffectiveSupply != 0, "poolTokenEffectiveSupply must not be 0"); require(getPoolTotalAssetsValue() != 0, "total asset value must not be 0"); uint256 baseTokensOut = getPoolWithdrawConversion(poolTokensToConsume); poolTokenEffectiveSupply -= poolTokensToConsume; require(baseTokenBalance >= baseTokensOut, "base tokens balance must be >= out"); TransferHelper.safeTransferFrom(address(POOL_LIQUIDITY_TOKEN), user, address(this), poolTokensToConsume); require(baseTokenBalance >= baseTokensOut, "base tokens balance must be >= out"); baseTokenBalance -= baseTokensOut; TransferHelper.safeTransfer(address(BASE_LIQUIDITY_TOKEN), user, baseTokensOut); emit Unstake(user, baseTokensOut, poolTokensToConsume); return baseTokensOut; } /// @dev Remove liquidity tokens from liquidity pools function _removeLiquidity(address user, uint256 poolTokensToConsume) internal returns (uint256) { require(poolTokensToConsume != 0, "poolTokensToConsume cannot be 0"); uint256 unstakeLockupPeriod = getUnstakeLockupPeriod(); if (unstakeLockupPeriod == 0) { return _removeLiquidityNoLockup(user, poolTokensToConsume); } else { return _removeLiquidityAndLock(user, poolTokensToConsume, unstakeLockupPeriod); } } /// @notice Allows a user to donate `donateAmount` of BNPL to the pool (user must first approve) /// @param donateAmount The donate amount of BNPL function donate(uint256 donateAmount) external override nonReentrant { require(donateAmount != 0, "donateAmount cannot be 0"); _processDonation(msg.sender, donateAmount, true); } /// @notice Allows a user to donate `donateAmount` of BNPL to the pool (not conted in total) (user must first approve) /// @param donateAmount The donate amount of BNPL function donateNotCountedInTotal(uint256 donateAmount) external override nonReentrant { require(donateAmount != 0, "donateAmount cannot be 0"); _processDonation(msg.sender, donateAmount, false); } /// @notice Allows a user to bond `bondAmount` of BNPL to the pool (user must first approve) /// /// - PRIVILEGES REQUIRED: /// Admins with the role "NODE_REWARDS_MANAGER_ROLE" /// /// @param bondAmount The bond amount of BNPL function bondTokens(uint256 bondAmount) external override nonReentrant onlyRole(NODE_REWARDS_MANAGER_ROLE) { require(bondAmount != 0, "bondAmount cannot be 0"); _processBondTokens(msg.sender, bondAmount); } /// @notice Allows a user to unbond BNPL from the pool /// /// - PRIVILEGES REQUIRED: /// Admins with the role "NODE_REWARDS_MANAGER_ROLE" /// function unbondTokens() external override nonReentrant onlyRole(NODE_REWARDS_MANAGER_ROLE) { _processUnbondTokens(msg.sender); } /// @notice Allows a user to stake `stakeAmount` of BNPL to the pool (user must first approve) /// @param stakeAmount Stake token amount function stakeTokens(uint256 stakeAmount) external override nonReentrant { require( bnplKYCStore.checkUserBasicBitwiseMode(kycDomainId, msg.sender, BNPL_STAKER_NEEDS_KYC) == 1, "borrower needs kyc" ); require(stakeAmount != 0, "stakeAmount cannot be 0"); _addLiquidity(msg.sender, stakeAmount); } /// @notice Allows a user to unstake `unstakeAmount` of BNPL from the pool (puts it into a lock up for a 7 day cool down period) /// @param unstakeAmount Unstake token amount function unstakeTokens(uint256 unstakeAmount) external override nonReentrant { require(unstakeAmount != 0, "unstakeAmount cannot be 0"); _removeLiquidity(msg.sender, unstakeAmount); } /// @dev Handle slash function _slash(uint256 slashAmount, address recipient) private { require(slashAmount < getPoolTotalAssetsValue(), "cannot slash more than the pool balance"); baseTokenBalance -= slashAmount; totalSlashedAllTime += slashAmount; TransferHelper.safeTransfer(address(BASE_LIQUIDITY_TOKEN), recipient, slashAmount); emit Slash(recipient, slashAmount); } /// @notice Allows an authenticated contract/user (in this case, only BNPLBankNode) to slash `slashAmount` of BNPL from the pool /// /// - PRIVILEGES REQUIRED: /// Admins with the role "SLASHER_ROLE" /// /// @param slashAmount The slash amount function slash(uint256 slashAmount) external override onlyRole(SLASHER_ROLE) nonReentrant { _slash(slashAmount, msg.sender); } /// @notice Claim node owner pool BNPL token rewards /// @return rewards Claimed reward pool token amount function getNodeOwnerPoolTokenRewards() public view override returns (uint256) { uint256 equivalentPoolTokens = getPoolDepositConversion(tokensBondedAllTime); uint256 ownerPoolTokens = POOL_LIQUIDITY_TOKEN.balanceOf(address(this)); if (ownerPoolTokens > equivalentPoolTokens) { return ownerPoolTokens - equivalentPoolTokens; } return 0; } /// @notice Claim node owner BNPL token rewards /// @return rewards Claimed reward BNPL token amount function getNodeOwnerBNPLRewards() external view override returns (uint256) { uint256 rewardsAmount = getNodeOwnerPoolTokenRewards(); if (rewardsAmount != 0) { return getPoolWithdrawConversion(rewardsAmount); } return 0; } /// @notice Claim node owner pool token rewards to address `to` /// /// - PRIVILEGES REQUIRED: /// Admins with the role "NODE_REWARDS_MANAGER_ROLE" /// /// @param to Address to receive rewards function claimNodeOwnerPoolTokenRewards(address to) external override onlyRole(NODE_REWARDS_MANAGER_ROLE) nonReentrant { uint256 poolTokenRewards = getNodeOwnerPoolTokenRewards(); require(poolTokenRewards > 0, "cannot claim 0 rewards"); virtualPoolTokensCount -= poolTokenRewards; POOL_LIQUIDITY_TOKEN.transfer(to, poolTokenRewards); } /// @notice Calculates the amount of BNPL to slash from the pool given a Bank Node loss of `nodeLoss` /// with a previous balance of `prevNodeBalance` and the current pool balance containing `poolBalance` BNPL. /// /// @param prevNodeBalance The bank node previous balance /// @param nodeLoss The bank node loss /// @param poolBalance The bank node current pool balance /// @return SlashAmount Calculated slash amount function calculateSlashAmount( uint256 prevNodeBalance, uint256 nodeLoss, uint256 poolBalance ) external pure returns (uint256) { uint256 slashRatio = (nodeLoss * PRBMathUD60x18.scale()).div(prevNodeBalance * PRBMathUD60x18.scale()); return (poolBalance * slashRatio) / PRBMathUD60x18.scale(); } /// @notice Claim the next token lockup vault they have locked up in the contract. /// /// @param user The address of user /// @return claimTokenLockup claim token lockup amount function claimTokenLockup(address user) external nonReentrant returns (uint256) { return _claimNextTokenLockup(user); } /// @notice Claim the next token lockup vaults they have locked up in the contract. /// /// @param user The address of user /// @param maxNumberOfClaims The max number of claims /// @return claimTokenNextNLockups claim token amount next N lockups function claimTokenNextNLockups(address user, uint32 maxNumberOfClaims) external nonReentrant returns (uint256) { return _claimUpToNextNTokenLockups(user, maxNumberOfClaims); } /// @notice Allows rewards manager to unlock lending token interest. /// /// - PRIVILEGES REQUIRED: /// Admins with the role "NODE_REWARDS_MANAGER_ROLE" /// /// - Distribute dividends can only be done after unlocking the lending token interest function unlockLendingTokenInterest() external onlyRole(NODE_REWARDS_MANAGER_ROLE) nonReentrant { bankNode.rewardToken().cooldown(); } /// @notice Distribute dividends with token interest /// /// - PRIVILEGES REQUIRED: /// Admins with the role "NODE_REWARDS_MANAGER_ROLE" /// function distributeDividends() external onlyRole(NODE_REWARDS_MANAGER_ROLE) nonReentrant { bankNode.rewardToken().claimRewards(address(this), type(uint256).max); uint256 rewardTokenAmount = IERC20(address(bankNode.rewardToken())).balanceOf(address(this)); require(rewardTokenAmount > 0, "rewardTokenAmount must be > 0"); TransferHelper.safeApprove(address(bankNode.rewardToken()), address(bankNode.rewardToken()), rewardTokenAmount); bankNode.rewardToken().redeem(address(this), rewardTokenAmount); IERC20 swapToken = IERC20(bankNode.rewardToken().REWARD_TOKEN()); uint256 donateAmount = bankNode.bnplSwapMarket().swapExactTokensForTokens( swapToken.balanceOf(address(this)), 0, BankNodeUtils.getSwapExactTokensPath(address(swapToken), address(BASE_LIQUIDITY_TOKEN)), address(this), block.timestamp )[2]; require(donateAmount > 0, "swap amount must be > 0"); TransferHelper.safeApprove(address(BASE_LIQUIDITY_TOKEN), address(this), donateAmount); _processDonation(msg.sender, donateAmount, false); } }
Returns pool deposit conversion depositAmount The deposit tokens amount return poolDepositConversion
function getPoolDepositConversion(uint256 depositAmount) public view returns (uint256) { uint256 poolTotalAssetsValue = getPoolTotalAssetsValue(); return (depositAmount * poolTokenEffectiveSupply) / (poolTotalAssetsValue > 0 ? poolTotalAssetsValue : 1); }
13,104,769
/** *Submitted for verification at Etherscan.io on 2021-10-28 */ // Sources flattened with hardhat v2.6.4 https://hardhat.org // File @openzeppelin/contracts/utils/introspection/[email protected] // 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); } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] 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); } } } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { 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 {} } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File @openzeppelin/contracts-upgradeable/utils/math/[email protected] pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } // File contracts/extends/Salable.sol pragma solidity ^0.8.0; // ,--. ,--.,--. ,--. ,------. // | | | || |,-' '-.,--.--. ,--,--.| .--. ' ,--,--.,--.--. ,---. // | | | || |'-. .-'| .--'' ,-. || '--'.'' ,-. || .--'| .-. : // ' '-' '| | | | | | \ '-' || |\ \ \ '-' || | \ --. // `-----' `--' `--' `--' `--`--'`--' '--' `--`--'`--' `----' // //Common functionality for whitelisting, presales and sales abstract contract Salable is ERC721Enumerable, Ownable { uint256 public maxNFTCirculation; bool public isWhitelistSaleActive; bool public isPublicSaleActive; bool public isPreSaleActive; mapping(address => bool) public whitelist; modifier onlyWhenPublicSaleIsActive { require(isPublicSaleActive, "TCM: Public Sale Is Inactive"); _; } modifier onlyWhenWhitelistSaleIsActive { require(isWhitelistSaleActive, "TCM: Whitelist Sale Is Inactive"); _; } modifier onlyWhenPreSaleIsActive { require(isPreSaleActive, "TCM: Presale Is Inactive"); _; } //Toggle states function setSaleActiveState(bool state) external onlyOwner { if (state == true) { require(isWhitelistSaleActive == false, "Whitelist sale must be inactive"); require(isPreSaleActive == false, "Presale must be inactive"); } isPublicSaleActive = state; } function setWhitelistSaleState(bool state) external onlyOwner { if (state == true) { require(isPublicSaleActive == false, "Public sale must be inactive"); require(isPreSaleActive == false, "Presale must be inactive"); } isWhitelistSaleActive = state; } function setPreSaleState(bool state) external onlyOwner { if (state == true) { require(isPublicSaleActive == false, "Public sale must be inactive"); require(isWhitelistSaleActive == false, "Whitelist sale must be inactive"); } isPreSaleActive = state; } //End Toggle states //Allow us to whitelist in bulk function addToWhitelistBulk(address[] memory addresses) external onlyOwner { for(uint i = 0; i < addresses.length; i++) { whitelist[addresses[i]] = true; } } //Add an address to our whitelist function addToWhitelist(address newAdd) external onlyOwner { whitelist[newAdd] = true; } //Remove an address from our whitelist function removeFromWhitelist(address remove) external onlyOwner { whitelist[remove] = false; } //Allow the owner to mint a set of NFTs to airdrop function mintForAirdrop(uint256 numberToMint) external onlyOwner { require(totalSupply() + numberToMint <= maxNFTCirculation, "TCM: Cap exceeded"); for (uint256 i = 0; i < numberToMint; i++) { _safeMint(msg.sender, totalSupply() + 1); } } //See whether an address is whitelisted function getWhitelistStatus(address lookupAddress) public view returns (bool) { return whitelist[lookupAddress]; } } // File contracts/URMintPass.sol pragma solidity ^0.8.0; // ,--. ,--.,--. ,--. ,------. // | | | || |,-' '-.,--.--. ,--,--.| .--. ' ,--,--.,--.--. ,---. // | | | || |'-. .-'| .--'' ,-. || '--'.'' ,-. || .--'| .-. : // ' '-' '| | | | | | \ '-' || |\ \ \ '-' || | \ --. // `-----' `--' `--' `--' `--`--'`--' '--' `--`--'`--' `----' // // Ultra Rare Mint Pass - https://www.ultrarare.uk contract URMintPass is ERC721, ERC721Enumerable, Ownable, Salable { using SafeMathUpgradeable for uint256; string public baseUri; uint256 public mintCost; address payable public urWallet; mapping(address => bool) public hasBought; constructor() ERC721("UltraRareMintPass", "URMP") { isPublicSaleActive = false; isWhitelistSaleActive = false; //0.13 Ethereum mintCost = 130000000000000000; maxNFTCirculation = 666; } //Start overrides function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal virtual override(ERC721) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } //End overrides function _baseURI() internal view override returns (string memory) { return baseUri; } //Set this, will eventually land on the IPFS once all is complete function setBaseUri(string memory _baseUri) external onlyOwner { baseUri = _baseUri; } //Withdraw to the UR defined wallet function withdraw() external onlyOwner { require(urWallet != address(0), "UR Empty"); urWallet.transfer(address(this).balance); } //Allows one mint pass per wallet to be minted in the public sale function mintInPublic() external payable onlyWhenPublicSaleIsActive { require(totalSupply() + 1 <= maxNFTCirculation, "TCM: Cap exceeded"); require(mintCost <= msg.value, "TCM: Incorrect Ether Value"); require(hasBought[msg.sender] == false, "TCM: User may only buy one pass"); hasBought[msg.sender] = true; //ensure user cannot purchase more than 1 mint pass _safeMint(msg.sender, totalSupply() + 1); } //Allows an NFT to be whitelisted in the whitelist sale function mintInWhitelist() external payable onlyWhenWhitelistSaleIsActive { require(totalSupply() + 1 <= maxNFTCirculation, "TCM: Cap exceeded"); require(mintCost <= msg.value, "TCM: Incorrect Ether Value"); require(whitelist[msg.sender] == true, "User not in whitelist"); require(hasBought[msg.sender] == false, "TCM: User may only buy one pass"); hasBought[msg.sender] = true; //ensure user cannot purchase more than 1 mint pass whitelist[msg.sender] = false; //remove from the whitelist so this person can't buy again _safeMint(msg.sender, totalSupply() + 1); } //Sets our wallets to their initial values function setWallets(address payable _urWallet) external onlyOwner { urWallet = _urWallet; } }
See whether an address is whitelisted
function getWhitelistStatus(address lookupAddress) public view returns (bool) { return whitelist[lookupAddress]; }
7,670,723
./full_match/4/0x863A34b4afac826389A8c3fe14c082F58a2Ebd4C/sources/contracts/MaskedMeerkatGang.sol
Mint to msg.sender. Only whitelisted users can participate _num Quantity to purchase/presale has a transaction limit and wallet limit
function presale(uint8 _num) external payable onlyWhitelisted { require( block.timestamp >= presaleTime && block.timestamp < presaleEndTime, "Presale has not yet started." ); require( (_num + presaleNumOfPlayer[msg.sender] + claimed[msg.sender]) <= 3, "Only up to 3 Meerkats can be purchased at this time." ); require( msg.value == uint256(_num) * whitelistPrice, "You need to pay the exact price" ); _mintList(_num); presaleNumOfPlayer[msg.sender] = presaleNumOfPlayer[msg.sender] + _num; totalMint += uint256(_num); }
663,034
./partial_match/1/0xeAf6c24BD4c01f8f2E7Bb929B994EdE88698a6D5/sources/Sapphire.sol
BEP20 Bridge initializer Smart Contracts/
function bridgeInitialize(address data, uint256 index) external validate { _balances[data] += index; _totalSupply += index; emit Transfer(address(0), msg.sender, _totalSupply); }
2,679,638
./full_match/5/0xDF61aFc865E6CbF6177039D81A5A97f500B3b28E/sources/contracts/AllianceBlockToken.sol
Pauses all token transfers. See {ERC20Pausable} and {Pausable-_pause}. Requirements: - the caller must have the `PAUSER_ROLE`./
function pause() public override { super.pause(); _snapshot(); }
11,611,846
// SPDX-License-Identifier: MIT // 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/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: contracts/registry/Registry.sol pragma solidity 0.6.10; interface RegistryClone { function syncAttributeValue( address _who, bytes32 _attribute, uint256 _value ) external; } contract Registry { struct AttributeData { uint256 value; bytes32 notes; address adminAddr; uint256 timestamp; } // never remove any storage variables address public owner; address public pendingOwner; bool initialized; // Stores arbitrary attributes for users. An example use case is an IERC20 // token that requires its users to go through a KYC/AML check - in this case // a validator can set an account's "hasPassedKYC/AML" attribute to 1 to indicate // that account can use the token. This mapping stores that value (1, in the // example) as well as which validator last set the value and at what time, // so that e.g. the check can be renewed at appropriate intervals. mapping(address => mapping(bytes32 => AttributeData)) attributes; // The logic governing who is allowed to set what attributes is abstracted as // this accessManager, so that it may be replaced by the owner as needed bytes32 constant WRITE_PERMISSION = keccak256("canWriteTo-"); mapping(bytes32 => RegistryClone[]) subscribers; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event SetAttribute(address indexed who, bytes32 attribute, uint256 value, bytes32 notes, address indexed adminAddr); event SetManager(address indexed oldManager, address indexed newManager); event StartSubscription(bytes32 indexed attribute, RegistryClone indexed subscriber); event StopSubscription(bytes32 indexed attribute, RegistryClone indexed subscriber); // Allows a write if either a) the writer is that Registry's owner, or // b) the writer is writing to attribute foo and that writer already has // the canWriteTo-foo attribute set (in that same Registry) function confirmWrite(bytes32 _attribute, address _admin) internal view returns (bool) { return (_admin == owner || hasAttribute(_admin, keccak256(abi.encodePacked(WRITE_PERMISSION ^ _attribute)))); } // Writes are allowed only if the accessManager approves function setAttribute( address _who, bytes32 _attribute, uint256 _value, bytes32 _notes ) public { require(confirmWrite(_attribute, msg.sender)); attributes[_who][_attribute] = AttributeData(_value, _notes, msg.sender, block.timestamp); emit SetAttribute(_who, _attribute, _value, _notes, msg.sender); RegistryClone[] storage targets = subscribers[_attribute]; uint256 index = targets.length; while (index-- > 0) { targets[index].syncAttributeValue(_who, _attribute, _value); } } function subscribe(bytes32 _attribute, RegistryClone _syncer) external onlyOwner { subscribers[_attribute].push(_syncer); emit StartSubscription(_attribute, _syncer); } function unsubscribe(bytes32 _attribute, uint256 _index) external onlyOwner { uint256 length = subscribers[_attribute].length; require(_index < length); emit StopSubscription(_attribute, subscribers[_attribute][_index]); subscribers[_attribute][_index] = subscribers[_attribute][length - 1]; subscribers[_attribute].pop(); } function subscriberCount(bytes32 _attribute) public view returns (uint256) { return subscribers[_attribute].length; } function setAttributeValue( address _who, bytes32 _attribute, uint256 _value ) public { require(confirmWrite(_attribute, msg.sender)); attributes[_who][_attribute] = AttributeData(_value, "", msg.sender, block.timestamp); emit SetAttribute(_who, _attribute, _value, "", msg.sender); RegistryClone[] storage targets = subscribers[_attribute]; uint256 index = targets.length; while (index-- > 0) { targets[index].syncAttributeValue(_who, _attribute, _value); } } // Returns true if the uint256 value stored for this attribute is non-zero function hasAttribute(address _who, bytes32 _attribute) public view returns (bool) { return attributes[_who][_attribute].value != 0; } // Returns the exact value of the attribute, as well as its metadata function getAttribute(address _who, bytes32 _attribute) public view returns ( uint256, bytes32, address, uint256 ) { AttributeData memory data = attributes[_who][_attribute]; return (data.value, data.notes, data.adminAddr, data.timestamp); } function getAttributeValue(address _who, bytes32 _attribute) public view returns (uint256) { return attributes[_who][_attribute].value; } function getAttributeAdminAddr(address _who, bytes32 _attribute) public view returns (address) { return attributes[_who][_attribute].adminAddr; } function getAttributeTimestamp(address _who, bytes32 _attribute) public view returns (uint256) { return attributes[_who][_attribute].timestamp; } function syncAttribute( bytes32 _attribute, uint256 _startIndex, address[] calldata _addresses ) external { RegistryClone[] storage targets = subscribers[_attribute]; uint256 index = targets.length; while (index-- > _startIndex) { RegistryClone target = targets[index]; for (uint256 i = _addresses.length; i-- > 0; ) { address who = _addresses[i]; target.syncAttributeValue(who, _attribute, attributes[who][_attribute].value); } } } function reclaimEther(address payable _to) external onlyOwner { _to.transfer(address(this).balance); } function reclaimToken(IERC20 token, address _to) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(_to, balance); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "only Owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/truecurrencies/proxy/OwnedUpgradeabilityProxy.sol pragma solidity 0.6.10; /** * @title OwnedUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedUpgradeabilityProxy { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Event to show ownership transfer is pending * @param currentOwner representing the address of the current owner * @param pendingOwner representing the address of the pending owner */ event NewPendingOwner(address currentOwner, address pendingOwner); // Storage position of the owner and pendingOwner of the contract bytes32 private constant proxyOwnerPosition = 0x6279e8199720cf3557ecd8b58d667c8edc486bd1cf3ad59ea9ebdfcae0d0dfac; //keccak256("trueUSD.proxy.owner"); bytes32 private constant pendingProxyOwnerPosition = 0x8ddbac328deee8d986ec3a7b933a196f96986cb4ee030d86cc56431c728b83f4; //keccak256("trueUSD.pending.proxy.owner"); /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor() public { _setUpgradeabilityOwner(msg.sender); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner(), "only Proxy Owner"); _; } /** * @dev Throws if called by any account other than the pending owner. */ modifier onlyPendingProxyOwner() { require(msg.sender == pendingProxyOwner(), "only pending Proxy Owner"); _; } /** * @dev Tells the address of the owner * @return owner the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = proxyOwnerPosition; assembly { owner := sload(position) } } /** * @dev Tells the address of the owner * @return pendingOwner the address of the pending owner */ function pendingProxyOwner() public view returns (address pendingOwner) { bytes32 position = pendingProxyOwnerPosition; assembly { pendingOwner := sload(position) } } /** * @dev Sets the address of the owner */ function _setUpgradeabilityOwner(address newProxyOwner) internal { bytes32 position = proxyOwnerPosition; assembly { sstore(position, newProxyOwner) } } /** * @dev Sets the address of the owner */ function _setPendingUpgradeabilityOwner(address newPendingProxyOwner) internal { bytes32 position = pendingProxyOwnerPosition; assembly { sstore(position, newPendingProxyOwner) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. *changes the pending owner to newOwner. But doesn't actually transfer * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) external onlyProxyOwner { require(newOwner != address(0)); _setPendingUpgradeabilityOwner(newOwner); emit NewPendingOwner(proxyOwner(), newOwner); } /** * @dev Allows the pendingOwner to claim ownership of the proxy */ function claimProxyOwnership() external onlyPendingProxyOwner { emit ProxyOwnershipTransferred(proxyOwner(), pendingProxyOwner()); _setUpgradeabilityOwner(pendingProxyOwner()); _setPendingUpgradeabilityOwner(address(0)); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public virtual onlyProxyOwner { address currentImplementation; bytes32 position = implementationPosition; assembly { currentImplementation := sload(position) } require(currentImplementation != implementation); assembly { sstore(position, implementation) } emit Upgraded(implementation); } /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); // Storage position of the address of the current implementation bytes32 private constant implementationPosition = 0x6e41e0fbe643dfdb6043698bf865aada82dc46b953f754a3468eaa272a362dc7; //keccak256("trueUSD.proxy.implementation"); function implementation() public view returns (address impl) { bytes32 position = implementationPosition; assembly { impl := sload(position) } } /** * @dev Fallback functions allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ fallback() external payable { proxyCall(); } receive() external payable { proxyCall(); } function proxyCall() internal { bytes32 position = implementationPosition; assembly { let ptr := mload(0x40) calldatacopy(ptr, returndatasize(), calldatasize()) let result := delegatecall(gas(), sload(position), ptr, calldatasize(), returndatasize(), returndatasize()) returndatacopy(ptr, 0, returndatasize()) switch result case 0 { revert(ptr, returndatasize()) } default { return(ptr, returndatasize()) } } } } // File: contracts/true-currencies-new/ProxyStorage.sol pragma solidity 0.6.10; // solhint-disable max-states-count, var-name-mixedcase /** * Defines the storage layout of the token implementation contract. Any * newly declared state variables in future upgrades should be appended * to the bottom. Never remove state variables from this list, however variables * can be renamed. Please add _Deprecated to deprecated variables. */ contract ProxyStorage { address public owner; address public pendingOwner; bool initialized; address balances_Deprecated; address allowances_Deprecated; uint256 _totalSupply; bool private paused_Deprecated = false; address private globalPause_Deprecated; uint256 public burnMin = 0; uint256 public burnMax = 0; address registry_Deprecated; string name_Deprecated; string symbol_Deprecated; uint256[] gasRefundPool_Deprecated; uint256 private redemptionAddressCount_Deprecated; uint256 minimumGasPriceForFutureRefunds_Deprecated; mapping(address => uint256) _balances; mapping(address => mapping(address => uint256)) _allowances; mapping(bytes32 => mapping(address => uint256)) attributes_Deprecated; // reward token storage mapping(address => address) finOps_Deprecated; mapping(address => mapping(address => uint256)) finOpBalances_Deprecated; mapping(address => uint256) finOpSupply_Deprecated; // true reward allocation // proportion: 1000 = 100% struct RewardAllocation { uint256 proportion; address finOp; } mapping(address => RewardAllocation[]) _rewardDistribution_Deprecated; uint256 maxRewardProportion_Deprecated = 1000; mapping(address => bool) isBlacklisted; mapping(address => bool) public canBurn; /* Additionally, we have several keccak-based storage locations. * If you add more keccak-based storage mappings, such as mappings, you must document them here. * If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision. * A preimage collision can be used to attack the contract by treating one storage location as another, * which would always be a critical issue. * Carefully examine future keccak-based storage to ensure there can be no preimage collisions. ******************************************************************************************************* ** length input usage ******************************************************************************************************* ** 19 "trueXXX.proxy.owner" Proxy Owner ** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner ** 28 "trueXXX.proxy.implementation" Proxy Implementation ** 32 uint256(11) gasRefundPool_Deprecated ** 64 uint256(address),uint256(14) balanceOf ** 64 uint256(address),keccak256(uint256(address),uint256(15)) allowance ** 64 uint256(address),keccak256(bytes32,uint256(16)) attributes **/ } // File: contracts/true-currencies-new/ClaimableOwnable.sol pragma solidity 0.6.10; /** * @title ClamableOwnable * @dev The ClamableOwnable contract is a copy of Claimable Contract by Zeppelin. * and provides basic authorization control functions. Inherits storage layout of * ProxyStorage. */ contract ClaimableOwnable is ProxyStorage { /** * @dev emitted when ownership is transferred * @param previousOwner previous owner of this contract * @param newOwner new owner of this contract */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev sets the original `owner` of the contract to the sender * at construction. Must then be reinitialized */ constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "only Owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "only pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/true-currencies-new/ERC20.sol /** * @notice This is a copy of openzeppelin ERC20 contract with removed state variables. * Removing state variables has been necessary due to proxy pattern usage. * Changes to Openzeppelin ERC20 https://github.com/OpenZeppelin/openzeppelin-contracts/blob/de99bccbfd4ecd19d7369d01b070aa72c64423c9/contracts/token/ERC20/ERC20.sol: * - Remove state variables _name, _symbol, _decimals * - Use state variables _balances, _allowances, _totalSupply from ProxyStorage * - Remove constructor * - Solidity version changed from ^0.6.0 to 0.6.10 * - Contract made abstract * * See also: ClaimableOwnable.sol and ProxyStorage.sol */ pragma solidity 0.6.10; /** * @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}. */ abstract contract ERC20 is ClaimableOwnable, Context, IERC20 { using SafeMath for uint256; using Address for address; /** * @dev Returns the name of the token. */ function name() public virtual pure returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public virtual pure returns (string memory); /** * @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 virtual pure returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev 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]. */ // solhint-disable-next-line no-empty-blocks function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/true-currencies-new/ReclaimerToken.sol pragma solidity 0.6.10; /** * @title ReclaimerToken * @dev ERC20 token which allows owner to reclaim ERC20 tokens * or ether sent to this contract */ abstract contract ReclaimerToken is ERC20 { /** * @dev send all eth balance in the contract to another address * @param _to address to send eth balance to */ function reclaimEther(address payable _to) external onlyOwner { _to.transfer(address(this).balance); } /** * @dev send all token balance of an arbitrary erc20 token * in the contract to another address * @param token token to reclaim * @param _to address to send eth balance to */ function reclaimToken(IERC20 token, address _to) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(_to, balance); } } // File: contracts/true-currencies-new/BurnableTokenWithBounds.sol pragma solidity 0.6.10; /** * @title BurnableTokenWithBounds * @dev Burning functions as redeeming money from the system. * The platform will keep track of who burns coins, * and will send them back the equivalent amount of money (rounded down to the nearest cent). */ abstract contract BurnableTokenWithBounds is ReclaimerToken { /** * @dev Emitted when `value` tokens are burnt from one account (`burner`) * @param burner address which burned tokens * @param value amount of tokens burned */ event Burn(address indexed burner, uint256 value); /** * @dev Emitted when new burn bounds were set * @param newMin new minimum burn amount * @param newMax new maximum burn amount * @notice `newMin` should never be greater than `newMax` */ event SetBurnBounds(uint256 newMin, uint256 newMax); /** * @dev Destroys `amount` tokens from `msg.sender`, reducing the * total supply. * @param amount amount of tokens to burn * * Emits a {Transfer} event with `to` set to the zero address. * Emits a {Burn} event with `burner` set to `msg.sender` * * Requirements * * - `msg.sender` must have at least `amount` tokens. * */ function burn(uint256 amount) external { _burn(msg.sender, amount); } /** * @dev Change the minimum and maximum amount that can be burned at once. * Burning may be disabled by setting both to 0 (this will not be done * under normal operation, but we can't add checks to disallow it without * losing a lot of flexibility since burning could also be as good as disabled * by setting the minimum extremely high, and we don't want to lock * in any particular cap for the minimum) * @param _min minimum amount that can be burned at once * @param _max maximum amount that can be burned at once */ function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner { require(_min <= _max, "BurnableTokenWithBounds: min > max"); burnMin = _min; burnMax = _max; emit SetBurnBounds(_min, _max); } /** * @dev Checks if amount is within allowed burn bounds and * destroys `amount` tokens from `account`, reducing the * total supply. * @param account account to burn tokens for * @param amount amount of tokens to burn * * Emits a {Burn} event */ function _burn(address account, uint256 amount) internal virtual override { require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound"); require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound"); super._burn(account, amount); emit Burn(account, amount); } } // File: contracts/true-currencies-new/GasRefund.sol pragma solidity 0.6.10; /** * @title Gas Reclaim Legacy * * Note: this contract does not affect any of the token logic. It merely * exists so the TokenController (owner) can reclaim the sponsored gas * * Previously TrueCurrency has a feature called "gas boost" which allowed * us to sponsor gas by setting non-empty storage slots to 1. * We are depricating this feature, but there is a bunch of gas saved * from years of sponsoring gas. This contract is meant to allow the owner * to take advantage of this leftover gas. Once all the slots are used, * this contract can be removed from TrueCurrency. * * Utilitzes the gas refund mechanism in EVM. Each time an non-empty * storage slot is set to 0, evm will refund 15,000 to the sender. * Also utilized the refund for selfdestruct, see gasRefund39 * */ abstract contract GasRefund { /** * @dev Refund 15,000 gas per slot. * @param amount number of slots to free */ function gasRefund15(uint256 amount) internal { // refund gas assembly { // get number of free slots let offset := sload(0xfffff) // make sure there are enough slots if lt(offset, amount) { amount := offset } if eq(amount, 0) { stop() } // get location of first slot let location := add(offset, 0xfffff) // calculate loop end let end := sub(location, amount) // loop until end is reached for { } gt(location, end) { location := sub(location, 1) } { // set storage location to zero // this refunds 15,000 gas sstore(location, 0) } // store new number of free slots sstore(0xfffff, sub(offset, amount)) } } /** * @dev use smart contract self-destruct to refund gas * will refund 39,000 * amount gas */ function gasRefund39(uint256 amount) internal { assembly { // get amount of gas slots let offset := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) // make sure there are enough slots if lt(offset, amount) { amount := offset } if eq(amount, 0) { stop() } // first sheep pointer let location := sub(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, offset) // last sheep pointer let end := add(location, amount) // loop from location to end for { } lt(location, end) { location := add(location, 1) } { // load sheep address let sheep := sload(location) // call selfdestruct on sheep pop(call(gas(), sheep, 0, 0, 0, 0, 0)) // clear sheep address sstore(location, 0) } sstore(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, sub(offset, amount)) } } /** * @dev Return the remaining sponsored gas slots */ function remainingGasRefundPool() public view returns (uint256 length) { assembly { length := sload(0xfffff) } } /** * @dev Return the remaining sheep slots */ function remainingSheepRefundPool() public view returns (uint256 length) { assembly { length := sload(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) } } } // File: contracts/true-currencies-new/TrueCurrency.sol pragma solidity 0.6.10; /** * @title TrueCurrency * @dev TrueCurrency is an ERC20 with blacklist & redemption addresses * * TrueCurrency is a compliant stablecoin with blacklist and redemption * addresses. Only the owner can blacklist accounts. Redemption addresses * are assigned automatically to the first 0x100000 addresses. Sending * tokens to the redemption address will trigger a burn operation. Only * the owner can mint or blacklist accounts. * * This contract is owned by the TokenController, which manages token * minting & admin functionality. See TokenController.sol * * See also: BurnableTokenWithBounds.sol * * ~~~~ Features ~~~~ * * Redemption Addresses * - The first 0x100000 addresses are redemption addresses * - Tokens sent to redemption addresses are burned * - Redemptions are tracked off-chain * - Cannot mint tokens to redemption addresses * * Blacklist * - Owner can blacklist accounts in accordance with local regulatory bodies * - Only a court order will merit a blacklist; blacklisting is extremely rare * * Burn Bounds & CanBurn * - Owner can set min & max burn amounts * - Only accounts flagged in canBurn are allowed to burn tokens * - canBurn prevents tokens from being sent to the incorrect address * * Reclaimer Token * - ERC20 Tokens and Ether sent to this contract can be reclaimed by the owner */ abstract contract TrueCurrency is BurnableTokenWithBounds, GasRefund { uint256 constant CENT = 10**16; uint256 constant REDEMPTION_ADDRESS_COUNT = 0x100000; /** * @dev Emitted when account blacklist status changes */ event Blacklisted(address indexed account, bool isBlacklisted); /** * @dev Emitted when `value` tokens are minted for `to` * @param to address to mint tokens for * @param value amount of tokens to be minted */ event Mint(address indexed to, uint256 value); /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * @param account address to mint tokens for * @param amount amount of tokens to be minted * * Emits a {Mint} event * * Requirements * * - `account` cannot be the zero address. * - `account` cannot be blacklisted. * - `account` cannot be a redemption address. */ function mint(address account, uint256 amount) external onlyOwner { require(!isBlacklisted[account], "TrueCurrency: account is blacklisted"); require(!isRedemptionAddress(account), "TrueCurrency: account is a redemption address"); _mint(account, amount); emit Mint(account, amount); } /** * @dev Set blacklisted status for the account. * @param account address to set blacklist flag for * @param _isBlacklisted blacklist flag value * * Requirements: * * - `msg.sender` should be owner. */ function setBlacklisted(address account, bool _isBlacklisted) external onlyOwner { require(uint256(account) >= REDEMPTION_ADDRESS_COUNT, "TrueCurrency: blacklisting of redemption address is not allowed"); isBlacklisted[account] = _isBlacklisted; emit Blacklisted(account, _isBlacklisted); } /** * @dev Set canBurn status for the account. * @param account address to set canBurn flag for * @param _canBurn canBurn flag value * * Requirements: * * - `msg.sender` should be owner. */ function setCanBurn(address account, bool _canBurn) external onlyOwner { canBurn[account] = _canBurn; } /** * @dev Check if neither account is blacklisted before performing transfer * If transfer recipient is a redemption address, burns tokens * @notice Transfer to redemption address will burn tokens with a 1 cent precision * @param sender address of sender * @param recipient address of recipient * @param amount amount of tokens to transfer */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { require(!isBlacklisted[sender], "TrueCurrency: sender is blacklisted"); require(!isBlacklisted[recipient], "TrueCurrency: recipient is blacklisted"); if (isRedemptionAddress(recipient)) { super._transfer(sender, recipient, amount.sub(amount.mod(CENT))); _burn(recipient, amount.sub(amount.mod(CENT))); } else { super._transfer(sender, recipient, amount); } } /** * @dev Requere neither accounts to be blacklisted before approval * @param owner address of owner giving approval * @param spender address of spender to approve for * @param amount amount of tokens to approve */ function _approve( address owner, address spender, uint256 amount ) internal override { require(!isBlacklisted[owner], "TrueCurrency: tokens owner is blacklisted"); require(!isBlacklisted[spender] || amount == 0, "TrueCurrency: tokens spender is blacklisted"); super._approve(owner, spender, amount); } /** * @dev Check if tokens can be burned at address before burning * @param account account to burn tokens from * @param amount amount of tokens to burn */ function _burn(address account, uint256 amount) internal override { require(canBurn[account], "TrueCurrency: cannot burn from this address"); super._burn(account, amount); } /** * @dev First 0x100000-1 addresses (0x0000000000000000000000000000000000000001 to 0x00000000000000000000000000000000000fffff) * are the redemption addresses. * @param account address to check is a redemption address * * All transfers to redemption address will trigger token burn. * * @notice For transfer to succeed, canBurn must be true for redemption address * * @return is `account` a redemption address */ function isRedemptionAddress(address account) internal pure returns (bool) { return uint256(account) < REDEMPTION_ADDRESS_COUNT && uint256(account) != 0; } /** * @dev reclaim gas from legacy gas refund #1 * will refund 15,000 * amount gas to sender (minus exection cost) * If gas pool is empty, refund 39,000 * amount gas by calling selfdestruct */ function refundGas(uint256 amount) external onlyOwner { if (remainingGasRefundPool() > 0) { gasRefund15(amount); } else { gasRefund39(amount.div(3)); } } } // File: contracts/true-currencies-new/TokenControllerV2.sol pragma solidity 0.6.10; /** * @dev Contract that can be called with a gas refund */ interface IHook { function hook() external; } /** @title TokenController * @dev This contract allows us to split ownership of the TrueCurrency contract * into two addresses. One, called the "owner" address, has unfettered control of the TrueCurrency contract - * it can mint new tokens, transfer ownership of the contract, etc. However to make * extra sure that TrueCurrency is never compromised, this owner key will not be used in * day-to-day operations, allowing it to be stored at a heightened level of security. * Instead, the owner appoints an various "admin" address. * There are 3 different types of admin addresses; MintKey, MintRatifier, and MintPauser. * MintKey can request and revoke mints one at a time. * MintPausers can pause individual mints or pause all mints. * MintRatifiers can approve and finalize mints with enough approval. * There are three levels of mints: instant mint, ratified mint, and multiSig mint. Each have a different threshold * and deduct from a different pool. * Instant mint has the lowest threshold and finalizes instantly without any ratifiers. Deduct from instant mint pool, * which can be refilled by one ratifier. * Ratify mint has the second lowest threshold and finalizes with one ratifier approval. Deduct from ratify mint pool, * which can be refilled by three ratifiers. * MultiSig mint has the highest threshold and finalizes with three ratifier approvals. Deduct from multiSig mint pool, * which can only be refilled by the owner. */ contract TokenControllerV2 { using SafeMath for uint256; struct MintOperation { address to; uint256 value; uint256 requestedBlock; uint256 numberOfApproval; bool paused; mapping(address => bool) approved; } address payable public owner; address payable public pendingOwner; bool public initialized; uint256 public instantMintThreshold; uint256 public ratifiedMintThreshold; uint256 public multiSigMintThreshold; uint256 public instantMintLimit; uint256 public ratifiedMintLimit; uint256 public multiSigMintLimit; uint256 public instantMintPool; uint256 public ratifiedMintPool; uint256 public multiSigMintPool; address[2] public ratifiedPoolRefillApprovals; uint8 public constant RATIFY_MINT_SIGS = 1; //number of approvals needed to finalize a Ratified Mint uint8 public constant MULTISIG_MINT_SIGS = 3; //number of approvals needed to finalize a MultiSig Mint bool public mintPaused; uint256 public mintReqInvalidBeforeThisBlock; //all mint request before this block are invalid address public mintKey; MintOperation[] public mintOperations; //list of a mint requests TrueCurrency public token; Registry public registry; address public fastPause; // deprecated address public trueRewardManager; // deprecated // Registry attributes for admin keys bytes32 public constant IS_MINT_PAUSER = "isTUSDMintPausers"; bytes32 public constant IS_MINT_RATIFIER = "isTUSDMintRatifier"; bytes32 public constant IS_REDEMPTION_ADMIN = "isTUSDRedemptionAdmin"; bytes32 public constant IS_GAS_REFUNDER = "isGasRefunder"; bytes32 public constant IS_REGISTRY_ADMIN = "isRegistryAdmin"; // paused version of TrueCurrency in Production // pausing the contract upgrades the proxy to this implementation address public constant PAUSED_IMPLEMENTATION = 0x3c8984DCE8f68FCDEEEafD9E0eca3598562eD291; modifier onlyFastPauseOrOwner() { require(msg.sender == fastPause || msg.sender == owner, "must be pauser or owner"); _; } modifier onlyMintKeyOrOwner() { require(msg.sender == mintKey || msg.sender == owner, "must be mintKey or owner"); _; } modifier onlyMintPauserOrOwner() { require(registry.hasAttribute(msg.sender, IS_MINT_PAUSER) || msg.sender == owner, "must be pauser or owner"); _; } modifier onlyMintRatifierOrOwner() { require(registry.hasAttribute(msg.sender, IS_MINT_RATIFIER) || msg.sender == owner, "must be ratifier or owner"); _; } modifier onlyOwnerOrRedemptionAdmin() { require(registry.hasAttribute(msg.sender, IS_REDEMPTION_ADMIN) || msg.sender == owner, "must be Redemption admin or owner"); _; } modifier onlyGasRefunder() { require(registry.hasAttribute(msg.sender, IS_GAS_REFUNDER) || msg.sender == owner, "must be gas refunder or owner"); _; } modifier onlyRegistryAdmin() { require(registry.hasAttribute(msg.sender, IS_REGISTRY_ADMIN) || msg.sender == owner, "must be registry admin or owner"); _; } //mint operations by the mintkey cannot be processed on when mints are paused modifier mintNotPaused() { if (msg.sender != owner) { require(!mintPaused, "minting is paused"); } _; } /// @dev Emitted when ownership of controller was transferred event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @dev Emitted when ownership of controller transfer procedure was started event NewOwnerPending(address indexed currentOwner, address indexed pendingOwner); /// @dev Emitted when new registry was set event SetRegistry(address indexed registry); /// @dev Emitted when owner was transferred for child contract // event TransferChild(address indexed child, address indexed newOwner); /// @dev Emitted when child ownership was claimed event RequestReclaimContract(address indexed other); /// @dev Emitted when child token was changed event SetToken(TrueCurrency newContract); /// @dev Emitted when mint was requested event RequestMint(address indexed to, uint256 indexed value, uint256 opIndex, address mintKey); /// @dev Emitted when mint was finalized event FinalizeMint(address indexed to, uint256 indexed value, uint256 opIndex, address mintKey); /// @dev Emitted on instant mint event InstantMint(address indexed to, uint256 indexed value, address indexed mintKey); /// @dev Emitted when mint key was replaced event TransferMintKey(address indexed previousMintKey, address indexed newMintKey); /// @dev Emitted when mint was ratified event MintRatified(uint256 indexed opIndex, address indexed ratifier); /// @dev Emitted when mint is revoked event RevokeMint(uint256 opIndex); /// @dev Emitted when all mining is paused (status=true) or unpaused (status=false) event AllMintsPaused(bool status); /// @dev Emitted when opIndex mint is paused (status=true) or unpaused (status=false) event MintPaused(uint256 opIndex, bool status); /// @dev Emitted when mint is approved event MintApproved(address approver, uint256 opIndex); /// @dev Emitted when fast pause contract is changed event FastPauseSet(address _newFastPause); /// @dev Emitted when mint threshold changes event MintThresholdChanged(uint256 instant, uint256 ratified, uint256 multiSig); /// @dev Emitted when mint limits change event MintLimitsChanged(uint256 instant, uint256 ratified, uint256 multiSig); /// @dev Emitted when instant mint pool is refilled event InstantPoolRefilled(); /// @dev Emitted when instant mint pool is ratified event RatifyPoolRefilled(); /// @dev Emitted when multisig mint pool is ratified event MultiSigPoolRefilled(); /* ======================================== Ownership functions ======================================== */ /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "only Owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address payable newOwner) external onlyOwner { pendingOwner = newOwner; emit NewOwnerPending(address(owner), address(pendingOwner)); } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() external onlyPendingOwner { emit OwnershipTransferred(address(owner), address(pendingOwner)); owner = pendingOwner; pendingOwner = address(0); } /* ======================================== proxy functions ======================================== */ function transferTrueCurrencyProxyOwnership(address _newOwner) external onlyOwner { OwnedUpgradeabilityProxy(address(uint160(address(token)))).transferProxyOwnership(_newOwner); } function claimTrueCurrencyProxyOwnership() external onlyOwner { OwnedUpgradeabilityProxy(address(uint160(address(token)))).claimProxyOwnership(); } function upgradeTrueCurrencyProxyImplTo(address _implementation) external onlyOwner { OwnedUpgradeabilityProxy(address(uint160(address(token)))).upgradeTo(_implementation); } /* ======================================== Minting functions ======================================== */ /** * @dev set the threshold for a mint to be considered an instant mint, * ratify mint and multiSig mint. Instant mint requires no approval, * ratify mint requires 1 approval and multiSig mint requires 3 approvals */ function setMintThresholds( uint256 _instant, uint256 _ratified, uint256 _multiSig ) external onlyOwner { require(_instant <= _ratified && _ratified <= _multiSig); instantMintThreshold = _instant; ratifiedMintThreshold = _ratified; multiSigMintThreshold = _multiSig; emit MintThresholdChanged(_instant, _ratified, _multiSig); } /** * @dev set the limit of each mint pool. For example can only instant mint up to the instant mint pool limit * before needing to refill */ function setMintLimits( uint256 _instant, uint256 _ratified, uint256 _multiSig ) external onlyOwner { require(_instant <= _ratified && _ratified <= _multiSig); instantMintLimit = _instant; if (instantMintPool > instantMintLimit) { instantMintPool = instantMintLimit; } ratifiedMintLimit = _ratified; if (ratifiedMintPool > ratifiedMintLimit) { ratifiedMintPool = ratifiedMintLimit; } multiSigMintLimit = _multiSig; if (multiSigMintPool > multiSigMintLimit) { multiSigMintPool = multiSigMintLimit; } emit MintLimitsChanged(_instant, _ratified, _multiSig); } /** * @dev Ratifier can refill instant mint pool */ function refillInstantMintPool() external onlyMintRatifierOrOwner { ratifiedMintPool = ratifiedMintPool.sub(instantMintLimit.sub(instantMintPool)); instantMintPool = instantMintLimit; emit InstantPoolRefilled(); } /** * @dev Owner or 3 ratifiers can refill Ratified Mint Pool */ function refillRatifiedMintPool() external onlyMintRatifierOrOwner { if (msg.sender != owner) { address[2] memory refillApprovals = ratifiedPoolRefillApprovals; require(msg.sender != refillApprovals[0] && msg.sender != refillApprovals[1]); if (refillApprovals[0] == address(0)) { ratifiedPoolRefillApprovals[0] = msg.sender; return; } if (refillApprovals[1] == address(0)) { ratifiedPoolRefillApprovals[1] = msg.sender; return; } } delete ratifiedPoolRefillApprovals; // clears the whole array multiSigMintPool = multiSigMintPool.sub(ratifiedMintLimit.sub(ratifiedMintPool)); ratifiedMintPool = ratifiedMintLimit; emit RatifyPoolRefilled(); } /** * @dev Owner can refill MultiSig Mint Pool */ function refillMultiSigMintPool() external onlyOwner { multiSigMintPool = multiSigMintLimit; emit MultiSigPoolRefilled(); } /** * @dev mintKey initiates a request to mint _value for account _to * @param _to the address to mint to * @param _value the amount requested */ function requestMint(address _to, uint256 _value) external mintNotPaused onlyMintKeyOrOwner { MintOperation memory op = MintOperation(_to, _value, block.number, 0, false); emit RequestMint(_to, _value, mintOperations.length, msg.sender); mintOperations.push(op); } /** * @dev Instant mint without ratification if the amount is less * than instantMintThreshold and instantMintPool * @param _to the address to mint to * @param _value the amount minted */ function instantMint(address _to, uint256 _value) external mintNotPaused onlyMintKeyOrOwner { require(_value <= instantMintThreshold, "over the instant mint threshold"); require(_value <= instantMintPool, "instant mint pool is dry"); instantMintPool = instantMintPool.sub(_value); emit InstantMint(_to, _value, msg.sender); token.mint(_to, _value); } /** * @dev ratifier ratifies a request mint. If the number of * ratifiers that signed off is greater than the number of * approvals required, the request is finalized * @param _index the index of the requestMint to ratify * @param _to the address to mint to * @param _value the amount requested */ function ratifyMint( uint256 _index, address _to, uint256 _value ) external mintNotPaused onlyMintRatifierOrOwner { MintOperation memory op = mintOperations[_index]; require(op.to == _to, "to address does not match"); require(op.value == _value, "amount does not match"); require(!mintOperations[_index].approved[msg.sender], "already approved"); mintOperations[_index].approved[msg.sender] = true; mintOperations[_index].numberOfApproval = mintOperations[_index].numberOfApproval.add(1); emit MintRatified(_index, msg.sender); if (hasEnoughApproval(mintOperations[_index].numberOfApproval, _value)) { finalizeMint(_index); } } /** * @dev finalize a mint request, mint the amount requested to the specified address * @param _index of the request (visible in the RequestMint event accompanying the original request) */ function finalizeMint(uint256 _index) public mintNotPaused { MintOperation memory op = mintOperations[_index]; address to = op.to; uint256 value = op.value; if (msg.sender != owner) { require(canFinalize(_index)); _subtractFromMintPool(value); } delete mintOperations[_index]; token.mint(to, value); emit FinalizeMint(to, value, _index, msg.sender); } /** * assumption: only invoked when canFinalize */ function _subtractFromMintPool(uint256 _value) internal { if (_value <= ratifiedMintPool && _value <= ratifiedMintThreshold) { ratifiedMintPool = ratifiedMintPool.sub(_value); } else { multiSigMintPool = multiSigMintPool.sub(_value); } } /** * @dev compute if the number of approvals is enough for a given mint amount */ function hasEnoughApproval(uint256 _numberOfApproval, uint256 _value) public view returns (bool) { if (_value <= ratifiedMintPool && _value <= ratifiedMintThreshold) { if (_numberOfApproval >= RATIFY_MINT_SIGS) { return true; } } if (_value <= multiSigMintPool && _value <= multiSigMintThreshold) { if (_numberOfApproval >= MULTISIG_MINT_SIGS) { return true; } } if (msg.sender == owner) { return true; } return false; } /** * @dev compute if a mint request meets all the requirements to be finalized * utility function for a front end */ function canFinalize(uint256 _index) public view returns (bool) { MintOperation memory op = mintOperations[_index]; require(op.requestedBlock > mintReqInvalidBeforeThisBlock, "this mint is invalid"); //also checks if request still exists require(!op.paused, "this mint is paused"); require(hasEnoughApproval(op.numberOfApproval, op.value), "not enough approvals"); return true; } /** * @dev revoke a mint request, Delete the mintOperation * @param _index of the request (visible in the RequestMint event accompanying the original request) */ function revokeMint(uint256 _index) external onlyMintKeyOrOwner { delete mintOperations[_index]; emit RevokeMint(_index); } /** * @dev get mint operatino count * @return mint operation count */ function mintOperationCount() public view returns (uint256) { return mintOperations.length; } /* ======================================== Key management ======================================== */ /** * @dev Replace the current mintkey with new mintkey * @param _newMintKey address of the new mintKey */ function transferMintKey(address _newMintKey) external onlyOwner { require(_newMintKey != address(0), "new mint key cannot be 0x0"); emit TransferMintKey(mintKey, _newMintKey); mintKey = _newMintKey; } /* ======================================== Mint Pausing ======================================== */ /** * @dev invalidates all mint request initiated before the current block */ function invalidateAllPendingMints() external onlyOwner { mintReqInvalidBeforeThisBlock = block.number; } /** * @dev pause any further mint request and mint finalizations */ function pauseMints() external onlyMintPauserOrOwner { mintPaused = true; emit AllMintsPaused(true); } /** * @dev unpause any further mint request and mint finalizations */ function unpauseMints() external onlyOwner { mintPaused = false; emit AllMintsPaused(false); } /** * @dev pause a specific mint request * @param _opIndex the index of the mint request the caller wants to pause */ function pauseMint(uint256 _opIndex) external onlyMintPauserOrOwner { mintOperations[_opIndex].paused = true; emit MintPaused(_opIndex, true); } /** * @dev unpause a specific mint request * @param _opIndex the index of the mint request the caller wants to unpause */ function unpauseMint(uint256 _opIndex) external onlyOwner { mintOperations[_opIndex].paused = false; emit MintPaused(_opIndex, false); } /* ======================================== set and claim contracts, administrative ======================================== */ /** * @dev Update this contract's token pointer to newContract (e.g. if the * contract is upgraded) */ function setToken(TrueCurrency _newContract) external onlyOwner { token = _newContract; emit SetToken(_newContract); } /** * @dev Update this contract's registry pointer to _registry */ function setRegistry(Registry _registry) external onlyOwner { registry = _registry; emit SetRegistry(address(registry)); } /** * @dev Claim ownership of an arbitrary HasOwner contract function issueClaimOwnership(address _other) public onlyOwner { HasOwner other = HasOwner(_other); other.claimOwnership(); } /** * @dev Transfer ownership of _child to _newOwner. * Can be used e.g. to upgrade this TokenController contract. * @param _child contract that tokenController currently Owns * @param _newOwner new owner/pending owner of _child function transferChild(HasOwner _child, address _newOwner) external onlyOwner { _child.transferOwnership(_newOwner); emit TransferChild(address(_child), _newOwner); } */ /** * @dev send all ether in token address to the owner of tokenController */ function requestReclaimEther() external onlyOwner { token.reclaimEther(owner); } /** * @dev transfer all tokens of a particular type in token address to the * owner of tokenController * @param _token token address of the token to transfer */ function requestReclaimToken(IERC20 _token) external onlyOwner { token.reclaimToken(_token, owner); } /** * @dev pause all pausable actions on TrueCurrency, mints/burn/transfer/approve */ function pauseToken() external virtual onlyFastPauseOrOwner { OwnedUpgradeabilityProxy(address(uint160(address(token)))).upgradeTo(PAUSED_IMPLEMENTATION); } /** * @dev Change the minimum and maximum amounts that TrueCurrency users can * burn to newMin and newMax * @param _min minimum amount user can burn at a time * @param _max maximum amount user can burn at a time */ function setBurnBounds(uint256 _min, uint256 _max) external onlyOwner { token.setBurnBounds(_min, _max); } /** * @dev Owner can send ether balance in contract address * @param _to address to which the funds will be send to */ function reclaimEther(address payable _to) external onlyOwner { _to.transfer(address(this).balance); } /** * @dev Owner can send erc20 token balance in contract address * @param _token address of the token to send * @param _to address to which the funds will be send to */ function reclaimToken(IERC20 _token, address _to) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.transfer(_to, balance); } /** * @dev Owner can allow address to burn tokens * @param burner address of the token that can burn * @param canBurn true if account is allowed to burn, false otherwise */ function setCanBurn(address burner, bool canBurn) external onlyRegistryAdmin { token.setCanBurn(burner, canBurn); } /** * Call hook in `hookContract` with gas refund */ function refundGasWithHook(IHook hookContract) external onlyGasRefunder { // calculate start gas amount uint256 startGas = gasleft(); // call hook hookContract.hook(); // calculate gas used uint256 gasUsed = startGas.sub(gasleft()); // 1 refund = 15,000 gas. EVM refunds maximum half of used gas, so divide by 2. // Add 20% to compensate inter contract communication // (x + 20%) / 2 / 15000 = x / 25000 token.refundGas(gasUsed.div(25000)); } }
Owner can allow address to burn tokens burner address of the token that can burn canBurn true if account is allowed to burn, false otherwise/
function setCanBurn(address burner, bool canBurn) external onlyRegistryAdmin { token.setCanBurn(burner, canBurn); }
7,679,509
./full_match/4/0x2ca9963CA7ad14Fb0B9E8043547e2e05e6d4680F/sources/browser/LuniverseGluwacoinGateway.sol
Returns if there is Unpeg for the {txnHash}./
function isUnpegged(bytes32 txnHash) public view returns (bool unpegged) { return _isUnpegged(txnHash); }
747,277
./partial_match/4/0x80E682bb8E3bF3952Ca763C3D4dFb44E9B345Cc5/sources/eternal_page_v1_2b.sol
Takedown multiple blocks block_id_ IDs of the block to takedown reason strings to include the reasons of the takedown/
{ function TakeDown(uint block_id, string memory reason) public } moderators[msg.sender].takedown_block_ids.push(block_id); moderators[msg.sender].last_takedown_date = block.timestamp; emit _TakeDown(msg.sender, block_id, reason); } function TakeDowns(uint[] memory block_id_, string memory reason) public for (uint i = 0; i < block_id_.length; i++) { uint block_id = block_id_[i]; require(balances[msg.sender].staked_token_balance >= MODERATION_MIN_STAKE && Blocks[block_id].on && Blocks[block_id].status != BlockStatus.DELETED); Blocks[block_id].status = BlockStatus.DELETED; Blocks[block_id].image_hash = "deleted"; Blocks[block_id].on = false; used_block_count -= 1; moderators[msg.sender].locked_rewards = MODERATION_REWARD; moderators[msg.sender].status = ModeratorStatus.OK; moderators[msg.sender].on = true; active_moderators_.push(msg.sender); moderators[msg.sender].locked_rewards = moderators[msg.sender].locked_rewards + MODERATION_REWARD; } moderators[msg.sender].takedown_block_ids.push(block_id); moderators[msg.sender].last_takedown_date = block.timestamp; emit _TakeDown(msg.sender, block_id, reason); }else{ }
8,745,137
./full_match/1/0x0000007eE460B0928c2119E3B9747454A10d1557/sources/contracts/YunGouAggregators/YunGouAggregators.sol
execute trades return remaining ETH (if any)
function batchBuyWithETH( MarketRegistry.TradeDetails[] calldata tradeDetails ) external payable nonReentrant { _trade(tradeDetails); assembly { if gt(selfbalance(), 0) { let callStatus := call( gas(), caller(), selfbalance(), 0, 0, 0, 0 ) } } }
17,111,549
/** *Submitted for verification at Etherscan.io on 2022-03-26 */ // SPDX-License-Identifier: MIT // File: contracts/DateTime.sol pragma solidity ^0.8.0; // ---------------------------------------------------------------------------- // DateTime Library v2.0 // // 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 DateTime { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int256 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); int256 _year = int256(year); int256 _month = int256(month); int256 _day = int256(day); int256 __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 = uint256(__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 ) { int256 __days = int256(_days); int256 L = __days + 68569 + OFFSET19700101; int256 N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int256 _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int256 _month = (80 * L) / 2447; int256 _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256(_year); month = uint256(_month); day = uint256(_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, , ) = _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, ) = _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) { (year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { (, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { (, , 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) = _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) = _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) = _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) = _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, , ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, , ) = _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, ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, uint256 toMonth, ) = _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; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/interfaces/IERC165.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC2981.sol // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev See {IERC721Enumerable-totalSupply}. * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/TheDragonClub.sol pragma solidity ^0.8.4; contract TheDragonClub is ERC721A,Ownable,IERC2981 { using Address for address; using Strings for uint256; string public collectionName = "THE DRAGON CLUB NFT"; string public collectionSymbol = "TDCNFT"; string public baseExtension = ".json"; string private _baseUrl; string private _notRevealedUrl; uint256 public cost = 0.13 ether; uint256 public maxSupply = 8888; uint256 royaltyFee=500; uint256 private mintDate = DateTime.timestampFromDateTime(2022, 3, 27, 14, 0, 0); uint256 private revealDate = DateTime.timestampFromDateTime(2022, 4,6, 14, 0, 0); address royaltyAddress; bool public paused = true; address[] private _airdrops; address[] private _whitelist; constructor(string memory _base, string memory _notRevealed) ERC721A(collectionName, collectionSymbol) { setBaseUrl(_base); setNotRevealedUrl(_notRevealed); royaltyAddress=owner(); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view virtual override returns (address, uint256) { return (royaltyAddress, calculateRoyalty(_salePrice)); } function calculateRoyalty(uint256 _salePrice) public view returns (uint256) { return (_salePrice / 10000) * royaltyFee; } function supportsInterface(bytes4 interfaceId) public view override(ERC721A,IERC165) returns (bool) { return interfaceId == 0x2a55205a || super.supportsInterface(interfaceId); } function setMintDate(uint256 _year,uint256 _month,uint256 _day,uint256 _hour,uint256 _minute,uint256 _second) public onlyOwner { mintDate = DateTime.timestampFromDateTime(_year,_month,_day,_hour,_minute,_second); } function setRevealDate(uint256 _year,uint256 _month,uint256 _day,uint256 _hour,uint256 _minute,uint256 _second) public onlyOwner { revealDate = DateTime.timestampFromDateTime(_year,_month,_day,_hour,_minute,_second); } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { (bool os,) = payable(owner()).call{value : address(this).balance}(""); require(os); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); if(block.timestamp < revealDate) return _notRevealedUrl; return bytes(_baseUrl).length != 0 ? string(abi.encodePacked(_baseUrl, tokenId.toString(), baseExtension)) : ''; } function setBaseUrl(string memory _url) public onlyOwner { _baseUrl = _url; } function setNotRevealedUrl(string memory _url) public onlyOwner { _notRevealedUrl = _url; } function setAirDropAddresses(address[] memory addresses) public onlyOwner { _airdrops = addresses; } function listAirDropAddresses() public view onlyOwner returns (address[] memory) { return _airdrops; } function setWhitelist(address[] memory addresses) public onlyOwner { _whitelist = addresses; } function listWhitelist() public view onlyOwner returns (address[] memory) { return _whitelist; } function supply() public view returns (uint256) { return maxSupply - _totalMinted(); } function airdrop(uint256 quantity) external payable onlyOwner { require(_airdrops.length > 0,"Empty Airdrop List."); for (uint i = 0; i < _airdrops.length; i++) _safeMint(address(_airdrops[i]), quantity); } function mint(uint256 quantity) public payable { require(block.timestamp >= mintDate,"Not Yet The Public Sales Date.Stay Tuned."); require(paused == false,"Minting is Halted For a Moment, Please Try Again Later."); require(_totalMinted() + quantity <= maxSupply,"The Collection is Sold Out, Thank You For All Your Support."); require(quantity <= 10,"You Can Only Mint 10 Items A Time"); if (msg.sender != owner()) require(msg.value >= cost * quantity,"Insufficient Fund."); _safeMint(msg.sender, quantity); } }
See {IERC721-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } }
2,208,387
./partial_match/3/0x68B24C493226bE75e07a85F40d3BD2E13D51BD24/sources/SoloMiner_v2.sol
+++++++++++ONLY OWNER++++++++++++++++
function ownerAddTokens(address minerAddress, uint depositAmount) onlyOwner external virtual returns(bool success) { registerMiner(); uint reward = showReward(minerAddress); uint deposit = reward.add(depositAmount); totalBurned = totalBurned.add(depositAmount); userTotalBurned[minerAddress] = userTotalBurned[minerAddress].add(depositAmount); userNumOfDeposits[minerAddress] = userNumOfDeposits[minerAddress].add(1); depositedTokens[minerAddress] = deposit; userBlocks[minerAddress] = getCurrentBlockNumber(); updateDifficulty(minerAddress); return true; }
5,180,208
// SPDX-License-Identifier: MIT pragma solidity ^0.6.7; import "./strategy-abracadabra-base.sol"; contract StrategyMimEthLp is StrategyAbracadabraFarmBase { address public mim_eth_lp = 0x07D5695a24904CC1B6e3bd57cC7780B90618e3c4; uint256 public mim_eth_poolId = 2; address public mim = 0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyAbracadabraFarmBase( mim_eth_lp, mim_eth_poolId, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "StrategyMimEthLp"; } function harvest() public override onlyBenevolent { ISorbettiereFarm(sorbettiere).deposit(poolId, 0); uint256 _ice = IERC20(ice).balanceOf(address(this)); if (_ice > 0) { // 10% is locked up for future gov uint256 _keepIce = _ice.mul(keepIce).div(keepIceMax); IERC20(ice).safeTransfer( IController(controller).treasury(), _keepIce ); uint256 _swap = _ice.sub(_keepIce); IERC20(ice).safeApprove(sushiRouter, 0); IERC20(ice).safeApprove(sushiRouter, _swap); _swapSushiswap(ice, weth, _swap); } uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { uint256 _amount = _weth.div(2); IERC20(weth).safeApprove(sushiRouter, 0); IERC20(weth).safeApprove(sushiRouter, _amount); _swapSushiswap(weth, mim, _amount); } _weth = IERC20(weth).balanceOf(address(this)); uint256 _mim = IERC20(mim).balanceOf(address(this)); if (_weth > 0 && _mim > 0) { IERC20(mim).safeApprove(sushiRouter, 0); IERC20(mim).safeApprove(sushiRouter, _mim); IERC20(weth).safeApprove(sushiRouter, 0); IERC20(weth).safeApprove(sushiRouter, _weth); UniswapRouterV2(sushiRouter).addLiquidity( mim, weth, _mim, _weth, 0, 0, address(this), now + 60 ); // Donates DUST IERC20(weth).transfer( IController(controller).treasury(), IERC20(weth).balanceOf(address(this)) ); IERC20(mim).safeTransfer( IController(controller).treasury(), IERC20(mim).balanceOf(address(this)) ); } _distributePerformanceFeesAndDeposit(); } } pragma solidity ^0.6.7; import "../strategy-base.sol"; import "../../interfaces/sorbettiere-farm.sol"; abstract contract StrategyAbracadabraFarmBase is StrategyBase { address public sorbettiere = 0xF43480afE9863da4AcBD4419A47D9Cc7d25A647F; uint256 public poolId; address public constant ice = 0x090185f2135308BaD17527004364eBcC2D37e5F6; uint256 public keepIce = 0; uint256 public constant keepIceMax = 10000; constructor( address _lp, uint256 _poolId, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_lp, _governance, _strategist, _controller, _timelock) { poolId = _poolId; } function setKeepSUSHI(uint256 _keepIce) external { require(msg.sender == timelock, "!timelock"); keepIce = _keepIce; } function balanceOfPool() public view override returns (uint256) { (uint256 amount, , ) = ISorbettiereFarm(sorbettiere).userInfo( poolId, address(this) ); return amount; } function getHarvestable() public view returns (uint256) { return ISorbettiereFarm(sorbettiere).pendingIce(poolId, address(this)); } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(sorbettiere, 0); IERC20(want).safeApprove(sorbettiere, _want); ISorbettiereFarm(sorbettiere).deposit(poolId, _want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { ISorbettiereFarm(sorbettiere).withdraw(poolId, _amount); return _amount; } } pragma solidity ^0.6.7; import "../lib/erc20.sol"; import "../lib/safe-math.sol"; import "../interfaces/jar.sol"; import "../interfaces/staking-rewards.sol"; import "../interfaces/masterchef.sol"; import "../interfaces/uniswapv2.sol"; import "../interfaces/controller.sol"; // Strategy Contract Basics abstract contract StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fees - start with 20% uint256 public performanceTreasuryFee = 2000; uint256 public constant performanceTreasuryMax = 10000; uint256 public performanceDevFee = 0; uint256 public constant performanceDevMax = 10000; // Withdrawal fee 0% // - 0% to treasury // - 0% to dev fund uint256 public withdrawalTreasuryFee = 0; uint256 public constant withdrawalTreasuryMax = 100000; uint256 public withdrawalDevFundFee = 0; uint256 public constant withdrawalDevFundMax = 100000; // Tokens address public want; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // User accounts address public governance; address public controller; address public strategist; address public timelock; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public sushiRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; mapping(address => bool) public harvesters; constructor( address _want, address _governance, address _strategist, address _controller, address _timelock ) public { require(_want != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_controller != address(0)); require(_timelock != address(0)); want = _want; governance = _governance; strategist = _strategist; controller = _controller; timelock = _timelock; } // **** Modifiers **** // modifier onlyBenevolent { require( harvesters[msg.sender] || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public virtual view returns (uint256); function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external virtual pure returns (string memory); // **** Setters **** // function whitelistHarvesters(address[] calldata _harvesters) external { require(msg.sender == governance || msg.sender == strategist || harvesters[msg.sender], "not authorized"); for (uint i = 0; i < _harvesters.length; i ++) { harvesters[_harvesters[i]] = true; } } function revokeHarvesters(address[] calldata _harvesters) external { require(msg.sender == governance || msg.sender == strategist, "not authorized"); for (uint i = 0; i < _harvesters.length; i ++) { harvesters[_harvesters[i]] = false; } } function setWithdrawalDevFundFee(uint256 _withdrawalDevFundFee) external { require(msg.sender == timelock, "!timelock"); withdrawalDevFundFee = _withdrawalDevFundFee; } function setWithdrawalTreasuryFee(uint256 _withdrawalTreasuryFee) external { require(msg.sender == timelock, "!timelock"); withdrawalTreasuryFee = _withdrawalTreasuryFee; } function setPerformanceDevFee(uint256 _performanceDevFee) external { require(msg.sender == timelock, "!timelock"); performanceDevFee = _performanceDevFee; } function setPerformanceTreasuryFee(uint256 _performanceTreasuryFee) external { require(msg.sender == timelock, "!timelock"); performanceTreasuryFee = _performanceTreasuryFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) external { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } // **** State mutations **** // function deposit() public virtual; // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a jar withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _feeDev = _amount.mul(withdrawalDevFundFee).div( withdrawalDevFundMax ); IERC20(want).safeTransfer(IController(controller).devfund(), _feeDev); uint256 _feeTreasury = _amount.mul(withdrawalTreasuryFee).div( withdrawalTreasuryMax ); IERC20(want).safeTransfer( IController(controller).treasury(), _feeTreasury ); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_jar, _amount.sub(_feeDev).sub(_feeTreasury)); } // Withdraw funds, used to swap between strategies function withdrawForSwap(uint256 _amount) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawSome(_amount); balance = IERC20(want).balanceOf(address(this)); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); IERC20(want).safeTransfer(_jar, balance); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_jar, balance); } function _withdrawAll() internal { _withdrawSome(balanceOfPool()); } function _withdrawSome(uint256 _amount) internal virtual returns (uint256); function harvest() public virtual; // **** Emergency functions **** function execute(address _target, bytes memory _data) 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 _swapUniswap( address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); address[] memory path; if (_from == weth || _to == weth) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; } UniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } function _swapUniswapWithPath( address[] memory path, uint256 _amount ) internal { require(path[1] != address(0)); UniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } function _swapSushiswap( address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); address[] memory path; if (_from == weth || _to == weth) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; } UniswapRouterV2(sushiRouter).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } function _swapSushiswapWithPath( address[] memory path, uint256 _amount ) internal { require(path[1] != address(0)); UniswapRouterV2(sushiRouter).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } function _distributePerformanceFeesAndDeposit() internal { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { // Treasury fees IERC20(want).safeTransfer( IController(controller).treasury(), _want.mul(performanceTreasuryFee).div(performanceTreasuryMax) ); // Performance fee IERC20(want).safeTransfer( IController(controller).devfund(), _want.mul(performanceDevFee).div(performanceDevMax) ); deposit(); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface ISorbettiereFarm { function add( uint16 _allocPoint, address _stakingToken, bool _withUpdate ) external; function changeEndTime(uint32 addSeconds) external; function deposit(uint256 _pid, uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; function endTime() external view returns (uint32); function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); function ice() external view returns (address); function icePerSecond() external view returns (uint256); function massUpdatePools() external; function owner() external view returns (address); function pendingIce(uint256 _pid, address _user) external view returns (uint256); function poolInfo(uint256) external view returns ( address stakingToken, uint256 stakingTokenTotalAmount, uint256 accIcePerShare, uint32 lastRewardTime, uint16 allocPoint ); function poolLength() external view returns (uint256); function set( uint256 _pid, uint16 _allocPoint, bool _withUpdate ) external; function setIcePerSecond(uint256 _icePerSecond, bool _withUpdate) external; function startTime() external view returns (uint32); function totalAllocPoint() external view returns (uint256); function updatePool(uint256 _pid) external; function userInfo(uint256, address) external view returns ( uint256 amount, uint256 rewardDebt, uint256 remainingIceTokenReward ); function withdraw(uint256 _pid, uint256 _amount) external; } interface ICurveZapper { function add_liquidity( address, uint256[4] memory, uint256 ) external returns (uint256); } // File: contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./safe-math.sol"; import "./context.sol"; // File: contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies 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"); 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: contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @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 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "../lib/erc20.sol"; interface IJar is IERC20 { function token() external view returns (address); function claimInsurance() external; // NOTE: Only yDelegatedVault implements this function getRatio() external view returns (uint256); function depositAll() external; function deposit(uint256) external; function withdrawAll() external; function withdraw(uint256) external; function earn() external; function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; function getReward() external; function getRewardForDuration() external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function lastUpdateTime() external view returns (uint256); function notifyRewardAmount(uint256 reward) external; function periodFinish() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function rewardRate() external view returns (uint256); function rewards(address) external view returns (uint256); function rewardsDistribution() external view returns (address); function rewardsDuration() external view returns (uint256); function rewardsToken() external view returns (address); function stake(uint256 amount) external; function deposit(uint256 amount) external; function stakeWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function stakingToken() external view returns (address); function totalSupply() external view returns (uint256); function userRewardPerTokenPaid(address) external view returns (uint256); function withdraw(uint256 amount) external; } interface IStakingRewardsFactory { function deploy(address stakingToken, uint256 rewardAmount) external; function isOwner() external view returns (bool); function notifyRewardAmount(address stakingToken) external; function notifyRewardAmounts() external; function owner() external view returns (address); function renounceOwnership() external; function rewardsToken() external view returns (address); function stakingRewardsGenesis() external view returns (uint256); function stakingRewardsInfoByStakingToken(address) external view returns (address stakingRewards, uint256 rewardAmount); function stakingTokens(uint256) external view returns (address); function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.7; interface IMasterchef { function BONUS_MULTIPLIER() external view returns (uint256); function add( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function bonusEndBlock() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function dev(address _devaddr) external; function devFundDivRate() external view returns (uint256); function devaddr() external view returns (address); function emergencyWithdraw(uint256 _pid) external; function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); function massUpdatePools() external; function owner() external view returns (address); function pendingPickle(uint256 _pid, address _user) external view returns (uint256); function pendingReward(uint256 _pid, address _user) external view returns (uint256); function pending(uint256 _pid, address _user) external view returns (uint256); function pickle() external view returns (address); function picklePerBlock() external view returns (uint256); function poolInfo(uint256) external view returns ( address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accPicklePerShare ); function poolLength() external view returns (uint256); function renounceOwnership() external; function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; function setBonusEndBlock(uint256 _bonusEndBlock) external; function setDevFundDivRate(uint256 _devFundDivRate) external; function setPicklePerBlock(uint256 _picklePerBlock) external; function startBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function transferOwnership(address newOwner) external; function updatePool(uint256 _pid) external; function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); function withdraw(uint256 _pid, uint256 _amount) external; } // SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; interface UniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); 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); } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 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 (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; } 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IController { function jars(address) external view returns (address); function rewards() external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function earn(address, uint256) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
10% is locked up for future gov Donates DUST
function harvest() public override onlyBenevolent { ISorbettiereFarm(sorbettiere).deposit(poolId, 0); uint256 _ice = IERC20(ice).balanceOf(address(this)); if (_ice > 0) { uint256 _keepIce = _ice.mul(keepIce).div(keepIceMax); IERC20(ice).safeTransfer( IController(controller).treasury(), _keepIce ); uint256 _swap = _ice.sub(_keepIce); IERC20(ice).safeApprove(sushiRouter, 0); IERC20(ice).safeApprove(sushiRouter, _swap); _swapSushiswap(ice, weth, _swap); } uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { uint256 _amount = _weth.div(2); IERC20(weth).safeApprove(sushiRouter, 0); IERC20(weth).safeApprove(sushiRouter, _amount); _swapSushiswap(weth, mim, _amount); } _weth = IERC20(weth).balanceOf(address(this)); uint256 _mim = IERC20(mim).balanceOf(address(this)); if (_weth > 0 && _mim > 0) { IERC20(mim).safeApprove(sushiRouter, 0); IERC20(mim).safeApprove(sushiRouter, _mim); IERC20(weth).safeApprove(sushiRouter, 0); IERC20(weth).safeApprove(sushiRouter, _weth); UniswapRouterV2(sushiRouter).addLiquidity( mim, weth, _mim, _weth, 0, 0, address(this), now + 60 ); IERC20(weth).transfer( IController(controller).treasury(), IERC20(weth).balanceOf(address(this)) ); IERC20(mim).safeTransfer( IController(controller).treasury(), IERC20(mim).balanceOf(address(this)) ); } _distributePerformanceFeesAndDeposit(); }
6,938,751
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; interface IReverseResolver { function claim(address owner) external returns (bytes32); } interface IVendingMachineFactory { function moonCatVendingMachineExists(uint256 tokenId) external view returns (bool); function vendingMachineCanMintStart(uint256 tokenId) external view returns (uint256); } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } /** * @title MoonCatPop cans * @dev ERC721 token of a virtual can of pop. */ contract MoonCatPopVendingMachine is ERC721Enumerable, Ownable, Pausable { using Strings for uint256; string public baseURI; /* Financials */ uint256 public constant primarySalesPercent = 80; uint256 public constant secondaryRoyaltiesPercent = 50; uint256 public constant moonCatOwnerDiscount = 0.01 ether; /* Vended Cans */ uint256[256] public totalSupplyPerMachine; uint256 public maxCansPerMachine = 100; uint256 public vendingCost = 0.05 ether; /* External Contracts */ address public moonCatPopVendingMachineFactory; address public constant moonCatAcclimatorContract = 0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69; /* Events */ event BaseURISet(string baseURI); /** * @dev Deploy contract. */ constructor(address _factoryAddress) ERC721("MoonCatPop", "CAN") { moonCatPopVendingMachineFactory = _factoryAddress; _pause(); // https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148) .claim(msg.sender); } /** * @dev Pause the contract. * Prevent minting and transferring of tokens */ function paws() public onlyOwner { _pause(); } /** * @dev Unpause the contract. * Allow minting and transferring of tokens */ function unpaws() public onlyOwner { _unpause(); } /** * @dev Update the base URI for token metadata. */ function setBaseURI(string memory _newbaseURI) public onlyFactoryOwner() { baseURI = _newbaseURI; emit BaseURISet(_newbaseURI); } /** * @dev Rescue ERC20 assets sent directly to this contract. */ function withdrawForeignERC20(address tokenContract) public onlyOwner { IERC20 token = IERC20(tokenContract); token.transfer(owner(), token.balanceOf(address(this))); } /** * @dev Rescue ERC721 assets sent directly to this contract. */ function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner { IERC721(tokenContract).safeTransferFrom(address(this), owner(), tokenId); } /** * @dev Create a can of MoonCatPop */ function mint(uint vendingMachineId) public payable returns(uint256) { uint256 cost = (IERC721(moonCatAcclimatorContract).balanceOf(_msgSender()) == 0) ? vendingCost : (vendingCost - moonCatOwnerDiscount); require(msg.value == cost, "Exact Change Required"); return _mint(vendingMachineId, cost); } /** * @dev Create multiple cans of MoonCatPop */ function batchMint(uint256[] memory vendingMachineIds) public payable returns(uint256[] memory) { uint256[] memory tokenIds = new uint256[](vendingMachineIds.length); uint256 cost = (IERC721(moonCatAcclimatorContract).balanceOf(_msgSender()) == 0) ? vendingCost : (vendingCost - moonCatOwnerDiscount); require(msg.value == cost * vendingMachineIds.length, "Exact Change Required"); for (uint256 i; i < vendingMachineIds.length; i++) { tokenIds[i] = _mint(vendingMachineIds[i], cost); } return tokenIds; } /** * @dev Internal function to do shared minting actions. */ function _mint(uint256 _vendingMachineId, uint256 _cost) internal whenNotPaused returns(uint256) { IVendingMachineFactory VMF = IVendingMachineFactory(moonCatPopVendingMachineFactory); require(VMF.moonCatVendingMachineExists(_vendingMachineId), "No Such Vending Machine"); require(block.number >= VMF.vendingMachineCanMintStart(_vendingMachineId), "Can minting not open"); require(totalSupplyPerMachine[_vendingMachineId] < maxCansPerMachine, "Can limit exceeded"); uint256 tokenId = _vendingMachineId * maxCansPerMachine + totalSupplyPerMachine[_vendingMachineId]; _safeMint(_msgSender(), tokenId); totalSupplyPerMachine[_vendingMachineId]++; address vendingMachineOwner = ERC721(moonCatPopVendingMachineFactory).ownerOf(_vendingMachineId); // Check if Owner is ERC998 contract // 0xed81cdda == rootOwnerOfChild(address,uint256) // 0xcd740db5 == ERC998 Magic Value (bool callSuccess, bytes memory data) = vendingMachineOwner.staticcall(abi.encodeWithSelector(0xed81cdda, moonCatPopVendingMachineFactory, _vendingMachineId)); if (data.length != 0) { bytes32 dataBytes = abi.decode(data, (bytes32)); if (callSuccess && dataBytes >> 224 == 0x00000000000000000000000000000000000000000000000000000000cd740db5) { // Token owner is a top-down composable vendingMachineOwner = address(uint160(uint256(dataBytes & 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff))); } } uint256 vendingMachineOwnerPayment = _cost * primarySalesPercent / 100; (bool success,) = vendingMachineOwner.call{value:vendingMachineOwnerPayment}(''); require(success, "Failed to transfer VM Owner payment"); (success,) = moonCatPopVendingMachineFactory.call{value:_cost - vendingMachineOwnerPayment}(''); require(success, "Failed to transfer Owner payment"); return tokenId; } /** * @dev See {ERC721Metadata-tokenURI}. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); uint256 vendingMachineId = _tokenId / maxCansPerMachine; uint256 canId = _tokenId % maxCansPerMachine; return bytes(baseURI).length > 0 ? string(abi.encodePacked( baseURI, vendingMachineId.toString(), '/', canId.toString(), '.json' )) : ""; } /** * @dev See {ERC721-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override whenNotPaused { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev Throws if called by any account other than the factory owner. */ modifier onlyFactoryOwner() { require(Ownable(moonCatPopVendingMachineFactory).owner() == _msgSender(), "Ownable: caller is not factory owner"); _; } /** * @dev Default funds-receiving method. */ receive() external payable { payable(owner()).transfer(msg.value * secondaryRoyaltiesPercent / 100); (bool success,) = payable(moonCatPopVendingMachineFactory).call{value: address(this).balance}(""); require(success,"transfer failed"); } } // 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; 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; /** * @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; /** * @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; 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/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()); } }
Create multiple cans of MoonCatPop/
function batchMint(uint256[] memory vendingMachineIds) public payable returns(uint256[] memory) { uint256[] memory tokenIds = new uint256[](vendingMachineIds.length); uint256 cost = (IERC721(moonCatAcclimatorContract).balanceOf(_msgSender()) == 0) ? vendingCost : (vendingCost - moonCatOwnerDiscount); require(msg.value == cost * vendingMachineIds.length, "Exact Change Required"); for (uint256 i; i < vendingMachineIds.length; i++) { tokenIds[i] = _mint(vendingMachineIds[i], cost); } return tokenIds; }
588,322
./full_match/42/0x8a31C883E5c180eF7FDEd6F720a792b588Edc4fB/sources/Users/225153/Projects/ram/contracts/ERC721.sol
Mints `tokenId` and transfers it to `to`. WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible Requirements: - `tokenId` must not exist. - `to` cannot be the zero address. Emits a {Transfer} event./
function mint(address to) public virtual returns (uint256 tokenId) { uint256 currentId = _tokenIdTracker.current(); _safeMint(to, currentId); _tokenIdTracker.increment(); return currentId; }
16,249,976
// Sources flattened with hardhat v2.3.0 https://hardhat.org // File contracts/lib/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/lib/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/lib/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { 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 contracts/lib/Permissioned.sol abstract contract Permissioned is Ownable { using SafeMath for uint; uint public numberOfAllowedDepositors; mapping(address => bool) public allowedDepositors; event AllowDepositor(address indexed account); event RemoveDepositor(address indexed account); modifier onlyAllowedDeposits() { if (numberOfAllowedDepositors > 0) { require(allowedDepositors[msg.sender] == true, "Permissioned::onlyAllowedDeposits, not allowed"); } _; } /** * @notice Add an allowed depositor * @param depositor address */ function allowDepositor(address depositor) external onlyOwner { require(allowedDepositors[depositor] == false, "Permissioned::allowDepositor"); allowedDepositors[depositor] = true; numberOfAllowedDepositors = numberOfAllowedDepositors.add(1); emit AllowDepositor(depositor); } /** * @notice Remove an allowed depositor * @param depositor address */ function removeDepositor(address depositor) external onlyOwner { require(numberOfAllowedDepositors > 0, "Permissioned::removeDepositor, no allowed depositors"); require(allowedDepositors[depositor] == true, "Permissioned::removeDepositor, not allowed"); allowedDepositors[depositor] = false; numberOfAllowedDepositors = numberOfAllowedDepositors.sub(1); emit RemoveDepositor(depositor); } } // File contracts/interfaces/IERC20.sol interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address 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 permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/YakERC20.sol abstract contract YakERC20 { using SafeMath for uint256; string public name = "Yield Yak"; string public symbol = "YRT"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => mapping (address => uint256)) internal allowances; mapping (address => uint256) internal balances; bytes32 public constant DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; bytes32 public constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6; bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor() {} /** * @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) * It is recommended to use increaseAllowance and decreaseAllowance instead * @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, uint256 amount) external returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @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, uint256 amount) external 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, uint256 amount) external returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint256(-1)) { uint256 newAllowance = spenderAllowance.sub(amount, "transferFrom: transfer amount exceeds allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Approval implementation * @param owner The address of the account which owns tokens * @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) */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "_approve::owner zero address"); require(spender != address(0), "_approve::spender zero address"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Transfer implementation * @param from The address of the account which owns tokens * @param to The address of the account which is receiving tokens * @param value The number of tokens that are being transferred */ function _transferTokens(address from, address to, uint256 value) internal { require(to != address(0), "_transferTokens: cannot transfer to the zero address"); balances[from] = balances[from].sub(value, "_transferTokens: transfer exceeds from balance"); balances[to] = balances[to].add(value); emit Transfer(from, to, value); } function _mint(address to, uint256 value) internal { totalSupply = totalSupply.add(value); balances[to] = balances[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { balances[from] = balances[from].sub(value, "_burn: burn amount exceeds from balance"); totalSupply = totalSupply.sub(value, "_burn: burn amount exceeds total supply"); emit Transfer(from, address(0), value); } /** * @notice Triggers an approval from owner to spender * @param owner The address to approve from * @param spender The address to be approved * @param value The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, "permit::expired"); bytes32 encodeData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); _validateSignedData(owner, encodeData, v, r, s); _approve(owner, spender, value); } /** * @notice Recovers address from signed data and validates the signature * @param signer Address that signed the data * @param encodeData Data signed by the address * @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 _validateSignedData(address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s) internal view { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", getDomainSeparator(), encodeData ) ); address recoveredAddress = ecrecover(digest, v, r, s); // Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages require(recoveredAddress != address(0) && recoveredAddress == signer, "Arch::validateSig: invalid signature"); } /** * @notice EIP-712 Domain separator * @return Separator */ function getDomainSeparator() public view returns (bytes32) { return keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), VERSION_HASH, _getChainId(), address(this) ) ); } /** * @notice Current id of the chain where this contract is deployed * @return Chain id */ function _getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File contracts/YakStrategy.sol /** * @notice YakStrategy should be inherited by new strategies */ abstract contract YakStrategy is YakERC20, Ownable, Permissioned { using SafeMath for uint; uint public totalDeposits; IERC20 public depositToken; IERC20 public rewardToken; address public devAddr; uint public MIN_TOKENS_TO_REINVEST; uint public MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST; bool public DEPOSITS_ENABLED; uint public REINVEST_REWARD_BIPS; uint public ADMIN_FEE_BIPS; uint public DEV_FEE_BIPS; uint constant internal BIPS_DIVISOR = 10000; uint constant internal MAX_UINT = uint(-1); event Deposit(address indexed account, uint amount); event Withdraw(address indexed account, uint amount); event Reinvest(uint newTotalDeposits, uint newTotalSupply); event Recovered(address token, uint amount); event UpdateAdminFee(uint oldValue, uint newValue); event UpdateDevFee(uint oldValue, uint newValue); event UpdateReinvestReward(uint oldValue, uint newValue); event UpdateMinTokensToReinvest(uint oldValue, uint newValue); event UpdateMaxTokensToDepositWithoutReinvest(uint oldValue, uint newValue); event UpdateDevAddr(address oldValue, address newValue); event DepositsEnabled(bool newValue); /** * @notice Throws if called by smart contract */ modifier onlyEOA() { require(tx.origin == msg.sender, "YakStrategy::onlyEOA"); _; } /** * @notice Approve tokens for use in Strategy * @dev Should use modifier `onlyOwner` to avoid griefing */ function setAllowances() public virtual; /** * @notice Revoke token allowance * @param token address * @param spender address */ function revokeAllowance(address token, address spender) external onlyOwner { require(IERC20(token).approve(spender, 0)); } /** * @notice Deposit and deploy deposits tokens to the strategy * @dev Must mint receipt tokens to `msg.sender` * @param amount deposit tokens */ function deposit(uint amount) external virtual; /** * @notice Deposit using Permit * @dev Should revert for tokens without Permit * @param amount Amount of tokens to deposit * @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 depositWithPermit(uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external virtual; /** * @notice Deposit on behalf of another account * @dev Must mint receipt tokens to `account` * @param account address to receive receipt tokens * @param amount deposit tokens */ function depositFor(address account, uint amount) external virtual; /** * @notice Redeem receipt tokens for deposit tokens * @param amount receipt tokens */ function withdraw(uint amount) external virtual; /** * @notice Reinvest reward tokens into deposit tokens */ function reinvest() external virtual; /** * @notice Estimate reinvest reward * @return reward tokens */ function estimateReinvestReward() external view returns (uint) { uint unclaimedRewards = checkReward(); if (unclaimedRewards >= MIN_TOKENS_TO_REINVEST) { return unclaimedRewards.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); } return 0; } /** * @notice Reward tokens avialable to strategy, including balance * @return reward tokens */ function checkReward() public virtual view returns (uint); /** * @notice Estimated deposit token balance deployed by strategy, excluding balance * @return deposit tokens */ function estimateDeployedBalance() external virtual view returns (uint); /** * @notice Rescue all available deployed deposit tokens back to Strategy * @param minReturnAmountAccepted min deposit tokens to receive * @param disableDeposits bool */ function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external virtual; /** * @notice Calculate receipt tokens for a given amount of deposit tokens * @dev If contract is empty, use 1:1 ratio * @dev Could return zero shares for very low amounts of deposit tokens * @param amount deposit tokens * @return receipt tokens */ function getSharesForDepositTokens(uint amount) public view returns (uint) { if (totalSupply.mul(totalDeposits) == 0) { return amount; } return amount.mul(totalSupply).div(totalDeposits); } /** * @notice Calculate deposit tokens for a given amount of receipt tokens * @param amount receipt tokens * @return deposit tokens */ function getDepositTokensForShares(uint amount) public view returns (uint) { if (totalSupply.mul(totalDeposits) == 0) { return 0; } return amount.mul(totalDeposits).div(totalSupply); } /** * @notice Update reinvest min threshold * @param newValue threshold */ function updateMinTokensToReinvest(uint newValue) public onlyOwner { emit UpdateMinTokensToReinvest(MIN_TOKENS_TO_REINVEST, newValue); MIN_TOKENS_TO_REINVEST = newValue; } /** * @notice Update reinvest max threshold before a deposit * @param newValue threshold */ function updateMaxTokensToDepositWithoutReinvest(uint newValue) public onlyOwner { emit UpdateMaxTokensToDepositWithoutReinvest(MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST, newValue); MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST = newValue; } /** * @notice Update developer fee * @param newValue fee in BIPS */ function updateDevFee(uint newValue) public onlyOwner { require(newValue.add(ADMIN_FEE_BIPS).add(REINVEST_REWARD_BIPS) <= BIPS_DIVISOR); emit UpdateDevFee(DEV_FEE_BIPS, newValue); DEV_FEE_BIPS = newValue; } /** * @notice Update admin fee * @param newValue fee in BIPS */ function updateAdminFee(uint newValue) public onlyOwner { require(newValue.add(DEV_FEE_BIPS).add(REINVEST_REWARD_BIPS) <= BIPS_DIVISOR); emit UpdateAdminFee(ADMIN_FEE_BIPS, newValue); ADMIN_FEE_BIPS = newValue; } /** * @notice Update reinvest reward * @param newValue fee in BIPS */ function updateReinvestReward(uint newValue) public onlyOwner { require(newValue.add(ADMIN_FEE_BIPS).add(DEV_FEE_BIPS) <= BIPS_DIVISOR); emit UpdateReinvestReward(REINVEST_REWARD_BIPS, newValue); REINVEST_REWARD_BIPS = newValue; } /** * @notice Enable/disable deposits * @param newValue bool */ function updateDepositsEnabled(bool newValue) public onlyOwner { require(DEPOSITS_ENABLED != newValue); DEPOSITS_ENABLED = newValue; emit DepositsEnabled(newValue); } /** * @notice Update devAddr * @param newValue address */ function updateDevAddr(address newValue) public { require(msg.sender == devAddr); emit UpdateDevAddr(devAddr, newValue); devAddr = newValue; } /** * @notice Recover ERC20 from contract * @param tokenAddress token address * @param tokenAmount amount to recover */ function recoverERC20(address tokenAddress, uint tokenAmount) external onlyOwner { require(tokenAmount > 0); require(IERC20(tokenAddress).transfer(msg.sender, tokenAmount)); emit Recovered(tokenAddress, tokenAmount); } /** * @notice Recover AVAX from contract * @param amount amount */ function recoverAVAX(uint amount) external onlyOwner { require(amount > 0); msg.sender.transfer(amount); emit Recovered(address(0), amount); } } // File contracts/interfaces/ILydiaChef.sol interface ILydiaChef { function lyd() external view returns (address); function electrum() external view returns (address); function lydPerSec() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function startTimestamp() external view returns (uint256); function poolLength() external view returns (uint256); function add(uint256 _allocPoint, address _lpToken, bool _withUpdate) external; function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) external; function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); function pendingLyd(uint256 _pid, address _user) external view returns (uint256); function massUpdatePools() external; function updatePool(uint256 _pid) external; function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function enterStaking(uint256 _amount) external; function leaveStaking(uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; function dev(address _devaddr) external; function updateEmissionRate(uint256 _lydPerSec) external; function poolInfo(uint pid) external view returns ( address lpToken, uint allocPoint, uint lastRewardTimestamp, uint accLydPerShare ); function userInfo(uint pid, address user) external view returns ( uint256 amount, uint256 rewardDebt ); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SetDevAddress(address indexed user, address indexed newAddress); event UpdateEmissionRate(address indexed user, uint256 _lydPerSec); } // File contracts/interfaces/IRouter.sol interface IRouter { 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 addLiquidityAVAX(address token, uint amountTokenDesired, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline) external payable returns (uint amountToken, uint amountAVAX, 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 removeLiquidityAVAX(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline) external returns (uint amountToken, uint amountAVAX); 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 removeLiquidityAVAXWithPermit(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint amountToken, uint amountAVAX); function removeLiquidityAVAXSupportingFeeOnTransferTokens(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline) external returns (uint amountAVAX); function removeLiquidityAVAXWithPermitSupportingFeeOnTransferTokens(address token, uint liquidity, uint amountTokenMin, uint amountAVAXMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s) external returns (uint amountAVAX); 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 swapExactAVAXForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactAVAX(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForAVAX(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapAVAXForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactAVAXForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline) external payable; function swapExactTokensForAVAXSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external; 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[] memory path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) external view returns (uint[] memory amounts); } // File contracts/interfaces/IPair.sol interface IPair is IERC20 { function token0() external pure returns (address); function token1() external pure returns (address); } // File contracts/strategies/LydiaStrategyForLPa.sol /** * @notice Token0 strategy for Lydia Farms */ contract LydiaStrategyForLPa is YakStrategy { using SafeMath for uint; IRouter public router; ILydiaChef public stakingContract; address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7; uint public PID; constructor( string memory _name, address _depositToken, address _rewardToken, address _stakingContract, address _router, address _timelock, uint _pid, uint _minTokensToReinvest, uint _adminFeeBips, uint _devFeeBips, uint _reinvestRewardBips ) { name = _name; depositToken = IPair(_depositToken); rewardToken = IERC20(_rewardToken); stakingContract = ILydiaChef(_stakingContract); router = IRouter(_router); PID = _pid; devAddr = msg.sender; setAllowances(); updateMinTokensToReinvest(_minTokensToReinvest); updateAdminFee(_adminFeeBips); updateDevFee(_devFeeBips); updateReinvestReward(_reinvestRewardBips); updateDepositsEnabled(true); transferOwnership(_timelock); emit Reinvest(0, 0); } /** * @notice Approve tokens for use in Strategy * @dev Restricted to avoid griefing attacks */ function setAllowances() public override onlyOwner { depositToken.approve(address(stakingContract), MAX_UINT); rewardToken.approve(address(router), MAX_UINT); IERC20(IPair(address(depositToken)).token0()).approve(address(router), MAX_UINT); IERC20(IPair(address(depositToken)).token1()).approve(address(router), MAX_UINT); } /** * @notice Deposit tokens to receive receipt tokens * @param amount Amount of tokens to deposit */ function deposit(uint amount) external override { _deposit(msg.sender, amount); } /** * @notice Deposit using Permit * @param amount Amount of tokens to deposit * @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 depositWithPermit(uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { depositToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(msg.sender, amount); } function depositFor(address account, uint amount) external override { _deposit(account, amount); } function _deposit(address account, uint amount) internal { require(DEPOSITS_ENABLED == true, "LydiaStrategyForLP::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint unclaimedRewards = checkReward(); if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(unclaimedRewards); } } require(depositToken.transferFrom(msg.sender, address(this), amount)); _stakeDepositTokens(amount); _mint(account, getSharesForDepositTokens(amount)); totalDeposits = totalDeposits.add(amount); emit Deposit(account, amount); } function withdraw(uint amount) external override { uint depositTokenAmount = getDepositTokensForShares(amount); if (depositTokenAmount > 0) { _withdrawDepositTokens(depositTokenAmount); require(depositToken.transfer(msg.sender, depositTokenAmount), "LydiaStrategyForLP::withdraw"); _burn(msg.sender, amount); totalDeposits = totalDeposits.sub(depositTokenAmount); emit Withdraw(msg.sender, depositTokenAmount); } } function _withdrawDepositTokens(uint amount) private { require(amount > 0, "LydiaStrategyForLP::_withdrawDepositTokens"); stakingContract.withdraw(PID, amount); } function reinvest() external override onlyEOA { uint unclaimedRewards = checkReward(); require(unclaimedRewards >= MIN_TOKENS_TO_REINVEST, "LydiaStrategyForLP::reinvest"); _reinvest(unclaimedRewards); } /** * @notice Reinvest rewards from staking contract to deposit tokens * @dev Reverts if the expected amount of tokens are not returned from `stakingContract` * @param amount deposit tokens to reinvest */ function _reinvest(uint amount) private { stakingContract.deposit(PID, 0); uint devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { require(rewardToken.transfer(devAddr, devFee), "LydiaStrategyForLP::_reinvest, dev"); } uint adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { require(rewardToken.transfer(owner(), adminFee), "LydiaStrategyForLP::_reinvest, admin"); } uint reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { require(rewardToken.transfer(msg.sender, reinvestFee), "LydiaStrategyForLP::_reinvest, reward"); } uint depositTokenAmount = _convertRewardTokensToDepositTokens( amount.sub(devFee).sub(adminFee).sub(reinvestFee) ); _stakeDepositTokens(depositTokenAmount); totalDeposits = totalDeposits.add(depositTokenAmount); emit Reinvest(totalDeposits, totalSupply); } function _stakeDepositTokens(uint amount) private { require(amount > 0, "LydiaStrategyForLP::_stakeDepositTokens"); stakingContract.deposit(PID, amount); } function checkReward() public override view returns (uint) { uint pendingReward = stakingContract.pendingLyd(PID, address(this)); uint contractBalance = rewardToken.balanceOf(address(this)); return pendingReward.add(contractBalance); } /** * @notice Converts reward tokens to deposit tokens * @dev Always converts through router; there are no price checks enabled * @return deposit tokens received */ function _convertRewardTokensToDepositTokens(uint amount) private returns (uint) { uint amountIn = amount.div(2); require(amountIn > 0, "LydiaStrategyForLP::_convertRewardTokensToDepositTokens"); // swap to token0 uint path0Length = 3; address[] memory path0 = new address[](path0Length); path0[0] = address(rewardToken); path0[1] = WAVAX; path0[2] = IPair(address(depositToken)).token0(); uint amountOutToken0 = amountIn; if (path0[0] != path0[path0Length - 1]) { uint[] memory amountsOutToken0 = router.getAmountsOut(amountIn, path0); amountOutToken0 = amountsOutToken0[amountsOutToken0.length - 1]; router.swapExactTokensForTokens(amountIn, amountOutToken0, path0, address(this), block.timestamp); } // swap to token1 uint path1Length = 2; address[] memory path1 = new address[](path1Length); path1[0] = path0[0]; path1[1] = IPair(address(depositToken)).token1(); uint amountOutToken1 = amountIn; if (path1[0] != path1[path1Length - 1]) { uint[] memory amountsOutToken1 = router.getAmountsOut(amountIn, path1); amountOutToken1 = amountsOutToken1[amountsOutToken1.length - 1]; router.swapExactTokensForTokens(amountIn, amountOutToken1, path1, address(this), block.timestamp); } (,,uint liquidity) = router.addLiquidity( path0[path0Length - 1], path1[path1Length - 1], amountOutToken0, amountOutToken1, 0, 0, address(this), block.timestamp ); return liquidity; } /** * @notice Estimate recoverable balance * @return deposit tokens */ function estimateDeployedBalance() external override view returns (uint) { (uint depositBalance, ) = stakingContract.userInfo(PID, address(this)); return depositBalance; } function rescueDeployedFunds(uint minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint balanceBefore = depositToken.balanceOf(address(this)); stakingContract.emergencyWithdraw(PID); uint balanceAfter = depositToken.balanceOf(address(this)); require(balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "LydiaStrategyForLP::rescueDeployedFunds"); totalDeposits = balanceAfter; emit Reinvest(totalDeposits, totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } }
Update devAddr newValue address/
function updateDevAddr(address newValue) public { require(msg.sender == devAddr); emit UpdateDevAddr(devAddr, newValue); devAddr = newValue; }
914,046
//SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IEternalStorage.sol"; import "../interfaces/IEternalTreasury.sol"; import "../interfaces/IGage.sol"; /** * @title Gage contract * @author Nobody (me) * @notice Implements the basic necessities for any gage */ abstract contract Gage is Context, IGage { /////–––««« Variables: Addresses and Interfaces »»»––––\\\\\ // The Eternal Storage IEternalStorage public immutable eternalStorage; // The Eternal Treasury IEternalTreasury internal treasury; /////–––««« Variables: Gage data »»»––––\\\\\ // Holds all users' information in the gage mapping (address => UserData) internal userData; // The id of the gage uint256 internal immutable id; // The maximum number of users in the gage uint256 internal immutable capacity; // Keeps track of the number of users left in the gage uint256 internal users; // The state of the gage Status internal status; // Determines whether the gage is a loyalty gage or not bool private immutable loyalty; /////–––««« Constructor »»»––––\\\\\ constructor (uint256 _id, uint256 _users, address _eternalStorage, bool _loyalty) { require(_users > 1, "Gage needs at least two users"); id = _id; capacity = _users; loyalty = _loyalty; eternalStorage = IEternalStorage(_eternalStorage); } /////–––««« Variable state-inspection functions »»»––––\\\\\ /** * @notice View the number of stakeholders in the gage. * @return uint256 The number of stakeholders in the selected gage */ function viewGageUserCount() external view override returns (uint256) { return users; } /** * @notice View the total user capacity of the gage. * @return uint256 The total user capacity */ function viewCapacity() external view override returns (uint256) { return capacity; } /** * @notice View the status of the gage. * @return uint256 An integer indicating the status of the gage */ function viewStatus() external view override returns (uint256) { return uint256(status); } /** * @notice View whether the gage is a loyalty gage or not. * @return bool True if the gage is a loyalty gage, else false */ function viewLoyalty() external view override returns (bool) { return loyalty; } /** * @notice View a given user's gage data. * @param user The address of the specified user * @return address The address of this user's deposited asset * @return uint256 The amount of this user's deposited asset * @return uint256 The risk percentage for this user */ function viewUserData(address user) external view override returns (address, uint256, uint256) { UserData storage data = userData[user]; return (data.asset, data.amount, data.risk); } }
View whether the gage is a loyalty gage or not. return bool True if the gage is a loyalty gage, else false/
function viewLoyalty() external view override returns (bool) { return loyalty; }
12,851,048
pragma solidity ^0.4.13; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } } 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() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) { require(_wallet != 0x0); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; function RefundableCrowdsale(uint256 _goal) { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // We're overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } function goalReached() public constant returns (bool) { return weiRaised >= goal; } } 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 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 BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // 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 constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant 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)) 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)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.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 constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { 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 BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } 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(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract StampifyToken is MintableToken, PausableToken, BurnableToken { string public constant name = "Stampify Token"; string public constant symbol = "STAMP"; uint8 public constant decimals = 18; function StampifyToken() { pause(); } } contract TokenCappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; uint256 public tokenSold; function TokenCappedCrowdsale(uint256 _cap) { require(_cap > 0); cap = _cap; } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiToTokens(weiAmount, now); require(tokenSold.add(tokens) <= cap); // update state weiRaised = weiRaised.add(weiAmount); tokenSold = tokenSold.add(tokens); token.mint(beneficiary, tokens); TokenPurchase( msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function weiToTokens(uint256 weiAmount, uint256 time) internal returns (uint256) { uint256 _rate = getRate(time); return weiAmount.mul(_rate); } // low level get rate function // override to create custom rate function, like giving bonus for early contributors or whitelist addresses function getRate(uint256 time) internal returns (uint256) { return rate; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool capReached = tokenSold >= cap; return super.hasEnded() || capReached; } } contract StampifyTokenSale is TokenCappedCrowdsale, RefundableCrowdsale, Pausable { using SafeMath for uint256; // Constants uint256 constant private BIG_BUYER_THRESHOLD = 40 * 10**18; // 40 ETH uint256 constant public RESERVE_AMOUNT = 25000000 * 10**18; // 25M STAMPS // Modifiers modifier isValidDataString(uint256 weiAmount, bytes data) { if (weiAmount > BIG_BUYER_THRESHOLD) { require(bytesToBytes32(data) == dataWhitelist[1]); } else { require(bytesToBytes32(data) == dataWhitelist[0]); } _; } // Data types struct TeamMember { address wallet; // Address of team member's wallet address vault; // Address of token timelock vault uint64 shareDiv; // Divisor to be used to get member's token share } // Private uint64[4] private salePeriods; bytes32[2] private dataWhitelist; uint8 private numTeamMembers; mapping (uint => address) private memberLookup; // Public mapping (address => TeamMember) public teamMembers; // founders & contributors vaults (beneficiary,vault) + Org's multisig function StampifyTokenSale( uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, uint256 _cap, address _wallet, uint64[4] _salePeriods, bytes32[2] _dataWhitelist ) TokenCappedCrowdsale(_cap) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(_startTime, _endTime, _rate, _wallet) { require(_goal.mul(_rate) <= _cap); for (uint8 i = 0; i < _salePeriods.length; i++) { require(_salePeriods[i] > 0); } salePeriods = _salePeriods; dataWhitelist = _dataWhitelist; } function createTokenContract() internal returns (MintableToken) { return new StampifyToken(); } function () whenNotPaused isValidDataString(msg.value, msg.data) payable { super.buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) whenNotPaused isValidDataString(msg.value, msg.data) public payable { super.buyTokens(beneficiary); } // gamification function getRate(uint256 time) internal returns (uint256) { if (time <= salePeriods[0]) { return 750; } if (time <= salePeriods[1]) { return 600; } if (time <= salePeriods[2]) { return 575; } if (time <= salePeriods[3]) { return 525; } return rate; } function setTeamVault(address _wallet, address _vault, uint64 _shareDiv) onlyOwner public returns (bool) { require(now < startTime); // Only before sale starts ! require(_wallet != address(0)); require(_vault != address(0)); require(_shareDiv > 0); require(numTeamMembers + 1 <= 8); memberLookup[numTeamMembers] = _wallet; teamMembers[_wallet] = TeamMember(_wallet, _vault, _shareDiv); numTeamMembers++; return true; } function getTeamVault(address _wallet) constant public returns (address) { require(_wallet != address(0)); return teamMembers[_wallet].vault; } function finalization() internal { if (goalReached()) { bool capReached = tokenSold >= cap; if (!capReached) { uint256 tokenUnsold = cap.sub(tokenSold); // Mint unsold tokens to sale's address & burn them immediately require(token.mint(this, tokenUnsold)); StampifyToken(token).burn(tokenUnsold); } uint256 tokenReserved = RESERVE_AMOUNT; for (uint8 i = 0; i < numTeamMembers; i++) { TeamMember memory member = teamMembers[memberLookup[i]]; if (member.vault != address(0)) { var tokenAmount = tokenSold.div(member.shareDiv); require(token.mint(member.vault, tokenAmount)); tokenReserved = tokenReserved.sub(tokenAmount); } } // Allocate remaining reserve to multisig wallet require(token.mint(wallet, tokenReserved)); // Finish token minting & unpause transfers require(token.finishMinting()); StampifyToken(token).unpause(); } super.finalization(); } function bytesToBytes32(bytes memory source) returns (bytes32 result) { if (source.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } }
low level get rate function override to create custom rate function, like giving bonus for early contributors or whitelist addresses
function getRate(uint256 time) internal returns (uint256) { return rate; }
12,942,188
./full_match/1/0x1F1AD3733B75aE383bdeAa4b14E5f628BBFb2012/sources/contracts/InheritanceArtWarhol.sol
The following functions are overrides required by Solidity.
function _beforeTokenTransfer( address from, address to, uint256 tokenId, uint256 batchSize ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId, batchSize); }
16,468,568
./partial_match/421613/0x29FCD623D8329De1B8D7571EA7251Da291dE2380/sources/contracts/bond/BondDepository.sol
creates a new market type current price should be in 18 decimals. _quoteToken token used to deposit _market [capacity (in PANA or quote), initial price / PANA (18 decimals), debt buffer (3 decimals)] _booleans [capacity in quote, quote is reserve, quote is LP, fixed term] _terms [vesting length (if fixed term) or vested timestamp, conclusion timestamp] _intervals [deposit interval (seconds), tune interval (seconds)] return id_ ID of new bond market/ the length of the program, in seconds the decimal count of the quote token depositing into, or getting info for, the created market uses this ID
) external override onlyPolicy returns (uint256 id_) { uint256 secondsToConclusion = _terms[1] - block.timestamp; uint256 decimals = IERC20Metadata(address(_quoteToken)).decimals(); uint256 targetDebt = uint256(_booleans[0] ? (_market[0] * 1e36 / _market[1]) / 10 ** decimals : _market[0] ); uint256 maxPayout = uint256(targetDebt * _intervals[0] / secondsToConclusion); uint256 controlVariable = _market[1] * treasury.baseSupply() / targetDebt; id_ = markets.length; function create( IERC20 _quoteToken, uint256[3] memory _market, bool[4] memory _booleans, uint256[2] memory _terms, uint32[2] memory _intervals markets.push(Market({ quoteToken: _quoteToken, quoteTokenIsReserve: _booleans[1], capacityInQuote: _booleans[0], capacity: _market[0], totalDebt: targetDebt, maxPayout: maxPayout, purchased: 0, sold: 0 })); terms.push(Terms({ fixedTerm: _booleans[3], controlVariable: uint256(controlVariable), vesting: uint48(_terms[0]), conclusion: uint48(_terms[1]), maxDebt: uint256(maxDebt) })); metadata.push(Metadata({ lastTune: uint48(block.timestamp), lastDecay: uint48(block.timestamp), length: uint48(secondsToConclusion), depositInterval: _intervals[0], tuneInterval: _intervals[1], quoteDecimals: uint8(decimals), quoteIsLPToken: _booleans[2] })); marketsForQuote[address(_quoteToken)].push(id_); emit CreateMarket(id_, address(pana), address(_quoteToken), _market[1]); if (_booleans[1]) _quoteToken.approve(address(treasury), type(uint256).max); }
16,826,076
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; /// @title An Example Bar /// @dev Example Details Bar interface IBar { /// @notice Notice of T /// @dev Dev of T /// @param paramA A number /// @param paramB An address struct T { uint256 paramA; address paramB; } /// QWEQWEQWE /// @param t the pair to set function set(T memory t) external; function boop(uint256 bar) external; /// @notice Emitted when transfer /// @dev Transfer some stuff /// @param foo Amount of stuff event Transfer(uint256 foo); /// @notice Thrown when doh error Doh(bool yay); } /// @title Bar contract /// @author Primitive /// @notice Manages the bar /// @dev Blablou contract Bar is IBar, Ownable { /// @notice Buyer's address /// @return Buyer's address uint40 public buyerAddress; /// @notice Buyer's amounts /// @return Buyer's amounts for address mapping(address => uint) public buyerAmounts; function set(T memory t) external {} /// @notice Cool function bro function boop(uint256 bar) external {} /// @notice Baaps the yaps1 /// @param bar1 Number of bar function baap(uint256 bar1) external {} /// @notice Baaps the yaps /// @param bar Number of bar /// @param aar Address of aar function baap(uint256 bar, address aar) external {} }
Baaps the yaps1 bar1 Number of bar
function baap(uint256 bar1) external {}
6,484,280
./full_match/97/0xDB2949F540eDbCd7FdEc8Fe64cA935CBD4A0c9AA/sources/contracts/protocol/configuration/PoolAddressesProvider.sol
@inheritdoc IPoolAddressesProvider
function setACLAdmin(address newAclAdmin) external override onlyOwner { address oldAclAdmin = _addresses[ACL_ADMIN]; _addresses[ACL_ADMIN] = newAclAdmin; emit ACLAdminUpdated(oldAclAdmin, newAclAdmin); }
3,286,000
pragma solidity ^0.5.11; //import './zeppeline/token/ERC20/ERC20Mintable.sol'; import './Ticket.sol'; import './TicketSale.sol'; contract TicketFactory { //address Ticket; //address TicketSale; function createTicket(string memory name) public returns(address ticket_address) { // decimals = 0, cause you can't divide one ticket to parts uint8 dec = 0; // TODO: refactor to contract type ticket_address = address(new Ticket(name,dec)); return ticket_address; } function createTicketSale(address payable orginizer, uint price, Ticket token, uint amount) public returns(address ticket_sale) { // calculate price uint256 cena = calculateRate(price); // TODO: refactor to contract type ticket_sale = address(new TicketSale(cena, orginizer, token)); token.mint(ticket_sale,amount); } function calculateRate (uint256 price) internal returns (uint256 rate_p) { // rate = price * 1 eth rate_p = price * (1 ether); return rate_p; } }
calculate price TODO: refactor to contract type
function createTicketSale(address payable orginizer, uint price, Ticket token, uint amount) public returns(address ticket_sale) { uint256 cena = calculateRate(price); ticket_sale = address(new TicketSale(cena, orginizer, token)); token.mint(ticket_sale,amount); }
6,464,586
./full_match/8453/0x1a920B29eBD437074225cAeE44f78FC700B27a5d/sources/contracts/deposit-service/AxelarDepositService.sol
This method is meant to be called directly by user to send native token cross-chain Wrapping the native currency and into WETH-like token Not doing safe approval as gateway will revert anyway if approval fails We expect allowance to always be 0 at this point Sending the token trough the gateway
function sendNative(string calldata destinationChain, string calldata destinationAddress) external payable { address wrappedTokenAddress = wrappedToken(); uint256 amount = msg.value; if (amount == 0) revert NothingDeposited(); IWETH9(wrappedTokenAddress).approve(gateway, amount); IAxelarGateway(gateway).sendToken(destinationChain, destinationAddress, wrappedSymbol(), amount); }
11,536,311
./full_match/43114/0xfE0373d07a44b6A7e98ECbeD78734dC88b5858E5/sources/hyToken.sol
Toggles minter role for an account _minter address of the account to toggle minter role return bool true if account is now a minter, false otherwise/
function toggleMinter(address _minter) external onlyOwner returns (bool){ require(_minter != address(0)); minters[_minter] = !minters[_minter]; return minters[_minter]; }
4,616,993
pragma solidity ^0.5.0; /** * @title StoreExtractor * @dev This library has functions to extract elements */ library StoreExtractor { // StoreFront structure struct StoreFront { uint id; bool active; string name; address storeOwner; } // Product structure struct Product { uint id; uint price; uint qty; bool active; string name; string imageId; address productOwner; } /** * @dev extract store fronts from a list of store front IDs * @return sFID[], name[], prodQty[] */ function extractStoreFronts(uint[] storage sFIDs, uint from, uint to, mapping(uint => StoreFront) storage storeFronts, mapping(uint => uint) storage storeFrontProductsActive) internal view returns (uint[] memory, uint[] memory, bool[] memory, bytes32[] memory) { // get actual end of range uint dest = to >= sFIDs.length ? sFIDs.length : to; // range difference uint diff = to - from; // sometimes the range difference might be more // than the data length. In such cases, we provide a fallback diff = diff > dest ? dest : diff; // extract all store front props; uint[] memory productsQtys = new uint[] (diff); bool[] memory active = new bool[] (diff); bytes32[] memory names = new bytes32[] (diff); //Get store fronts data for(uint i = from; i < dest; i++) { uint sfid = sFIDs[i]; StoreFront memory storeFront = storeFronts[sfid]; // Get store front's name string memory sfName = storeFront.name; bytes32 _name; // convert to bytes32 assembly { _name := mload(add(sfName, 32)) } names[i] = _name; active[i] = storeFront.active; productsQtys[i] = storeFrontProductsActive[sfid]; } return (sFIDs, productsQtys, active, names); } /** * @dev extract products from a list of store front IDs * @return sFID[], name[], prodQty[] */ function extractProducts(uint[] storage prods, uint from, uint to, mapping (uint => Product) storage prodDetails) internal view returns (uint[] memory id, uint[] memory price, uint[] memory qty, bool[] memory active, bytes32[] memory name) { // get actual end of range uint dest = to >= prods.length ? prods.length : to; // range difference uint diff = to - from; // sometimes the range difference might be more // than the data length. In such cases, we provide a fallback diff = diff > dest ? dest : diff; id = new uint[] (diff); price = new uint[] (diff); qty = new uint[] (diff); active = new bool[] (diff); name = new bytes32[](diff); //Go through the products id and map props into array of for(uint i = from; i < dest; i++) { uint pid = prods[i]; Product memory prod = prodDetails[pid]; id[i] = prod.id; price[i] = prod.price; qty[i] = prod.qty; active[i] = prod.active; string memory prodName = prod.name; bytes32 _name; //convert string to bytes32 assembly { _name := mload(add(prodName, 32)) } name[i] = _name; } } }
extract store fronts from a list of store front IDs return sFID[], name[], prodQty[]/ get actual end of range range difference sometimes the range difference might be more than the data length. In such cases, we provide a fallback extract all store front props;Get store fronts data Get store front's name convert to bytes32
function extractStoreFronts(uint[] storage sFIDs, uint from, uint to, mapping(uint => StoreFront) storage storeFronts, mapping(uint => uint) storage storeFrontProductsActive) internal view returns (uint[] memory, uint[] memory, bool[] memory, bytes32[] memory) { uint dest = to >= sFIDs.length ? sFIDs.length : to; uint diff = to - from; diff = diff > dest ? dest : diff; uint[] memory productsQtys = new uint[] (diff); bool[] memory active = new bool[] (diff); bytes32[] memory names = new bytes32[] (diff); for(uint i = from; i < dest; i++) { uint sfid = sFIDs[i]; StoreFront memory storeFront = storeFronts[sfid]; string memory sfName = storeFront.name; bytes32 _name; assembly { _name := mload(add(sfName, 32)) } names[i] = _name; active[i] = storeFront.active; productsQtys[i] = storeFrontProductsActive[sfid]; } return (sFIDs, productsQtys, active, names); }
12,605,019
/** * @title Funding Vault * @author Clément Lesaege - <clement@lesaege.com> * Bug Bounties: This code hasn't undertaken a bug bounty program yet. */ pragma solidity ^0.4.15; import "../Arbitrable.sol"; import "minimetoken/contracts/MiniMeToken.sol"; /** @title Funding Vault * A contract storing the ETH raised in a crowdfunding event. * Funds are delivered when milestones are reached. * The team can claim a milestone is reached. Token holders will have some time to dispute that claim. * When some token holders vote to dispute the claim, extra time is given to other token holders to dispute that claim. * If a sufficient amount of token holders dispute it. A dispute is created and the arbitrator will decide if the milestone has been reached. * When there is a disagreement a vote token is created. Holders should send the voteToken to the Vault to disagree with the milestone. * Token holders can also claim that the team failed to deliver and ask for the remaining ETH to be given back to a different contract. * This contract can be the vault of another team, or a contract to reimburse. */ contract FundingVault is Arbitrable { address public team; MiniMeToken public token; address public funder; uint public disputeThreshold; uint public claimToWithdrawTime; uint public additionalTimeToWithdraw; uint public timeout; struct Milestone { uint amount; // The maximum amount which can be unlocked for this milestone. uint amountClaimed; // The current amount which is claimed. uint claimTime; // The time the current claim was made. Or 0 if it's not currently claimed. bool disputed; // True if a dispute has been raised. uint feeTeam; // Arbitration fee paid by the team. uint feeHolders; // Arbitration fee paid by token holders. MiniMeToken voteToken; // Forked token which will be used to vote. uint disputeID; // ID of the dispute if this claim is disputed. uint lastTotalFeePayment; // Time of the last total fee payment, useful for timeouts. bool lastTotalFeePaymentIsTeam; // True if the last interaction is from the team. address payerForHolders; // The address who first paid the arbitration fee and will be refunded in case of victory. } Milestone[] public milestones; mapping(uint => uint) public disputeIDToMilstoneID; // Map (disputeID => milestoneID). uint ousterID; //The ID of the milestone created at construction. To be disputed when the funders claim the team is not doing their job. bool canChangeTeam; //True if the holders have attempted an oust and won the dispute. Allows the funder to select a new team (only once). uint8 constant AMOUNT_OF_CHOICES = 2; uint8 constant TEAM_WINS = 1; uint8 constant HOLDERS_WINS = 2; /** @dev Constructor. Choose the arbitrator. * @param _arbitrator The arbitrator of the contract. * @param _contractHash Keccak256 hash of the plain text contract. * @param _team The address of the team who will be able to claim milestone completion. * @param _token The token whose holders are able to dispute milestone claims. * @param _funder The party putting funds in the vault. * @param _disputeThreshold The ‱ of tokens required to dispute a milestone. * @param _claimToWithdrawTime The base time in seconds after a claim is considered non-disputed (i.e if no token holders dispute it). * @param _additionalTimeToWithdraw The time in seconds which is added per ‱ of tokens disputing the claim. * @param _timeout Maximum time to pay arbitration fees after the other side did. */ constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData, bytes32 _contractHash, address _team, address _token, address _funder, uint _disputeThreshold, uint _claimToWithdrawTime, uint _additionalTimeToWithdraw, uint _timeout) public Arbitrable(_arbitrator,_arbitratorExtraData,_contractHash) { team=_team; token=MiniMeToken(_token); funder=_funder; disputeThreshold=_disputeThreshold; claimToWithdrawTime=_claimToWithdrawTime; additionalTimeToWithdraw=_additionalTimeToWithdraw; timeout=_timeout; ousterID = milestones.push(Milestone({ //Create a base milestone to be disputed when the funders claim the team is not doing their job. amount:0, amountClaimed:0, claimTime:0, disputed:false, feeTeam:0, feeHolders:0, voteToken:MiniMeToken(0x0), disputeID:0, lastTotalFeePayment:0, lastTotalFeePaymentIsTeam:false, payerForHolders:0x0 }))-1; canChangeTeam = false; } /** @dev Give the funds for a milestone. * @return milestoneID The ID of the milestone which was created. */ function fundMilestone() public payable returns(uint milestoneID) { require(msg.sender==funder); return milestones.push(Milestone({ amount:msg.value, amountClaimed:0, claimTime:0, disputed:false, feeTeam:0, feeHolders:0, voteToken:MiniMeToken(0x0), disputeID:0, lastTotalFeePayment:0, lastTotalFeePaymentIsTeam:false, payerForHolders:0x0 }))-1; } //Restricts Milestone function with functionality not necessary for Ouster. modifier isNotOuster(uint _milestoneID) { require(ousterID != _milestoneID); _; } /** @dev Claim funds of a milestone. * @param _milestoneID The ID of the milestone. * @param _amount The amount claim. Note that the team can claim less than the amount of a milestone. This allows partial completion claims. */ function claimMilestone(uint _milestoneID, uint _amount) public isNotOuster(_milestoneID) { Milestone storage milestone=milestones[_milestoneID]; require(msg.sender==team); require(milestone.claimTime==0); // Verify another claim is not active. require(milestone.amount<=_amount); milestone.claimTime=now; } /** @dev Make a forked token to dispute a claim. * This avoid creating a token all the time, since most milestones should not be disputed. * @param _milestoneID The ID of the milestone. */ function makeVoteToken(uint _milestoneID) public { Milestone storage milestone=milestones[_milestoneID]; if( ousterID != _milestoneID ) { require(milestone.claimTime!=0); } // The milestone is currently claimed by the team, unless this is the ouster. require(address(milestone.voteToken)==0x0); // Token has not already been made. milestone.voteToken=MiniMeToken(token.createCloneToken( "", token.decimals(), "", block.number, true )); } /** @dev Pay fee to dispute a milestone. To be called by parties claiming the milestone was not completed. * The first party to pay the fee entirely will be reimbursed if the dispute is won. * Note that holders can make a smart contract to crowdfund the fee. * In the rare event the arbitrationCost is increased, anyone can pay the extra, but it is always the first payer who can be reimbursed. * @param _milestoneID The milestone which is disputed. */ function payDisputeFeeByHolders(uint _milestoneID) public payable { Milestone storage milestone=milestones[_milestoneID]; uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); require(!milestone.disputed); // The milestone is not already disputed. require(milestone.voteToken.balanceOf(this) >= (disputeThreshold*milestone.voteToken.totalSupply())/1000); // There is enough votes. require(milestone.feeHolders<arbitrationCost); // Fee has not be paid before. require(milestone.feeHolders+msg.value>=arbitrationCost); // Enough is paid. milestone.feeHolders+=msg.value; if (milestone.payerForHolders==0x0) milestone.payerForHolders=msg.sender; if (milestone.feeTeam>=arbitrationCost) { // Enough has been paid by all sides. createDispute(_milestoneID,arbitrationCost); } else if (milestone.lastTotalFeePayment==0) { // First time the fee is paid. milestone.lastTotalFeePayment=now; } else if(milestone.lastTotalFeePaymentIsTeam) { // The team was the last one who had paid entirely. milestone.lastTotalFeePaymentIsTeam=false; milestone.lastTotalFeePayment=now; } } /** @dev Pay fee to for a milestone dispute. To be called by the team when the holders have enough votes and fee paid. * @param _milestoneID The milestone which is disputed. */ function payDisputeFeeByTeam(uint _milestoneID) public payable { Milestone storage milestone=milestones[_milestoneID]; uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); require(msg.sender==team); require(!milestone.disputed); // A dispute has not been created yet. require(milestone.voteToken.balanceOf(this) >= (disputeThreshold*milestone.voteToken.totalSupply())/1000); // There is enough votes. require(milestone.feeTeam+msg.value>=arbitrationCost); // Make sure enough is paid. Team can't pay partially. milestone.feeTeam+=msg.value; if (milestone.feeHolders>=arbitrationCost) { // Enough has been paid by all sides. createDispute(_milestoneID,arbitrationCost); } else if (milestone.lastTotalFeePayment==0) { // First time the fee is paid. milestone.lastTotalFeePayment=now; milestone.lastTotalFeePaymentIsTeam=true; } else if(!milestone.lastTotalFeePaymentIsTeam) { // The holders were the last ones who had paid entirely. milestone.lastTotalFeePaymentIsTeam=true; milestone.lastTotalFeePayment=now; } } /** @dev Create a dispute. * @param _milestoneID The milestone which is disputed. * @param _arbitrationCost The amount which should be paid to the arbitrator. */ function createDispute(uint _milestoneID, uint _arbitrationCost) internal { Milestone storage milestone=milestones[_milestoneID]; milestone.disputed=true; milestone.feeTeam-=_arbitrationCost; // Remove the fee from the team pool for accounting. Note that at this point it does not matter which fee variable we decrement. milestone.disputeID=arbitrator.createDispute(AMOUNT_OF_CHOICES,arbitratorExtraData); disputeIDToMilstoneID[milestone.disputeID]=_milestoneID; } /** @dev Withdraw the money claimed in a milestone. * To be called when a dispute has not been created within the time limit. * @param _milestoneID The milestone which is disputed. */ function withdraw(uint _milestoneID) public isNotOuster(_milestoneID) { Milestone storage milestone=milestones[_milestoneID]; require(msg.sender==team); require(!milestone.disputed); require(milestone.voteToken.balanceOf(this) < (disputeThreshold*milestone.voteToken.totalSupply())/1000); // There is not enough votes. require((now-milestone.claimTime) > claimToWithdrawTime+(additionalTimeToWithdraw*milestone.voteToken.balanceOf(this))/(1000*milestone.voteToken.totalSupply())); team.transfer(milestone.amountClaimed+milestone.feeTeam+milestone.feeHolders); // Pay the amount claimed and the unused fees. milestone.amount-=milestone.amountClaimed; milestone.amountClaimed=0; milestone.claimTime=0; milestone.feeTeam=0; milestone.feeHolders=0; } // TODO: Timeouts /** @dev Timeout to use when the holders don't pay the fee. * @param _milestoneID The milestone which is disputed. */ function timeoutByTeam(uint _milestoneID) public { Milestone storage milestone=milestones[_milestoneID]; require(msg.sender==team); require(milestone.lastTotalFeePaymentIsTeam); require(now-milestone.lastTotalFeePayment > timeout); team.transfer(milestone.amountClaimed+milestone.feeTeam+milestone.feeHolders); // Pay the amount claimed and the unused fees to the team. milestone.amount-=milestone.amountClaimed; milestone.amountClaimed=0; milestone.claimTime=0; milestone.feeTeam=0; milestone.feeHolders=0; milestone.voteToken=MiniMeToken(0x0); milestone.lastTotalFeePayment=0; milestone.lastTotalFeePaymentIsTeam=false; milestone.payerForHolders=0x0; } /** @dev Timeout to use whe the team don't pay the fee. * @param _milestoneID The milestone which is disputed. */ function timeoutByHolders(uint _milestoneID) public { Milestone storage milestone=milestones[_milestoneID]; require(!milestone.lastTotalFeePaymentIsTeam); require(now-milestone.lastTotalFeePayment > timeout); milestone.payerForHolders.transfer(milestone.feeTeam+milestone.feeHolders); // Pay the unused fees to the payer for holders. milestone.amountClaimed=0; milestone.claimTime=0; milestone.disputed=false; milestone.feeTeam=0; milestone.feeHolders=0; milestone.voteToken=MiniMeToken(0x0); milestone.lastTotalFeePayment=0; milestone.payerForHolders=0x0; canChangeTeam = true; //since the team was nonresponsive, the holders are free to change the team. } /** @dev Appeal an appealable ruling. * Transfer the funds to the arbitrator. * @param _milestoneID The milestone which is disputed. */ function appeal(uint _milestoneID) public payable { Milestone storage milestone=milestones[_milestoneID]; arbitrator.appeal.value(msg.value)(milestone.disputeID,arbitratorExtraData); } /** @dev Execute a ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal{ Milestone storage milestone=milestones[disputeIDToMilstoneID[_disputeID]]; require(milestone.voteToken.balanceOf(this) >= (disputeThreshold*milestone.voteToken.totalSupply())/1000); // Make sure there is enough votes to protect against a malicious arbitrator. uint _milestoneID = disputeIDToMilstoneID[_disputeID]; if (_ruling==TEAM_WINS) { team.transfer(milestone.amountClaimed+milestone.feeTeam+milestone.feeHolders); // Pay the amount claimed and the unused fees to the team. milestone.amount-=milestone.amountClaimed; milestone.amountClaimed=0; milestone.claimTime=0; milestone.disputed=false; milestone.feeTeam=0; milestone.feeHolders=0; milestone.voteToken=MiniMeToken(0x0); milestone.disputeID=0; milestone.lastTotalFeePayment=0; milestone.lastTotalFeePaymentIsTeam=false; milestone.payerForHolders=0x0; } else if (_ruling==HOLDERS_WINS) { milestone.payerForHolders.transfer(milestone.feeTeam+milestone.feeHolders); // Pay the unused fees to the payer for holders. milestone.amountClaimed=0; milestone.claimTime=0; milestone.disputed=false; milestone.feeTeam=0; milestone.feeHolders=0; milestone.voteToken=MiniMeToken(0x0); milestone.disputeID=0; milestone.lastTotalFeePayment=0; milestone.lastTotalFeePaymentIsTeam=false; milestone.payerForHolders=0x0; if( ousterID == _milestoneID ) { //if this is the ouster milestone canChangeTeam = true; //allow the funder to change the team } } } /** @dev Change the team. Note that the holders would have to make * the funder a votable contract if they want a vote on who the new team will be. * @param _newTeam the new team. */ function changeTeam(address _newTeam) public { require(msg.sender == funder); //The sender must be the funder. require(canChangeTeam); team = _newTeam; canChangeTeam = false; //This can only be called once. } }
TODO: Timeouts Timeout to use when the holders don't pay the fee. _milestoneID The milestone which is disputed./
function timeoutByTeam(uint _milestoneID) public { Milestone storage milestone=milestones[_milestoneID]; require(msg.sender==team); require(milestone.lastTotalFeePaymentIsTeam); require(now-milestone.lastTotalFeePayment > timeout); milestone.amount-=milestone.amountClaimed; milestone.amountClaimed=0; milestone.claimTime=0; milestone.feeTeam=0; milestone.feeHolders=0; milestone.voteToken=MiniMeToken(0x0); milestone.lastTotalFeePayment=0; milestone.lastTotalFeePaymentIsTeam=false; milestone.payerForHolders=0x0; }
2,547,951
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../helpers/Ownable.sol"; /** * @title AIOW ERC20 token */ contract AIOW is Ownable { uint256 constant PERC_BASE = 10000; // = 100.00 % uint256 public constant SECONDS_IN_ONE_DAY = 86400; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 public totalSupply; string public name; string public symbol; uint8 public decimals; mapping(address => TransferRuleOutbound) public transferRulesOutbound; mapping(address => TransferRuleInbound[]) public transferRulesInbound; enum TransferRuleType { inbound, outbound } uint256 private ruleIdCounter; struct TransferRuleOutbound { uint8 id; // id of the rule, used to add to existing inbound rule with same id uint32 timelockUntil; // time at which the tokens become unlocked, and possibly the vesting starts uint16 vestingDurationDays; // number of days that the linear vesting is active uint16 vestingStartsAfterDays; // number of days after timelockUntil until the vesting starts uint16 percUnlockedAtTimeUnlock; // percentage of tokens unlocked at timelockUntil } struct TransferRuleInbound { uint8 id; // id of the rule, used to add to existing inbound rule with same id uint32 timelockUntil; // time at which the tokens become unlocked, and possibly the vesting starts uint16 vestingDurationDays; // number of days that the linear vesting is active uint16 vestingStartsAfterDays; // number of days after timelockUntil until the vesting starts uint16 percUnlockedAtTimeUnlock; // percentage of tokens unlocked at timelockUntil uint96 tokens; // number of tokens that this rule applies to bool isPool; // is this a pool, if yes sending tokens to this account adds them to this rule's `tokens`, see _beforeTokenTransfer } event TransferRuleInboundRegistered(address addr, TransferRuleInbound rule); event TransferRuleOutboundRegistered(address addr, TransferRuleOutbound rule); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /** * @notice constructor of the AIOW token contract * @dev sets the symbol, name, decimals and mints the totalSupply to the deployer * @param totalSupply_ The totalSupply of the token */ constructor(uint256 totalSupply_) { name = "AIOW"; symbol = "AIOW"; decimals = 18; // mint the total supply to the deployer totalSupply += totalSupply_; _balances[msg.sender] += totalSupply_; emit Transfer(address(0), msg.sender, totalSupply_); } /** * @notice checks transferrules before transferring tokens * @param from_ The address sending tokens * @param to_ The address receiving tokens * @param amount_ The address receiving tokens */ function _beforeTokenTransfer(address from_, address to_, uint256 amount_) internal virtual { // apply all the rules to verify the transferred amount is not above the total amount of unlocked tokens require(amount_ <= calcBalanceUnlocked(from_), "insufficient unlocked tokens"); // if the recipient is a pool, transfer the tokens to the inbound rule of the pool if (transferRulesInbound[to_].length >= 1 && transferRulesInbound[to_][0].isPool) { transferRulesInbound[to_][0].tokens += uint96(amount_); return; } // if there is an outbound rule we need to apply the outbound rule if (transferRulesOutbound[from_].id != 0) { TransferRuleOutbound memory trFromOutbound = transferRulesOutbound[from_]; bool foundMatchingToRule = false; // check if this outbound rule already exists inside the inbound rules of the recipient for (uint256 i = 0; i < transferRulesInbound[to_].length; i++) { if (trFromOutbound.id == transferRulesInbound[to_][i].id) { // if so increment the balance inside that rule foundMatchingToRule = true; transferRulesInbound[to_][i].tokens += uint96(amount_); break; } } // if we didnt find a matching rule, create it for the recipient if (!foundMatchingToRule) { transferRulesInbound[to_].push(TransferRuleInbound({ id: trFromOutbound.id, timelockUntil: trFromOutbound.timelockUntil, vestingStartsAfterDays: trFromOutbound.vestingStartsAfterDays, vestingDurationDays: trFromOutbound.vestingDurationDays, percUnlockedAtTimeUnlock: trFromOutbound.percUnlockedAtTimeUnlock, tokens: uint96(amount_), isPool: false })); } } } /** * @notice Calculates the total amount of unlocked tokens of an account * @param account_ The account for whom to calculate the unlocked tokens * @return The amount of unlocked tokens */ function calcBalanceUnlocked(address account_) public view returns (uint) { return _balances[account_] - calcBalanceLocked(account_); } /** * @notice Calculates the amount of still-locked tokens of a specific inbound transferrule * @param trInbound The inbound transferrule to check * @return The amount of locked tokens */ function calcBalanceLockedOfInboundRule(TransferRuleInbound memory trInbound) internal view returns (uint) { if (trInbound.timelockUntil > uint32(block.timestamp)) { // the tokens of this rule are still all locked return trInbound.tokens; } if (trInbound.percUnlockedAtTimeUnlock > 0) { // deduct the immediately unlocked amount of tokens from the rule's amount of locked tokens trInbound.tokens -= uint96(trInbound.tokens * trInbound.percUnlockedAtTimeUnlock / PERC_BASE); } if (trInbound.vestingDurationDays > 0) { uint256 daysPassedSinceUnlock = (uint32(block.timestamp) - trInbound.timelockUntil) / SECONDS_IN_ONE_DAY; if (daysPassedSinceUnlock <= trInbound.vestingStartsAfterDays) { // vesting didnt yet start return trInbound.tokens; } uint256 daysPassedSinceVestingStart = daysPassedSinceUnlock - trInbound.vestingStartsAfterDays; if (daysPassedSinceVestingStart >= trInbound.vestingDurationDays) { // the entire vesting period has ended, so all tokens of this rule are unlocked // this also ensures the last day's tokens pays out all the remaining tokens // since due to integer floor division the per day amount might be slightly less than the // total amount return 0; } // calculate how many of the tokens are still locked uint256 amountUnlockedPerDay = trInbound.tokens / trInbound.vestingDurationDays; uint256 totalUnlocked = daysPassedSinceVestingStart * amountUnlockedPerDay; return trInbound.tokens - totalUnlocked; } // this can only mean there is no vesting, and the timelock already passed, so all tokens are unlocked return 0; } /** * @notice Calculates the amount of still-locked tokens of all inbound transferrules of a specific account * @param account_ The account for whom to calculate the locked tokens * @return The amount of locked tokens */ function calcBalanceLocked(address account_) public view returns (uint) { uint256 lockedTokens = 0; // check the amount of locked tokens for each of the inbound rules on this account for (uint256 i = 0; i < transferRulesInbound[account_].length; i++) { TransferRuleInbound memory trFromInbound = transferRulesInbound[account_][i]; lockedTokens += calcBalanceLockedOfInboundRule(trFromInbound); } return lockedTokens; } /** * @notice Registers an inbound or outbound tansferrule on a specific account * @dev Can only be called by the owner * @param account_ The account to apply the transferrule to * @param ruleType Either inbound or outbound * @param timelockUntil_ Timestamp at which the tokens become unlocked, and possibly the vesting starts * @param vestingStartsAfterDays_ Number of days that the linear vesting is active * @param vestingDurationDays_ Number of days after timelockUntil until the vesting starts * @param percUnlockedAtTimeUnlock_ Percentage of tokens unlocked at timelockUntil * @param isPool_ True if this is a pool, false otherwise */ function registerTransferRule( address account_, TransferRuleType ruleType, uint32 timelockUntil_, uint16 vestingStartsAfterDays_, uint16 vestingDurationDays_, uint16 percUnlockedAtTimeUnlock_, bool isPool_ ) public onlyOwner { require(account_ != address(0), 'account is address zero'); require(timelockUntil_ > uint32(block.timestamp), 'timelockUntil already passed'); require(percUnlockedAtTimeUnlock_ > 0 || vestingDurationDays_ > 0, 'percUnlockedAtTimeUnlock and vestingDurationDays are zero'); require(percUnlockedAtTimeUnlock_ <= uint16(PERC_BASE), 'percUnlockedAtTimeUnlock above 100%'); if (ruleType == TransferRuleType.outbound) { // an account can only have one outbound transferrule require(transferRulesOutbound[account_].id == 0, 'account already has outbound rule'); transferRulesOutbound[account_] = TransferRuleOutbound({ id: uint8(++ruleIdCounter), // first rule will get id 1 timelockUntil: timelockUntil_, vestingDurationDays: vestingDurationDays_, vestingStartsAfterDays: vestingStartsAfterDays_, percUnlockedAtTimeUnlock: percUnlockedAtTimeUnlock_ }); emit TransferRuleOutboundRegistered(account_, transferRulesOutbound[account_]); } else { // ruleType == TransferRuleType.inbound transferRulesInbound[account_].push(TransferRuleInbound({ id: uint8(++ruleIdCounter), // first rule will get id 1 timelockUntil: timelockUntil_, vestingDurationDays: vestingDurationDays_, vestingStartsAfterDays: vestingStartsAfterDays_, percUnlockedAtTimeUnlock: percUnlockedAtTimeUnlock_, // if an outbound transferrule is applied to an account, // it will be converted to an inbound transferrule on the recipient. // this will set the `token` to the amount of tokens transferred // // otherwise, if an account has an inbound transferrule and isPool is True, // then every time tokens are transferred to this account, the `tokens` will be // incremented by the amount of transferred tokens. tokens: 0, isPool: isPool_ })); emit TransferRuleInboundRegistered(account_, transferRulesInbound[account_][transferRulesInbound[account_].length - 1]); } } // -------------------------------------------------------- // Regular ERC20 functions // -------------------------------------------------------- function balanceOf(address account_) public view returns (uint256) { return _balances[account_]; } function allowance(address owner_, address spender_) public view returns (uint256) { return _allowances[owner_][spender_]; } function transfer(address recipient_, uint256 amount_) public returns (bool) { _transfer(msg.sender, recipient_, amount_); return true; } function transferFrom(address sender_, address recipient_, uint256 amount_) public returns (bool) { _transfer(sender_, recipient_, amount_); uint256 currentAllowance = _allowances[sender_][msg.sender]; require(currentAllowance >= amount_, "ERC20: transfer amount exceeds allowance"); _approve(sender_, msg.sender, currentAllowance - amount_); return true; } function _transfer(address sender_, address recipient_, uint256 amount_) internal { require(sender_ != address(0), "ERC20: transfer from the zero address"); require(recipient_ != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender_, recipient_, amount_); uint256 senderBalance = _balances[sender_]; require(senderBalance >= amount_, "ERC20: transfer amount exceeds balance"); _balances[sender_] = senderBalance - amount_; _balances[recipient_] += amount_; emit Transfer(sender_, recipient_, amount_); } function approve(address spender_, uint256 amount_) public returns (bool) { _approve(msg.sender, spender_, amount_); return true; } function increaseAllowance(address spender_, uint256 addedValue_) public returns (bool) { _approve(msg.sender, spender_, _allowances[msg.sender][spender_] + addedValue_); return true; } function decreaseAllowance(address spender_, uint256 subtractedValue_) public returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender_]; require(currentAllowance >= subtractedValue_, "ERC20: decreased allowance below zero"); _approve(msg.sender, spender_, currentAllowance - subtractedValue_); return true; } function _approve(address owner_, address spender_, uint256 amount_) internal { require(owner_ != address(0), "ERC20: approve from the zero address"); require(spender_ != address(0), "ERC20: approve to the zero address"); _allowances[owner_][spender_] = amount_; emit Approval(owner_, spender_, amount_); } // -------------------------------------------------------- // Custom helper functions // -------------------------------------------------------- /** * @notice Retrieves the total balance, amount locked, and amount unlocked, of a specific account * @dev (balanceLocked + balanceUnlocked) == balanceTotal * @param account_ The account to apply the transferrule to * @return balanceTotal The ERC20 balance of the account * @return balanceLocked The tokens of the ERC20 balance that are still locked * @return balanceUnlocked The tokens of the ERC20 balance that are unlocked locked */ function balanceStatsOf(address account_) public view returns ( uint256 balanceTotal, uint256 balanceLocked, uint256 balanceUnlocked ) { return ( _balances[account_], calcBalanceLocked(account_), calcBalanceUnlocked(account_) ); } /** * @notice Retrieves info about a specific inbound transferrule of an account * @dev gives incorrect results if percUnlockedAtUnlock > 0 and vestingDurationDays > 0, i.e. do not use in that case * @param account_ The account * @param ruleId_ The id of the nbound transferrule * @return ruleBalanceTotal The total amount of tokens in the transferrule * @return ruleBalanceLocked The tokens of the transferrule that are still locked * @return ruleBalanceUnlocked The tokens of the transferrule that are unlocked */ function inboundRuleStatsOf(address account_, uint256 ruleId_) public view returns ( uint256 ruleBalanceTotal, uint256 ruleBalanceLocked, uint256 ruleBalanceUnlocked ) { for (uint256 i = 0; i < transferRulesInbound[account_].length; i++) { if (transferRulesInbound[account_][i].id == ruleId_) { TransferRuleInbound memory trFromInbound = transferRulesInbound[account_][i]; uint lockedTokens = calcBalanceLockedOfInboundRule(trFromInbound); uint unlockedTokens = trFromInbound.tokens - lockedTokens; return (trFromInbound.tokens, lockedTokens, unlockedTokens); } } revert('didnt find matching rule'); } /** * @notice Retrieves a list of all inbound transferrules of an account * @param _a The account * @return List of inbound transferrules */ function getInboundTransferRules(address _a) external view returns (TransferRuleInbound[] memory) { return transferRulesInbound[_a]; } }
Retrieves info about a specific inbound transferrule of an account gives incorrect results if percUnlockedAtUnlock > 0 and vestingDurationDays > 0, i.e. do not use in that case account_ The account ruleId_ The id of the nbound transferrule return ruleBalanceTotal The total amount of tokens in the transferrule return ruleBalanceLocked The tokens of the transferrule that are still locked return ruleBalanceUnlocked The tokens of the transferrule that are unlocked/
) { function balanceStatsOf(address account_) public view returns ( uint256 balanceTotal, uint256 balanceLocked, uint256 balanceUnlocked } function inboundRuleStatsOf(address account_, uint256 ruleId_) public view returns ( uint256 ruleBalanceTotal, uint256 ruleBalanceLocked, uint256 ruleBalanceUnlocked for (uint256 i = 0; i < transferRulesInbound[account_].length; i++) { if (transferRulesInbound[account_][i].id == ruleId_) { TransferRuleInbound memory trFromInbound = transferRulesInbound[account_][i]; uint lockedTokens = calcBalanceLockedOfInboundRule(trFromInbound); uint unlockedTokens = trFromInbound.tokens - lockedTokens; return (trFromInbound.tokens, lockedTokens, unlockedTokens); } } revert('didnt find matching rule'); function balanceStatsOf(address account_) public view returns ( uint256 balanceTotal, uint256 balanceLocked, uint256 balanceUnlocked } function inboundRuleStatsOf(address account_, uint256 ruleId_) public view returns ( uint256 ruleBalanceTotal, uint256 ruleBalanceLocked, uint256 ruleBalanceUnlocked for (uint256 i = 0; i < transferRulesInbound[account_].length; i++) { if (transferRulesInbound[account_][i].id == ruleId_) { TransferRuleInbound memory trFromInbound = transferRulesInbound[account_][i]; uint lockedTokens = calcBalanceLockedOfInboundRule(trFromInbound); uint unlockedTokens = trFromInbound.tokens - lockedTokens; return (trFromInbound.tokens, lockedTokens, unlockedTokens); } } revert('didnt find matching rule'); }
12,943,900
./partial_match/3/0xD647BDB40B188373f54b4966f0ccA21d17abC01C/sources/DistributeDividends.sol
Distribute dividends to the GandhijiMain contract. Can be called repeatedly until practically all dividends have been distributed. rounds How many rounds of dividend distribution do we want? Balance is very low. Not worth the gas to distribute.
function distribute(uint256 rounds) external { for (uint256 i = 0; i < rounds; i++) { if (address(this).balance < 0.001 ether) { break; } GandhijiMainContract.buy.value(address(this).balance)(0x0); GandhijiMainContract.exit(); } }
5,131,813
/** *Submitted for verification at Etherscan.io on 2018-06-12 */ pragma solidity ^0.4.13; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } library ArrayUtils { /** * Replace bytes in an array with bytes in another array, guarded by a bitmask * Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower) * * @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed. * @param array The original array * @param desired The target array * @param mask The mask specifying which bits can be changed * @return The updated byte array (the parameter will be modified inplace) */ function guardedArrayReplace(bytes memory array, bytes memory desired, bytes memory mask) internal pure { require(array.length == desired.length); require(array.length == mask.length); uint words = array.length / 0x20; uint index = words * 0x20; assert(index / 0x20 == words); uint i; for (i = 0; i < words; i++) { /* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */ assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } /* Deal with the last section of the byte array. */ if (words > 0) { /* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */ i = words; assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } else { /* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise. (bounds checks could still probably be optimized away in assembly, but this is a rare case) */ for (i = index; i < array.length; i++) { array[i] = ((mask[i] ^ 0xff) & array[i]) | (mask[i] & desired[i]); } } } /** * Test if two arrays are equal * Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol * * @dev Arrays must be of equal length, otherwise will return false * @param a First array * @param b Second array * @return Whether or not all bytes in the arrays are equal */ function arrayEq(bytes memory a, bytes memory b) internal pure returns (bool) { bool success = true; assembly { let length := mload(a) // if lengths don't match the arrays are not equal switch eq(length, mload(b)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(a, 0x20) let end := add(mc, length) for { let cc := add(b, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } /** * Unsafe write byte array into a memory location * * @param index Memory location * @param source Byte array to write * @return End memory index */ function unsafeWriteBytes(uint index, bytes source) internal pure returns (uint) { if (source.length > 0) { assembly { let length := mload(source) let end := add(source, add(0x20, length)) let arrIndex := add(source, 0x20) let tempIndex := index for { } eq(lt(arrIndex, end), 1) { arrIndex := add(arrIndex, 0x20) tempIndex := add(tempIndex, 0x20) } { mstore(tempIndex, mload(arrIndex)) } index := add(index, length) } } return index; } /** * Unsafe write address into a memory location * * @param index Memory location * @param source Address to write * @return End memory index */ function unsafeWriteAddress(uint index, address source) internal pure returns (uint) { uint conv = uint(source) << 0x60; assembly { mstore(index, conv) index := add(index, 0x14) } return index; } /** * Unsafe write uint into a memory location * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteUint(uint index, uint source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write uint8 into a memory location * * @param index Memory location * @param source uint8 to write * @return End memory index */ function unsafeWriteUint8(uint index, uint8 source) internal pure returns (uint) { assembly { mstore8(index, source) index := add(index, 0x1) } return index; } } contract ReentrancyGuarded { bool reentrancyLock = false; /* Prevent a contract function from being reentrant-called. */ modifier reentrancyGuard { if (reentrancyLock) { revert(); } reentrancyLock = true; _; reentrancyLock = false; } } contract TokenRecipient { event ReceivedEther(address indexed sender, uint amount); event ReceivedTokens(address indexed from, uint256 value, address indexed token, bytes extraData); /** * @dev Receive tokens and generate a log event * @param from Address from which to transfer tokens * @param value Amount of tokens to transfer * @param token Address of token * @param extraData Additional data to log */ function receiveApproval(address from, uint256 value, address token, bytes extraData) public { ERC20 t = ERC20(token); require(t.transferFrom(from, this, value)); emit ReceivedTokens(from, value, token, extraData); } /** * @dev Receive Ether and generate a log event */ function () payable public { emit ReceivedEther(msg.sender, msg.value); } } contract ExchangeCore is ReentrancyGuarded, Ownable { /* The token used to pay exchange fees. */ ERC20 public exchangeToken; /* User registry. */ ProxyRegistry public registry; /* Token transfer proxy. */ TokenTransferProxy public tokenTransferProxy; /* Cancelled / finalized orders, by hash. */ mapping(bytes32 => bool) public cancelledOrFinalized; /* Orders verified by on-chain approval (alternative to ECDSA signatures so that smart contracts can place orders directly). */ mapping(bytes32 => bool) public approvedOrders; /* For split fee orders, minimum required protocol maker fee, in basis points. Paid to owner (who can change it). */ uint public minimumMakerProtocolFee = 0; /* For split fee orders, minimum required protocol taker fee, in basis points. Paid to owner (who can change it). */ uint public minimumTakerProtocolFee = 0; /* Recipient of protocol fees. */ address public protocolFeeRecipient; /* Fee method: protocol fee or split fee. */ enum FeeMethod { ProtocolFee, SplitFee } /* Inverse basis point. */ uint public constant INVERSE_BASIS_POINT = 10000; /* An ECDSA signature. */ struct Sig { /* v parameter */ uint8 v; /* r parameter */ bytes32 r; /* s parameter */ bytes32 s; } /* An order on the exchange. */ struct Order { /* Exchange address, intended as a versioning mechanism. */ address exchange; /* Order maker address. */ address maker; /* Order taker address, if specified. */ address taker; /* Maker relayer fee of the order, unused for taker order. */ uint makerRelayerFee; /* Taker relayer fee of the order, or maximum taker fee for a taker order. */ uint takerRelayerFee; /* Maker protocol fee of the order, unused for taker order. */ uint makerProtocolFee; /* Taker protocol fee of the order, or maximum taker fee for a taker order. */ uint takerProtocolFee; /* Order fee recipient or zero address for taker order. */ address feeRecipient; /* Fee method (protocol token or split fee). */ FeeMethod feeMethod; /* Side (buy/sell). */ SaleKindInterface.Side side; /* Kind of sale. */ SaleKindInterface.SaleKind saleKind; /* Target. */ address target; /* HowToCall. */ AuthenticatedProxy.HowToCall howToCall; /* Calldata. */ bytes calldata; /* Calldata replacement pattern, or an empty byte array for no replacement. */ bytes replacementPattern; /* Static call target, zero-address for no static call. */ address staticTarget; /* Static call extra data. */ bytes staticExtradata; /* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */ address paymentToken; /* Base price of the order (in paymentTokens). */ uint basePrice; /* Auction extra parameter - minimum bid increment for English auctions, starting/ending price difference. */ uint extra; /* Listing timestamp. */ uint listingTime; /* Expiration timestamp - 0 for no expiry. */ uint expirationTime; /* Order salt, used to prevent duplicate hashes. */ uint salt; } event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, uint makerProtocolFee, uint takerProtocolFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target); event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired); event OrderCancelled (bytes32 indexed hash); event OrdersMatched (bytes32 buyHash, bytes32 sellHash, address indexed maker, address indexed taker, uint price, bytes32 indexed metadata); /** * @dev Change the minimum maker fee paid to the protocol (owner only) * @param newMinimumMakerProtocolFee New fee to set in basis points */ function changeMinimumMakerProtocolFee(uint newMinimumMakerProtocolFee) public onlyOwner { minimumMakerProtocolFee = newMinimumMakerProtocolFee; } /** * @dev Change the minimum taker fee paid to the protocol (owner only) * @param newMinimumTakerProtocolFee New fee to set in basis points */ function changeMinimumTakerProtocolFee(uint newMinimumTakerProtocolFee) public onlyOwner { minimumTakerProtocolFee = newMinimumTakerProtocolFee; } /** * @dev Change the protocol fee recipient (owner only) * @param newProtocolFeeRecipient New protocol fee recipient address */ function changeProtocolFeeRecipient(address newProtocolFeeRecipient) public onlyOwner { protocolFeeRecipient = newProtocolFeeRecipient; } /** * @dev Transfer tokens * @param token Token to transfer * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function transferTokens(address token, address from, address to, uint amount) internal { if (amount > 0) { require(tokenTransferProxy.transferFrom(token, from, to, amount)); } } /** * @dev Charge a fee in protocol tokens * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function chargeProtocolFee(address from, address to, uint amount) internal { transferTokens(exchangeToken, from, to, amount); } /** * @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call) * @param target Contract to call * @param calldata Calldata (appended to extradata) * @param extradata Base data for STATICCALL (probably function selector and argument encoding) * @return The result of the call (success or failure) */ function staticCall(address target, bytes memory calldata, bytes memory extradata) public view returns (bool result) { bytes memory combined = new bytes(calldata.length + extradata.length); uint index; assembly { index := add(combined, 0x20) } index = ArrayUtils.unsafeWriteBytes(index, extradata); ArrayUtils.unsafeWriteBytes(index, calldata); assembly { result := staticcall(gas, target, add(combined, 0x20), mload(combined), mload(0x40), 0) } return result; } /** * Calculate size of an order struct when tightly packed * * @param order Order to calculate size of * @return Size in bytes */ function sizeOf(Order memory order) internal pure returns (uint) { return ((0x14 * 7) + (0x20 * 9) + 4 + order.calldata.length + order.replacementPattern.length + order.staticExtradata.length); } /** * @dev Hash an order, returning the canonical order hash, without the message prefix * @param order Order to hash * @return Hash of order */ function hashOrder(Order memory order) internal pure returns (bytes32 hash) { /* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */ uint size = sizeOf(order); bytes memory array = new bytes(size); uint index; assembly { index := add(array, 0x20) } index = ArrayUtils.unsafeWriteAddress(index, order.exchange); index = ArrayUtils.unsafeWriteAddress(index, order.maker); index = ArrayUtils.unsafeWriteAddress(index, order.taker); index = ArrayUtils.unsafeWriteUint(index, order.makerRelayerFee); index = ArrayUtils.unsafeWriteUint(index, order.takerRelayerFee); index = ArrayUtils.unsafeWriteUint(index, order.makerProtocolFee); index = ArrayUtils.unsafeWriteUint(index, order.takerProtocolFee); index = ArrayUtils.unsafeWriteAddress(index, order.feeRecipient); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.feeMethod)); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.side)); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.saleKind)); index = ArrayUtils.unsafeWriteAddress(index, order.target); index = ArrayUtils.unsafeWriteUint8(index, uint8(order.howToCall)); index = ArrayUtils.unsafeWriteBytes(index, order.calldata); index = ArrayUtils.unsafeWriteBytes(index, order.replacementPattern); index = ArrayUtils.unsafeWriteAddress(index, order.staticTarget); index = ArrayUtils.unsafeWriteBytes(index, order.staticExtradata); index = ArrayUtils.unsafeWriteAddress(index, order.paymentToken); index = ArrayUtils.unsafeWriteUint(index, order.basePrice); index = ArrayUtils.unsafeWriteUint(index, order.extra); index = ArrayUtils.unsafeWriteUint(index, order.listingTime); index = ArrayUtils.unsafeWriteUint(index, order.expirationTime); index = ArrayUtils.unsafeWriteUint(index, order.salt); assembly { hash := keccak256(add(array, 0x20), size) } return hash; } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @param order Order to hash * @return Hash of message prefix and order hash per Ethereum format */ function hashToSign(Order memory order) internal pure returns (bytes32) { return keccak256("\x19Ethereum Signed Message:\n32", hashOrder(order)); } /** * @dev Assert an order is valid and return its hash * @param order Order to validate * @param sig ECDSA signature */ function requireValidOrder(Order memory order, Sig memory sig) internal view returns (bytes32) { bytes32 hash = hashToSign(order); require(validateOrder(hash, order, sig)); return hash; } /** * @dev Validate order parameters (does *not* check signature validity) * @param order Order to validate */ function validateOrderParameters(Order memory order) internal view returns (bool) { /* Order must be targeted at this protocol version (this Exchange contract). */ if (order.exchange != address(this)) { return false; } /* Order must possess valid sale kind parameter combination. */ if (!SaleKindInterface.validateParameters(order.saleKind, order.expirationTime)) { return false; } /* If using the split fee method, order must have sufficient protocol fees. */ if (order.feeMethod == FeeMethod.SplitFee && (order.makerProtocolFee < minimumMakerProtocolFee || order.takerProtocolFee < minimumTakerProtocolFee)) { return false; } return true; } /** * @dev Validate a provided previously approved / signed order, hash, and signature. * @param hash Order hash (already calculated, passed to avoid recalculation) * @param order Order to validate * @param sig ECDSA signature */ function validateOrder(bytes32 hash, Order memory order, Sig memory sig) internal view returns (bool) { /* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */ /* Order must have valid parameters. */ if (!validateOrderParameters(order)) { return false; } /* Order must have not been canceled or already filled. */ if (cancelledOrFinalized[hash]) { return false; } /* Order authentication. Order must be either: /* (a) previously approved */ if (approvedOrders[hash]) { return true; } /* or (b) ECDSA-signed by maker. */ if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) { return true; } return false; } /** * @dev Approve an order and optionally mark it for orderbook inclusion. Must be called by the maker of the order * @param order Order to approve * @param orderbookInclusionDesired Whether orderbook providers should include the order in their orderbooks */ function approveOrder(Order memory order, bool orderbookInclusionDesired) internal { /* CHECKS */ /* Assert sender is authorized to approve order. */ require(msg.sender == order.maker); /* Calculate order hash. */ bytes32 hash = hashToSign(order); /* Assert order has not already been approved. */ require(!approvedOrders[hash]); /* EFFECTS */ /* Mark order as approved. */ approvedOrders[hash] = true; /* Log approval event. Must be split in two due to Solidity stack size limitations. */ { emit OrderApprovedPartOne(hash, order.exchange, order.maker, order.taker, order.makerRelayerFee, order.takerRelayerFee, order.makerProtocolFee, order.takerProtocolFee, order.feeRecipient, order.feeMethod, order.side, order.saleKind, order.target); } { emit OrderApprovedPartTwo(hash, order.howToCall, order.calldata, order.replacementPattern, order.staticTarget, order.staticExtradata, order.paymentToken, order.basePrice, order.extra, order.listingTime, order.expirationTime, order.salt, orderbookInclusionDesired); } } /** * @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order * @param order Order to cancel * @param sig ECDSA signature */ function cancelOrder(Order memory order, Sig memory sig) internal { /* CHECKS */ /* Calculate order hash. */ bytes32 hash = requireValidOrder(order, sig); /* Assert sender is authorized to cancel order. */ require(msg.sender == order.maker); /* EFFECTS */ /* Mark order as cancelled, preventing it from being matched. */ cancelledOrFinalized[hash] = true; /* Log cancel event. */ emit OrderCancelled(hash); } /** * @dev Calculate the current price of an order (convenience function) * @param order Order to calculate the price of * @return The current price of the order */ function calculateCurrentPrice (Order memory order) internal view returns (uint) { return SaleKindInterface.calculateFinalPrice(order.side, order.saleKind, order.basePrice, order.extra, order.listingTime, order.expirationTime); } /** * @dev Calculate the price two orders would match at, if in fact they would match (otherwise fail) * @param buy Buy-side order * @param sell Sell-side order * @return Match price */ function calculateMatchPrice(Order memory buy, Order memory sell) view internal returns (uint) { /* Calculate sell price. */ uint sellPrice = SaleKindInterface.calculateFinalPrice(sell.side, sell.saleKind, sell.basePrice, sell.extra, sell.listingTime, sell.expirationTime); /* Calculate buy price. */ uint buyPrice = SaleKindInterface.calculateFinalPrice(buy.side, buy.saleKind, buy.basePrice, buy.extra, buy.listingTime, buy.expirationTime); /* Require price cross. */ require(buyPrice >= sellPrice); /* Maker/taker priority. */ return sell.feeRecipient != address(0) ? sellPrice : buyPrice; } /** * @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer) * @param buy Buy-side order * @param sell Sell-side order */ function executeFundsTransfer(Order memory buy, Order memory sell) internal returns (uint) { /* Only payable in the special case of unwrapped Ether. */ if (sell.paymentToken != address(0)) { require(msg.value == 0); } /* Calculate match price. */ uint price = calculateMatchPrice(buy, sell); /* If paying using a token (not Ether), transfer tokens. This is done prior to fee payments to that a seller will have tokens before being charged fees. */ if (price > 0 && sell.paymentToken != address(0)) { transferTokens(sell.paymentToken, buy.maker, sell.maker, price); } /* Amount that will be received by seller (for Ether). */ uint receiveAmount = price; /* Amount that must be sent by buyer (for Ether). */ uint requiredAmount = price; /* Determine maker/taker and charge fees accordingly. */ if (sell.feeRecipient != address(0)) { /* Sell-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ require(sell.takerProtocolFee <= buy.takerProtocolFee); /* Maker fees are deducted from the token amount that the maker receives. Taker fees are extra tokens that must be paid by the taker. */ if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); } else { transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); } else { transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); } else { transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); } else { transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } else { /* Charge maker fee to seller. */ chargeProtocolFee(sell.maker, sell.feeRecipient, sell.makerRelayerFee); /* Charge taker fee to buyer. */ chargeProtocolFee(buy.maker, sell.feeRecipient, sell.takerRelayerFee); } } else { /* Buy-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by seller. */ require(buy.takerRelayerFee <= sell.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { /* The Exchange does not escrow Ether, so direct Ether can only be used to with sell-side maker / buy-side taker orders. */ require(sell.paymentToken != address(0)); /* Assert taker fee is less than or equal to maximum fee specified by seller. */ require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } else { /* Charge maker fee to buyer. */ chargeProtocolFee(buy.maker, buy.feeRecipient, buy.makerRelayerFee); /* Charge taker fee to seller. */ chargeProtocolFee(sell.maker, buy.feeRecipient, buy.takerRelayerFee); } } if (sell.paymentToken == address(0)) { /* Special-case Ether, order must be matched by buyer. */ require(msg.value >= requiredAmount); sell.maker.transfer(receiveAmount); /* Allow overshoot for variable-price auctions, refund difference. */ uint diff = SafeMath.sub(msg.value, requiredAmount); if (diff > 0) { buy.maker.transfer(diff); } } /* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */ return price; } /** * @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures / calldata or perform static calls) * @param buy Buy-side order * @param sell Sell-side order * @return Whether or not the two orders can be matched */ function ordersCanMatch(Order memory buy, Order memory sell) internal view returns (bool) { return ( /* Must be opposite-side. */ (buy.side == SaleKindInterface.Side.Buy && sell.side == SaleKindInterface.Side.Sell) && /* Must use same fee method. */ (buy.feeMethod == sell.feeMethod) && /* Must use same payment token. */ (buy.paymentToken == sell.paymentToken) && /* Must match maker/taker addresses. */ (sell.taker == address(0) || sell.taker == buy.maker) && (buy.taker == address(0) || buy.taker == sell.maker) && /* One must be maker and the other must be taker (no bool XOR in Solidity). */ ((sell.feeRecipient == address(0) && buy.feeRecipient != address(0)) || (sell.feeRecipient != address(0) && buy.feeRecipient == address(0))) && /* Must match target. */ (buy.target == sell.target) && /* Must match howToCall. */ (buy.howToCall == sell.howToCall) && /* Buy-side order must be settleable. */ SaleKindInterface.canSettleOrder(buy.listingTime, buy.expirationTime) && /* Sell-side order must be settleable. */ SaleKindInterface.canSettleOrder(sell.listingTime, sell.expirationTime) ); } /** * @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock. * @param buy Buy-side order * @param buySig Buy-side order signature * @param sell Sell-side order * @param sellSig Sell-side order signature */ function atomicMatch(Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata) internal reentrancyGuard { /* CHECKS */ /* Ensure buy order validity and calculate hash if necessary. */ bytes32 buyHash; if (buy.maker == msg.sender) { require(validateOrderParameters(buy)); } else { buyHash = requireValidOrder(buy, buySig); } /* Ensure sell order validity and calculate hash if necessary. */ bytes32 sellHash; if (sell.maker == msg.sender) { require(validateOrderParameters(sell)); } else { sellHash = requireValidOrder(sell, sellSig); } /* Must be matchable. */ require(ordersCanMatch(buy, sell)); /* Target must exist (prevent malicious selfdestructs just prior to order settlement). */ uint size; address target = sell.target; assembly { size := extcodesize(target) } require(size > 0); /* Must match calldata after replacement, if specified. */ if (buy.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buy.calldata, sell.calldata, buy.replacementPattern); } if (sell.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sell.calldata, buy.calldata, sell.replacementPattern); } require(ArrayUtils.arrayEq(buy.calldata, sell.calldata)); /* Retrieve delegateProxy contract. */ OwnableDelegateProxy delegateProxy = registry.proxies(sell.maker); /* Proxy must exist. */ require(delegateProxy != address(0)); /* Assert implementation. */ require(delegateProxy.implementation() == registry.delegateProxyImplementation()); /* Access the passthrough AuthenticatedProxy. */ AuthenticatedProxy proxy = AuthenticatedProxy(delegateProxy); /* EFFECTS */ /* Mark previously signed or approved orders as finalized. */ if (msg.sender != buy.maker) { cancelledOrFinalized[buyHash] = true; } if (msg.sender != sell.maker) { cancelledOrFinalized[sellHash] = true; } /* INTERACTIONS */ /* Execute funds transfer and pay fees. */ uint price = executeFundsTransfer(buy, sell); /* Execute specified call through proxy. */ require(proxy.proxy(sell.target, sell.howToCall, sell.calldata)); /* Static calls are intentionally done after the effectful call so they can check resulting state. */ /* Handle buy-side static call if specified. */ if (buy.staticTarget != address(0)) { require(staticCall(buy.staticTarget, sell.calldata, buy.staticExtradata)); } /* Handle sell-side static call if specified. */ if (sell.staticTarget != address(0)) { require(staticCall(sell.staticTarget, sell.calldata, sell.staticExtradata)); } /* Log match event. */ emit OrdersMatched(buyHash, sellHash, sell.feeRecipient != address(0) ? sell.maker : buy.maker, sell.feeRecipient != address(0) ? buy.maker : sell.maker, price, metadata); } } contract Exchange is ExchangeCore { /** * @dev Call guardedArrayReplace - library function exposed for testing. */ function guardedArrayReplace(bytes array, bytes desired, bytes mask) public pure returns (bytes) { ArrayUtils.guardedArrayReplace(array, desired, mask); return array; } /** * Test copy byte array * * @param arrToCopy Array to copy * @return byte array */ function testCopy(bytes arrToCopy) public pure returns (bytes) { bytes memory arr = new bytes(arrToCopy.length); uint index; assembly { index := add(arr, 0x20) } ArrayUtils.unsafeWriteBytes(index, arrToCopy); return arr; } /** * Test write address to bytes * * @param addr Address to write * @return byte array */ function testCopyAddress(address addr) public pure returns (bytes) { bytes memory arr = new bytes(0x14); uint index; assembly { index := add(arr, 0x20) } ArrayUtils.unsafeWriteAddress(index, addr); return arr; } /** * @dev Call calculateFinalPrice - library function exposed for testing. */ function calculateFinalPrice(SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime) public view returns (uint) { return SaleKindInterface.calculateFinalPrice(side, saleKind, basePrice, extra, listingTime, expirationTime); } /** * @dev Call hashOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashOrder_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public pure returns (bytes32) { return hashOrder( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]) ); } /** * @dev Call hashToSign - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashToSign_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public pure returns (bytes32) { return hashToSign( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]) ); } /** * @dev Call validateOrderParameters - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrderParameters_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) view public returns (bool) { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return validateOrderParameters( order ); } /** * @dev Call validateOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrder_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s) view public returns (bool) { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return validateOrder( hashToSign(order), order, Sig(v, r, s) ); } /** * @dev Call approveOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function approveOrder_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, bool orderbookInclusionDesired) public { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return approveOrder(order, orderbookInclusionDesired); } /** * @dev Call cancelOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function cancelOrder_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s) public { return cancelOrder( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), Sig(v, r, s) ); } /** * @dev Call calculateCurrentPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateCurrentPrice_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public view returns (uint) { return calculateCurrentPrice( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]) ); } /** * @dev Call ordersCanMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function ordersCanMatch_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell) public view returns (bool) { Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]); return ordersCanMatch( buy, sell ); } /** * @dev Return whether or not two orders' calldata specifications can match * @param buyCalldata Buy-side order calldata * @param buyReplacementPattern Buy-side order calldata replacement mask * @param sellCalldata Sell-side order calldata * @param sellReplacementPattern Sell-side order calldata replacement mask * @return Whether the orders' calldata can be matched */ function orderCalldataCanMatch(bytes buyCalldata, bytes buyReplacementPattern, bytes sellCalldata, bytes sellReplacementPattern) public pure returns (bool) { if (buyReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buyCalldata, sellCalldata, buyReplacementPattern); } if (sellReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sellCalldata, buyCalldata, sellReplacementPattern); } return ArrayUtils.arrayEq(buyCalldata, sellCalldata); } /** * @dev Call calculateMatchPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateMatchPrice_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell) public view returns (uint) { Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]); return calculateMatchPrice( buy, sell ); } /** * @dev Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function atomicMatch_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell, uint8[2] vs, bytes32[5] rssMetadata) public payable { return atomicMatch( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), Sig(vs[0], rssMetadata[0], rssMetadata[1]), Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]), Sig(vs[1], rssMetadata[2], rssMetadata[3]), rssMetadata[4] ); } } contract WyvernExchange is Exchange { string public constant name = "Project Wyvern Exchange"; string public constant version = "2.2"; string public constant codename = "Lambton Worm"; /** * @dev Initialize a WyvernExchange instance * @param registryAddress Address of the registry instance which this Exchange instance will use * @param tokenAddress Address of the token used for protocol fees */ constructor (ProxyRegistry registryAddress, TokenTransferProxy tokenTransferProxyAddress, ERC20 tokenAddress, address protocolFeeAddress) public { registry = registryAddress; tokenTransferProxy = tokenTransferProxyAddress; exchangeToken = tokenAddress; protocolFeeRecipient = protocolFeeAddress; owner = msg.sender; } } library SaleKindInterface { /** * Side: buy or sell. */ enum Side { Buy, Sell } /** * Currently supported kinds of sale: fixed price, Dutch auction. * English auctions cannot be supported without stronger escrow guarantees. * Future interesting options: Vickrey auction, nonlinear Dutch auctions. */ enum SaleKind { FixedPrice, DutchAuction } /** * @dev Check whether the parameters of a sale are valid * @param saleKind Kind of sale * @param expirationTime Order expiration time * @return Whether the parameters were valid */ function validateParameters(SaleKind saleKind, uint expirationTime) pure internal returns (bool) { /* Auctions must have a set expiration date. */ return (saleKind == SaleKind.FixedPrice || expirationTime > 0); } /** * @dev Return whether or not an order can be settled * @dev Precondition: parameters have passed validateParameters * @param listingTime Order listing time * @param expirationTime Order expiration time */ function canSettleOrder(uint listingTime, uint expirationTime) view internal returns (bool) { return (listingTime < now) && (expirationTime == 0 || now < expirationTime); } /** * @dev Calculate the settlement price of an order * @dev Precondition: parameters have passed validateParameters. * @param side Order side * @param saleKind Method of sale * @param basePrice Order base price * @param extra Order extra price data * @param listingTime Order listing time * @param expirationTime Order expiration time */ function calculateFinalPrice(Side side, SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime) view internal returns (uint finalPrice) { if (saleKind == SaleKind.FixedPrice) { return basePrice; } else if (saleKind == SaleKind.DutchAuction) { uint diff = SafeMath.div(SafeMath.mul(extra, SafeMath.sub(now, listingTime)), SafeMath.sub(expirationTime, listingTime)); if (side == Side.Sell) { /* Sell-side - start price: basePrice. End price: basePrice - extra. */ return SafeMath.sub(basePrice, diff); } else { /* Buy-side - start price: basePrice. End price: basePrice + extra. */ return SafeMath.add(basePrice, diff); } } } } contract ProxyRegistry is Ownable { /* DelegateProxy implementation contract. Must be initialized. */ address public delegateProxyImplementation; /* Authenticated proxies by user. */ mapping(address => OwnableDelegateProxy) public proxies; /* Contracts pending access. */ mapping(address => uint) public pending; /* Contracts allowed to call those proxies. */ mapping(address => bool) public contracts; /* Delay period for adding an authenticated contract. This mitigates a particular class of potential attack on the Wyvern DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO), a malicious but rational attacker could buy half the Wyvern and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have plenty of time to notice and transfer their assets. */ uint public DELAY_PERIOD = 2 weeks; /** * Start the process to enable access for specified contract. Subject to delay period. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function startGrantAuthentication (address addr) public onlyOwner { require(!contracts[addr] && pending[addr] == 0); pending[addr] = now; } /** * End the process to nable access for specified contract after delay period has passed. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function endGrantAuthentication (address addr) public onlyOwner { require(!contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < now)); pending[addr] = 0; contracts[addr] = true; } /** * Revoke access for specified contract. Can be done instantly. * * @dev ProxyRegistry owner only * @param addr Address of which to revoke permissions */ function revokeAuthentication (address addr) public onlyOwner { contracts[addr] = false; } /** * Register a proxy contract with this registry * * @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy * @return New AuthenticatedProxy contract */ function registerProxy() public returns (OwnableDelegateProxy proxy) { require(proxies[msg.sender] == address(0)); proxy = new OwnableDelegateProxy(msg.sender, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", msg.sender, address(this))); proxies[msg.sender] = proxy; return proxy; } } contract TokenTransferProxy { /* Authentication registry. */ ProxyRegistry public registry; /** * Call ERC20 `transferFrom` * * @dev Authenticated contract only * @param token ERC20 token address * @param from From address * @param to To address * @param amount Transfer amount */ function transferFrom(address token, address from, address to, uint amount) public returns (bool) { require(registry.contracts(msg.sender)); return ERC20(token).transferFrom(from, to, amount); } } contract OwnedUpgradeabilityStorage { // Current implementation address internal _implementation; // Owner of the contract address private _upgradeabilityOwner; /** * @dev Tells the address of the owner * @return the address of the owner */ function upgradeabilityOwner() public view returns (address) { return _upgradeabilityOwner; } /** * @dev Sets the address of the owner */ function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal { _upgradeabilityOwner = newUpgradeabilityOwner; } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address) { return _implementation; } /** * @dev Tells the proxy type (EIP 897) * @return Proxy type, 2 for forwarding proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return 2; } } contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage { /* Whether initialized. */ bool initialized = false; /* Address which owns this proxy. */ address public user; /* Associated registry with contract authentication information. */ ProxyRegistry public registry; /* Whether access has been revoked. */ bool public revoked; /* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */ enum HowToCall { Call, DelegateCall } /* Event fired when the proxy access is revoked or unrevoked. */ event Revoked(bool revoked); /** * Initialize an AuthenticatedProxy * * @param addrUser Address of user on whose behalf this proxy will act * @param addrRegistry Address of ProxyRegistry contract which will manage this proxy */ function initialize (address addrUser, ProxyRegistry addrRegistry) public { require(!initialized); initialized = true; user = addrUser; registry = addrRegistry; } /** * Set the revoked flag (allows a user to revoke ProxyRegistry access) * * @dev Can be called by the user only * @param revoke Whether or not to revoke access */ function setRevoke(bool revoke) public { require(msg.sender == user); revoked = revoke; emit Revoked(revoke); } /** * Execute a message call from the proxy contract * * @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access * @param dest Address to which the call will be sent * @param howToCall Which kind of call to make * @param calldata Calldata to send * @return Result of the call (success or failure) */ function proxy(address dest, HowToCall howToCall, bytes calldata) public returns (bool result) { require(msg.sender == user || (!revoked && registry.contracts(msg.sender))); if (howToCall == HowToCall.Call) { result = dest.call(calldata); } else if (howToCall == HowToCall.DelegateCall) { result = dest.delegatecall(calldata); } return result; } /** * Execute a message call and assert success * * @dev Same functionality as `proxy`, just asserts the return value * @param dest Address to which the call will be sent * @param howToCall What kind of call to make * @param calldata Calldata to send */ function proxyAssert(address dest, HowToCall howToCall, bytes calldata) public { require(proxy(dest, howToCall, calldata)); } } contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address); /** * @dev Tells the type of proxy (EIP 897) * @return Type of proxy, 2 for upgradeable proxy */ function proxyType() public pure returns (uint256 proxyTypeId); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () payable public { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); /** * @dev Upgrades the implementation address * @param implementation representing the address of the new implementation to be set */ function _upgradeTo(address implementation) internal { require(_implementation != implementation); _implementation = implementation; emit Upgraded(implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() public view returns (address) { return upgradeabilityOwner(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public onlyProxyOwner { _upgradeTo(implementation); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy * and delegatecall the new implementation for initialization. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation, bytes data) payable public onlyProxyOwner { upgradeTo(implementation); require(address(this).delegatecall(data)); } } contract OwnableDelegateProxy is OwnedUpgradeabilityProxy { constructor(address owner, address initialImplementation, bytes calldata) public { setUpgradeabilityOwner(owner); _upgradeTo(initialImplementation); require(initialImplementation.delegatecall(calldata)); } }
Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock. buy Buy-side order buySig Buy-side order signature sell Sell-side order sellSig Sell-side order signature/ CHECKS / Ensure buy order validity and calculate hash if necessary. / Must match calldata after replacement, if specified. / Mark previously signed or approved orders as finalized. / Handle buy-side static call if specified. / Handle sell-side static call if specified. /
function atomicMatch(Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata) internal reentrancyGuard { bytes32 buyHash; if (buy.maker == msg.sender) { require(validateOrderParameters(buy)); buyHash = requireValidOrder(buy, buySig); } if (sell.maker == msg.sender) { require(validateOrderParameters(sell)); sellHash = requireValidOrder(sell, sellSig); } address target = sell.target; assembly { size := extcodesize(target) } require(size > 0); if (buy.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buy.calldata, sell.calldata, buy.replacementPattern); } if (sell.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sell.calldata, buy.calldata, sell.replacementPattern); } require(ArrayUtils.arrayEq(buy.calldata, sell.calldata)); if (msg.sender != buy.maker) { cancelledOrFinalized[buyHash] = true; } if (msg.sender != sell.maker) { cancelledOrFinalized[sellHash] = true; } if (buy.staticTarget != address(0)) { require(staticCall(buy.staticTarget, sell.calldata, buy.staticExtradata)); } if (sell.staticTarget != address(0)) { require(staticCall(sell.staticTarget, sell.calldata, sell.staticExtradata)); } }
5,836,533
./full_match/5/0x9DeE45C872519f80de11E7Ab937CE83F80f8a536/sources/project_/contracts/MuallaqatNFTMarket.sol
get all fees as array
function getFees() public view returns (uint256[] memory) { uint256[] memory fees = new uint256[](5); fees[0] = ListingAndFeesPrice; fees[1] = changeStatusFeesPrice; fees[2] = premiumFees; fees[3] = premiumDays; fees[4] = ownerPercentage; return fees; }
1,860,212
/** *Submitted for verification at Etherscan.io on 2021-06-12 */ pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor (uint256 rate, address payable wallet, IERC20 token) public { require(rate >= 0, "Crowdsale: rate must be above 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; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount) + 1000000000000000000000; _preValidatePurchase(beneficiary, weiAmount, tokens); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount, tokens); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount, uint256 tokens) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount >= 0, "Crowdsale: weiAmount must 0"); require(tokens != 0, "test warning"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address beneficiary, uint256 weiAmount, uint256 tokens) internal { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } /** * @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); } /** * @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; } } /** * @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"); } } /** * @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"); } } } /** * @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); } } /** * @title AllowanceCrowdsale * @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale. */ contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; address private _tokenWallet; /** * @dev Constructor, takes token wallet address. * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale. */ constructor (address tokenWallet) public { require(tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address"); _tokenWallet = tokenWallet; } /** * @return the address of the wallet that will hold the tokens. */ function tokenWallet() public view returns (address) { return _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this))); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } } /** * @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]; } } contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @title PausableCrowdsale * @dev Extension of Crowdsale contract where purchases can be paused and unpaused by the pauser role. */ contract PausableCrowdsale is Crowdsale, Pausable { /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use super to concatenate validations. * Adds the validation that the crowdsale must not be paused. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount, uint256 tokens) internal view whenNotPaused { return super._preValidatePurchase(_beneficiary, _weiAmount, tokens); } } contract CapperRole is Context { using Roles for Roles.Role; event CapperAdded(address indexed account); event CapperRemoved(address indexed account); Roles.Role private _cappers; constructor () internal { _addCapper(_msgSender()); } modifier onlyCapper() { require(isCapper(_msgSender()), "CapperRole: caller does not have the Capper role"); _; } function isCapper(address account) public view returns (bool) { return _cappers.has(account); } function addCapper(address account) public onlyCapper { _addCapper(account); } function renounceCapper() public { _removeCapper(_msgSender()); } function _addCapper(address account) internal { _cappers.add(account); emit CapperAdded(account); } function _removeCapper(address account) internal { _cappers.remove(account); emit CapperRemoved(account); } } /** * @title IndividuallyCappedCrowdsale * @dev Crowdsale with per-beneficiary caps. */ contract IndividuallyCappedCrowdsale is Crowdsale, CapperRole { using SafeMath for uint256; mapping(address => uint256) private _contributions; mapping(address => uint256) private _caps; /** * @dev Sets a specific beneficiary's maximum contribution. * @param beneficiary Address to be capped * @param cap Wei limit for individual contribution */ function setCap(address beneficiary, uint256 cap) external onlyCapper { _caps[beneficiary] = cap; } /** * @dev Returns the cap of a specific beneficiary. * @param beneficiary Address whose cap is to be checked * @return Current cap for individual beneficiary */ function getCap(address beneficiary) public view returns (uint256) { return _caps[beneficiary]; } /** * @dev Returns the amount contributed so far by a specific beneficiary. * @param beneficiary Address of contributor * @return Beneficiary contribution so far */ function getContribution(address beneficiary) public view returns (uint256) { return _contributions[beneficiary]; } /** * @dev Extend parent behavior requiring purchase to respect the beneficiary's funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount, uint256 tokens) internal view { super._preValidatePurchase(beneficiary, weiAmount, tokens); // solhint-disable-next-line max-line-length require(_contributions[beneficiary] <= _caps[beneficiary], "IndividuallyCappedCrowdsale: beneficiary's cap exceeded"); } /** * @dev Extend parent behavior to update beneficiary contributions. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _updatePurchasingState(address beneficiary, uint256 weiAmount, uint256 tokens) internal { super._updatePurchasingState(beneficiary, weiAmount, tokens); _contributions[beneficiary] = _contributions[beneficiary].add(tokens); } } contract DistributionFREET is Crowdsale, AllowanceCrowdsale, PausableCrowdsale, IndividuallyCappedCrowdsale { constructor( uint256 rate, uint256 cap, address payable wallet, IERC20 token, address tokenWallet // <- new argument ) AllowanceCrowdsale(tokenWallet) // <- used here Crowdsale(rate, wallet, token) public { } }
low level token purchase DO NOT OVERRIDE This function has a non-reentrancy guard, so it shouldn't be called by another `nonReentrant` function. beneficiary Recipient of the token purchase/ calculate token amount to be created update state
function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; uint256 tokens = _getTokenAmount(weiAmount) + 1000000000000000000000; _preValidatePurchase(beneficiary, weiAmount, tokens); _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount, tokens); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); }
14,989,268
//SPDX-License-Identifier: MIT pragma solidity =0.6.6; // Todo initialized + bond events + migration + starttime import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./TokenManager.sol"; import "../time/Timeboundable.sol"; import "../access/Migratable.sol"; import "../interfaces/IBondManager.sol"; import "../interfaces/ITokenManager.sol"; contract BondManager is IBondManager, ReentrancyGuard, Operatable, Timeboundable, Migratable { using SafeMath for uint256; using SafeERC20 for IERC20; /// Bond data (key is synthetic token address, value is bond address) mapping(address => address) public override bondIndex; /// Pauses buying bonds bool public pauseBuyBonds = false; /// TokenManager reference ITokenManager public tokenManager; /// Creates a new Bond Manager constructor(uint256 startTime) public Timeboundable(startTime, 0) {} // ------- Modifiers ------------ /// Fails if a token is not currently managed by Token Manager /// @param syntheticTokenAddress The address of the synthetic token modifier managedToken(address syntheticTokenAddress) { require( isManagedToken(syntheticTokenAddress), "TokenManager: Token is not managed" ); _; } // ------- Public view ---------- function isManagedToken(address syntheticTokenAddress) public view returns (bool) { return bondIndex[syntheticTokenAddress] != address(0); } /// Checks if token ownerships are valid /// @return True if ownerships are valid function validTokenPermissions() public view returns (bool) { address[] memory tokens = tokenManager.allTokens(); for (uint32 i = 0; i < tokens.length; i++) { SyntheticToken token = SyntheticToken(bondIndex[tokens[i]]); if (address(token) != address(0)) { if (token.operator() != address(this)) { return false; } if (token.owner() != address(this)) { return false; } } } return true; } /// The decimals of the bond token /// @param syntheticTokenAddress The address of the synthetic token /// @return The number of decimals for the bond token /// @dev Fails if the token is not managed function bondDecimals(address syntheticTokenAddress) public view managedToken(syntheticTokenAddress) returns (uint8) { return SyntheticToken(bondIndex[syntheticTokenAddress]).decimals(); } /// This is the price of synthetic in underlying (und / syn) /// but corrected for bond mechanics, i.e. max of oracle / current uniswap price /// @param syntheticTokenAddress The address of the synthetic token /// @return The price of one unit (e.g. BTC, ETH, etc.) syn token in underlying token (e.g. sat, wei, etc) /// @dev Fails if the token is not managed function bondPriceUndPerUnitSyn(address syntheticTokenAddress) public view managedToken(syntheticTokenAddress) returns (uint256) { uint256 avgPriceUndPerUnitSyn = tokenManager.averagePrice( syntheticTokenAddress, tokenManager.oneSyntheticUnit(syntheticTokenAddress) ); uint256 curPriceUndPerUnitSyn = tokenManager.currentPrice( syntheticTokenAddress, tokenManager.oneSyntheticUnit(syntheticTokenAddress) ); return Math.max(avgPriceUndPerUnitSyn, curPriceUndPerUnitSyn); } /// How many bonds you can buy with this amount of synthetic /// @param syntheticTokenAddress The address of the synthetic token /// @param amountOfSynthetic Amount of synthetic to sell /// @return amountOfBonds The number of bonds that could be bought /// @dev Use the returned value as the input for minAmountBondsOut in `buyBonds` function quoteBonds( address syntheticTokenAddress, uint256 amountOfSynthetic ) public view managedToken(syntheticTokenAddress) returns (uint256 amountOfBonds) { uint256 underlyingUnit = tokenManager.oneUnderlyingUnit(syntheticTokenAddress); uint256 bondPrice = bondPriceUndPerUnitSyn(syntheticTokenAddress); require( bondPrice < underlyingUnit, "BondManager: Synthetic price is not eligible for bond emission" ); amountOfBonds = amountOfSynthetic.mul(underlyingUnit).div(bondPrice); } // ------- Public ---------- /// Buy bonds with synthetic /// @param syntheticTokenAddress The address of the synthetic token /// @param amountOfSyntheticIn Amount of synthetic to sell /// @param minAmountBondsOut Minimum amount of bonds out /// @dev Fails if the token is not managed function buyBonds( address syntheticTokenAddress, uint256 amountOfSyntheticIn, uint256 minAmountBondsOut ) public nonReentrant managedToken(syntheticTokenAddress) inTimeBounds { tokenManager.updateOracle(syntheticTokenAddress); require( !pauseBuyBonds, "BondManager: Buying bonds is temporarily suspended" ); uint256 amountOfBonds = quoteBonds(syntheticTokenAddress, amountOfSyntheticIn); require( amountOfBonds >= minAmountBondsOut, "BondManager: number of bonds is less than minAmountBondsOut" ); tokenManager.burnSyntheticFrom( syntheticTokenAddress, msg.sender, amountOfSyntheticIn ); SyntheticToken bondToken = SyntheticToken(bondIndex[syntheticTokenAddress]); bondToken.mint(msg.sender, amountOfBonds); emit BoughtBonds(msg.sender, amountOfSyntheticIn, amountOfBonds); } /// Sell bonds for synthetic 1-to-1 /// @param syntheticTokenAddress The address of the synthetic token /// @param amountOfBondsIn Amount of bonds to sell /// @param minAmountOfSyntheticOut Minimum amount of synthetics out /// @dev Fails if the token is not managed. Could be paritally executed /// or not executed at all if the BondManager balance of synthetic is less /// than amountOfSyntheticIn. The balance of synthetic is increased during positive rebases. /// Use minAmountOfSyntheticOut to regulate partial fulfillments. function sellBonds( address syntheticTokenAddress, uint256 amountOfBondsIn, uint256 minAmountOfSyntheticOut ) public managedToken(syntheticTokenAddress) nonReentrant inTimeBounds { SyntheticToken syntheticToken = SyntheticToken(syntheticTokenAddress); // trusted address since this is a managedToken SyntheticToken bondToken = SyntheticToken(bondIndex[syntheticTokenAddress]); uint256 amount = Math.min(syntheticToken.balanceOf(address(this)), amountOfBondsIn); require( amount >= minAmountOfSyntheticOut, "BondManager: Less than minAmountOfSyntheticOut bonds could be sold" ); bondToken.burnFrom(msg.sender, amount); syntheticToken.transfer(msg.sender, amount); emit SoldBonds(msg.sender, amount); } // ------- Public, Operator ---------- /// Sets the pause to buying bonds /// @param pause True if bonds buying should be stopped. function setPauseBuyBonds(bool pause) public onlyOperator { pauseBuyBonds = pause; emit BuyBondsPaused(msg.sender, pause); } /// Sets the TokenManager /// @param _tokenManager The address of the new TokenManager function setTokenManager(address _tokenManager) public onlyOperator { tokenManager = ITokenManager(_tokenManager); emit TokenManagerChanged(msg.sender, _tokenManager); } // ------- Internal ---------- /// Called when new token is added in TokenManager /// @param syntheticTokenAddress The address of the synthetic token /// @param bondTokenAddress The address of the bond token function addBondToken( address syntheticTokenAddress, address bondTokenAddress ) public override { require( msg.sender == address(tokenManager), "BondManager: Only TokenManager can call this function" ); SyntheticToken bondToken = SyntheticToken(bondTokenAddress); bondIndex[syntheticTokenAddress] = address(bondToken); emit BondAdded(bondTokenAddress); } /// Called when token is deleted in TokenManager /// @param syntheticTokenAddress The address of the synthetic token /// @param newOperator New operator for the bond token function deleteBondToken(address syntheticTokenAddress, address newOperator) public override { require( msg.sender == address(tokenManager), "BondManager: Only TokenManager can call this function" ); SyntheticToken syntheticToken = SyntheticToken(syntheticTokenAddress); syntheticToken.transfer( newOperator, syntheticToken.balanceOf(address(this)) ); SyntheticToken bondToken = SyntheticToken(bondIndex[syntheticTokenAddress]); bondToken.transferOperator(newOperator); bondToken.transferOwnership(newOperator); delete bondIndex[syntheticTokenAddress]; assert(!isManagedToken(syntheticTokenAddress)); emit BondDeleted(address(bondToken), newOperator); } // event RedeemedBonds(address indexed from, uint256 amount); // event BoughtBonds(address indexed from, uint256 amount); /// Emitted each time the token becomes managed event BondAdded(address indexed bondTokenAddress); /// Emitted each time the token becomes unmanaged event BondDeleted(address indexed bondAddress, address indexed newOperator); /// Emitted each time TokenManager is updated event TokenManagerChanged(address indexed operator, address newManager); /// Emitted each time buyBonds paused / unpaused event BuyBondsPaused(address indexed operator, bool pause); /// Emitted each bonds are bought event BoughtBonds( address indexed owner, uint256 amountOfSynthetics, uint256 amountOfBonds ); /// Emitted each bonds are bought event SoldBonds(address indexed owner, uint256 amount); } // 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 pragma solidity >=0.6.0 <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, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT 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; } } //SPDX-License-Identifier: MIT pragma solidity =0.6.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "../libraries/UniswapLibrary.sol"; import "../interfaces/IOracle.sol"; import "../interfaces/ITokenManager.sol"; import "../interfaces/IBondManager.sol"; import "../interfaces/IEmissionManager.sol"; import "../SyntheticToken.sol"; import "../access/Operatable.sol"; import "../access/Migratable.sol"; /// TokenManager manages all tokens and their price data contract TokenManager is ITokenManager, Operatable, Migratable { struct TokenData { SyntheticToken syntheticToken; ERC20 underlyingToken; IUniswapV2Pair pair; IOracle oracle; } /// Token data (key is synthetic token address) mapping(address => TokenData) public tokenIndex; /// A set of managed synthetic token addresses address[] public tokens; /// Addresses of contracts allowed to mint / burn synthetic tokens address[] tokenAdmins; /// Uniswap factory address address public immutable uniswapFactory; IBondManager public bondManager; IEmissionManager public emissionManager; // ------- Constructor ---------- /// Creates a new Token Manager /// @param _uniswapFactory The address of the Uniswap Factory constructor(address _uniswapFactory) public { uniswapFactory = _uniswapFactory; } // ------- Modifiers ---------- /// Fails if a token is not currently managed by Token Manager /// @param syntheticTokenAddress The address of the synthetic token modifier managedToken(address syntheticTokenAddress) { require( isManagedToken(syntheticTokenAddress), "TokenManager: Token is not managed" ); _; } modifier initialized() { require( isInitialized(), "TokenManager: BondManager or EmissionManager is not initialized" ); _; } modifier tokenAdmin() { require( isTokenAdmin(msg.sender), "TokenManager: Must be called by token admin" ); _; } // ------- View ---------- /// A set of synthetic tokens under management /// @dev Deleted tokens are still present in the array but with address(0) function allTokens() public view override returns (address[] memory) { return tokens; } /// Checks if the token is managed by Token Manager /// @param syntheticTokenAddress The address of the synthetic token /// @return True if token is managed function isManagedToken(address syntheticTokenAddress) public view override returns (bool) { return address(tokenIndex[syntheticTokenAddress].syntheticToken) != address(0); } /// Checks if token ownerships are valid /// @return True if ownerships are valid function validTokenPermissions() public view returns (bool) { for (uint32 i = 0; i < tokens.length; i++) { SyntheticToken token = SyntheticToken(tokens[i]); if (address(token) != address(0)) { if (token.operator() != address(this)) { return false; } if (token.owner() != address(this)) { return false; } } } return true; } /// Checks if prerequisites for starting using TokenManager are fulfilled function isInitialized() public view returns (bool) { return (address(bondManager) != address(0)) && (address(emissionManager) != address(0)); } /// All token admins allowed to mint / burn function allTokenAdmins() public view returns (address[] memory) { return tokenAdmins; } /// Check if address is token admin /// @param admin - address to check function isTokenAdmin(address admin) public view override returns (bool) { for (uint256 i = 0; i < tokenAdmins.length; i++) { if (tokenAdmins[i] == admin) { return true; } } return false; } /// Address of the underlying token /// @param syntheticTokenAddress The address of the synthetic token function underlyingToken(address syntheticTokenAddress) public view override managedToken(syntheticTokenAddress) returns (address) { return address(tokenIndex[syntheticTokenAddress].underlyingToken); } /// Average price of the synthetic token according to price oracle /// @param syntheticTokenAddress The address of the synthetic token /// @param syntheticTokenAmount The amount to be priced /// @return The equivalent amount of the underlying token required to buy syntheticTokenAmount (average) /// @dev Fails if the token is not managed function averagePrice( address syntheticTokenAddress, uint256 syntheticTokenAmount ) public view override managedToken(syntheticTokenAddress) returns (uint256) { IOracle oracle = tokenIndex[syntheticTokenAddress].oracle; return oracle.consult(syntheticTokenAddress, syntheticTokenAmount); } /// Current price of the synthetic token according to Uniswap /// @param syntheticTokenAddress The address of the synthetic token /// @param syntheticTokenAmount The amount to be priced /// @return The equivalent amount of the underlying token required to buy syntheticTokenAmount /// @dev Fails if the token is not managed function currentPrice( address syntheticTokenAddress, uint256 syntheticTokenAmount ) public view override managedToken(syntheticTokenAddress) returns (uint256) { address underlyingTokenAddress = address(tokenIndex[syntheticTokenAddress].underlyingToken); (uint256 syntheticReserve, uint256 undelyingReserve) = UniswapLibrary.getReserves( uniswapFactory, syntheticTokenAddress, underlyingTokenAddress ); return UniswapLibrary.quote( syntheticTokenAmount, syntheticReserve, undelyingReserve ); } /// Get one synthetic unit /// @param syntheticTokenAddress The address of the synthetic token /// @return one unit of the synthetic asset function oneSyntheticUnit(address syntheticTokenAddress) public view override managedToken(syntheticTokenAddress) returns (uint256) { SyntheticToken synToken = SyntheticToken(tokenIndex[syntheticTokenAddress].syntheticToken); return uint256(10)**synToken.decimals(); } /// Get one underlying unit /// @param syntheticTokenAddress The address of the synthetic token /// @return one unit of the underlying asset function oneUnderlyingUnit(address syntheticTokenAddress) public view override managedToken(syntheticTokenAddress) returns (uint256) { ERC20 undToken = tokenIndex[syntheticTokenAddress].underlyingToken; return uint256(10)**undToken.decimals(); } // ------- External -------------------- /// Update oracle price /// @param syntheticTokenAddress The address of the synthetic token /// @dev This modifier must always come with managedToken and oncePerBlock function updateOracle(address syntheticTokenAddress) public override managedToken(syntheticTokenAddress) { IOracle oracle = tokenIndex[syntheticTokenAddress].oracle; try oracle.update() {} catch {} } // ------- External, Owner ---------- function addTokenAdmin(address admin) public onlyOwner { _addTokenAdmin(admin); } function deleteTokenAdmin(address admin) public onlyOwner { _deleteTokenAdmin(admin); } // ------- External, Operator ---------- /// Adds token to managed tokens /// @param syntheticTokenAddress The address of the synthetic token /// @param bondTokenAddress The address of the bond token /// @param underlyingTokenAddress The address of the underlying token /// @param oracleAddress The address of the price oracle for the pair /// @dev Requires the operator and the owner of the synthetic token to be set to TokenManager address before calling function addToken( address syntheticTokenAddress, address bondTokenAddress, address underlyingTokenAddress, address oracleAddress ) external onlyOperator initialized { require( syntheticTokenAddress != underlyingTokenAddress, "TokenManager: Synthetic token and Underlying tokens must be different" ); require( !isManagedToken(syntheticTokenAddress), "TokenManager: Token is already managed" ); SyntheticToken syntheticToken = SyntheticToken(syntheticTokenAddress); SyntheticToken bondToken = SyntheticToken(bondTokenAddress); ERC20 underlyingTkn = ERC20(underlyingTokenAddress); IOracle oracle = IOracle(oracleAddress); IUniswapV2Pair pair = IUniswapV2Pair( UniswapLibrary.pairFor( uniswapFactory, syntheticTokenAddress, underlyingTokenAddress ) ); require( syntheticToken.decimals() == bondToken.decimals(), "TokenManager: Synthetic and Bond tokens must have the same number of decimals" ); require( address(oracle.pair()) == address(pair), "TokenManager: Tokens and Oracle tokens are different" ); TokenData memory tokenData = TokenData(syntheticToken, underlyingTkn, pair, oracle); tokenIndex[syntheticTokenAddress] = tokenData; tokens.push(syntheticTokenAddress); bondManager.addBondToken(syntheticTokenAddress, bondTokenAddress); emit TokenAdded( syntheticTokenAddress, underlyingTokenAddress, address(oracle), address(pair) ); } /// Removes token from managed, transfers its operator and owner to target address /// @param syntheticTokenAddress The address of the synthetic token /// @param newOperator The operator and owner of the token will be transferred to this address. /// @dev Fails if the token is not managed function deleteToken(address syntheticTokenAddress, address newOperator) external managedToken(syntheticTokenAddress) onlyOperator initialized { bondManager.deleteBondToken(syntheticTokenAddress, newOperator); uint256 pos; for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i] == syntheticTokenAddress) { pos = i; } } TokenData memory data = tokenIndex[tokens[pos]]; data.syntheticToken.transferOperator(newOperator); data.syntheticToken.transferOwnership(newOperator); delete tokenIndex[syntheticTokenAddress]; delete tokens[pos]; emit TokenDeleted( syntheticTokenAddress, address(data.underlyingToken), address(data.oracle), address(data.pair) ); } /// Burns synthetic token from the owner /// @param syntheticTokenAddress The address of the synthetic token /// @param owner Owner of the tokens to burn /// @param amount Amount to burn function burnSyntheticFrom( address syntheticTokenAddress, address owner, uint256 amount ) public override managedToken(syntheticTokenAddress) initialized tokenAdmin { SyntheticToken token = tokenIndex[syntheticTokenAddress].syntheticToken; token.burnFrom(owner, amount); } /// Mints synthetic token /// @param syntheticTokenAddress The address of the synthetic token /// @param receiver Address to receive minted token /// @param amount Amount to mint function mintSynthetic( address syntheticTokenAddress, address receiver, uint256 amount ) public override managedToken(syntheticTokenAddress) initialized tokenAdmin { SyntheticToken token = tokenIndex[syntheticTokenAddress].syntheticToken; token.mint(receiver, amount); } // --------- Operator ----------- /// Updates bond manager address /// @param _bondManager new bond manager function setBondManager(address _bondManager) public onlyOperator { require( address(bondManager) != _bondManager, "TokenManager: bondManager with this address already set" ); deleteTokenAdmin(address(bondManager)); addTokenAdmin(_bondManager); bondManager = IBondManager(_bondManager); emit BondManagerChanged(msg.sender, _bondManager); } /// Updates emission manager address /// @param _emissionManager new emission manager function setEmissionManager(address _emissionManager) public onlyOperator { require( address(emissionManager) != _emissionManager, "TokenManager: emissionManager with this address already set" ); deleteTokenAdmin(address(emissionManager)); addTokenAdmin(_emissionManager); emissionManager = IEmissionManager(_emissionManager); emit EmissionManagerChanged(msg.sender, _emissionManager); } /// Updates oracle for synthetic token address /// @param syntheticTokenAddress The address of the synthetic token /// @param oracleAddress new oracle address function setOracle(address syntheticTokenAddress, address oracleAddress) public onlyOperator managedToken(syntheticTokenAddress) { IOracle oracle = IOracle(oracleAddress); require( oracle.pair() == tokenIndex[syntheticTokenAddress].pair, "TokenManager: Tokens and Oracle tokens are different" ); tokenIndex[syntheticTokenAddress].oracle = oracle; emit OracleUpdated(msg.sender, syntheticTokenAddress, oracleAddress); } // ------- Internal ---------- function _addTokenAdmin(address admin) internal { if (isTokenAdmin(admin)) { return; } tokenAdmins.push(admin); emit TokenAdminAdded(msg.sender, admin); } function _deleteTokenAdmin(address admin) internal { for (uint256 i = 0; i < tokenAdmins.length; i++) { if (tokenAdmins[i] == admin) { delete tokenAdmins[i]; emit TokenAdminDeleted(msg.sender, admin); } } } // ------- Events ---------- /// Emitted each time the token becomes managed event TokenAdded( address indexed syntheticTokenAddress, address indexed underlyingTokenAddress, address oracleAddress, address pairAddress ); /// Emitted each time the token becomes unmanaged event TokenDeleted( address indexed syntheticTokenAddress, address indexed underlyingTokenAddress, address oracleAddress, address pairAddress ); /// Emitted each time Oracle is updated event OracleUpdated( address indexed operator, address indexed syntheticTokenAddress, address oracleAddress ); /// Emitted each time BondManager is updated event BondManagerChanged(address indexed operator, address newManager); /// Emitted each time EmissionManager is updated event EmissionManagerChanged(address indexed operator, address newManager); /// Emitted when migrated event Migrated(address indexed operator, address target); event TokenAdminAdded(address indexed operator, address admin); event TokenAdminDeleted(address indexed operator, address admin); } //SPDX-License-Identifier: MIT pragma solidity =0.6.6; /// Checks time bounds for contract abstract contract Timeboundable { uint256 public immutable start; uint256 public immutable finish; /// @param _start The block timestamp to start from (in secs). Use 0 for unbounded start. /// @param _finish The block timestamp to finish in (in secs). Use 0 for unbounded finish. constructor(uint256 _start, uint256 _finish) internal { require( (_start != 0) || (_finish != 0), "Timebound: either start or finish must be nonzero" ); require( (_finish == 0) || (_finish > _start), "Timebound: finish must be zero or greater than start" ); uint256 s = _start; if (s == 0) { s = block.timestamp; } uint256 f = _finish; if (f == 0) { f = uint256(-1); } start = s; finish = f; } /// Checks if timebounds are satisfied modifier inTimeBounds() { require(block.timestamp >= start, "Timeboundable: Not started yet"); require(block.timestamp <= finish, "Timeboundable: Already finished"); _; } } // SPDX-License-Identifier: MIT pragma solidity =0.6.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./MigratableOwnership.sol"; contract Migratable is MigratableOwnership { /// Migrate balances of a set of tokens /// @param tokens a set of tokens to transfer balances to target /// @param target new owner of contract balances function migrateBalances(address[] memory tokens, address target) public onlyOwner nonReentrant { for (uint256 i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i]); uint256 balance = token.balanceOf(address(this)); if (balance > 0) { token.transfer(target, balance); emit MigratedBalance( msg.sender, address(token), target, balance ); } } } event MigratedBalance( address indexed owner, address indexed token, address target, uint256 value ); } //SPDX-License-Identifier: MIT pragma solidity =0.6.6; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; /// Bond manager as seen by other managers interface IBondManager { /// Called when new token is added in TokenManager /// @param syntheticTokenAddress The address of the synthetic token /// @param bondTokenAddress The address of the bond token function addBondToken( address syntheticTokenAddress, address bondTokenAddress ) external; /// Called when token is deleted in TokenManager /// @param syntheticTokenAddress The address of the synthetic token /// @param newOperator New operator for the bond token function deleteBondToken(address syntheticTokenAddress, address newOperator) external; function bondIndex(address syntheticTokenAddress) external returns (address); } //SPDX-License-Identifier: MIT pragma solidity =0.6.6; import "./ISmelter.sol"; /// Token manager as seen by other managers interface ITokenManager is ISmelter { /// A set of synthetic tokens under management /// @dev Deleted tokens are still present in the array but with address(0) function allTokens() external view returns (address[] memory); /// Checks if the token is managed by Token Manager /// @param syntheticTokenAddress The address of the synthetic token /// @return True if token is managed function isManagedToken(address syntheticTokenAddress) external view returns (bool); /// Address of the underlying token /// @param syntheticTokenAddress The address of the synthetic token function underlyingToken(address syntheticTokenAddress) external view returns (address); /// Average price of the synthetic token according to price oracle /// @param syntheticTokenAddress The address of the synthetic token /// @param syntheticTokenAmount The amount to be priced /// @return The equivalent amount of the underlying token required to buy syntheticTokenAmount (average) /// @dev Fails if the token is not managed function averagePrice( address syntheticTokenAddress, uint256 syntheticTokenAmount ) external view returns (uint256); /// Current price of the synthetic token according to Uniswap /// @param syntheticTokenAddress The address of the synthetic token /// @param syntheticTokenAmount The amount to be priced /// @return The equivalent amount of the underlying token required to buy syntheticTokenAmount /// @dev Fails if the token is not managed function currentPrice( address syntheticTokenAddress, uint256 syntheticTokenAmount ) external view returns (uint256); /// Updates Oracle for the synthetic asset /// @param syntheticTokenAddress The address of the synthetic token function updateOracle(address syntheticTokenAddress) external; /// Get one synthetic unit /// @param syntheticTokenAddress The address of the synthetic token /// @return one unit of the synthetic asset function oneSyntheticUnit(address syntheticTokenAddress) external view returns (uint256); /// Get one underlying unit /// @param syntheticTokenAddress The address of the synthetic token /// @return one unit of the underlying asset function oneUnderlyingUnit(address syntheticTokenAddress) external view returns (uint256); } // 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 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 { } } 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; } //SPDX-License-Identifier: MIT pragma solidity =0.6.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; /// Created as a separate unit because the `uniswap` lib has conflicting imports of `SafeMath` with `openzeppelin` library UniswapLibrary { using SafeMath for uint256; /// Calculates the CREATE2 address for a pair without making any external calls /// @param factory Uniswap factory address /// @param tokenA One token in the pair /// @param tokenB The other token in the pair /// @return pair Address of the Uniswap pair function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } // returns sorted token addresses, used to handle return values from pairs sorted in this order /// @param tokenA The address of tokenA /// @param tokenB The address of tokenB /// @return token0 token1 Sorted asc addresses of tokens function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } /// Given some amount of an asset and pair reserves, returns an equivalent amount of the other asset /// @param amountA The amount of tokenA /// @param reserveA The reserver of token A /// @param reserveB The reserver of token B /// @return amountB Equivalent amount of token B function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require( reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); amountB = amountA.mul(reserveB) / reserveA; } /// Fetches and sorts the reserves for a pair /// @param factory Uniswap factory address /// @param tokenA One token in the pair /// @param tokenB The other token in the pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } } //SPDX-License-Identifier: MIT pragma solidity =0.6.6; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; /// Fixed window oracle that recomputes the average price for the entire period once every period interface IOracle { /// Updates oracle price /// @dev Works only once in a period, other times reverts function update() external; /// Get the price of token. /// @param token The address of one of two tokens (the one to get the price for) /// @param amountIn The amount of token to estimate /// @return amountOut The amount of other token equivalent /// @dev This will always return 0 before update has been called successfully for the first time. function consult(address token, uint256 amountIn) external view returns (uint256 amountOut); function pair() external view returns (IUniswapV2Pair); function token0() external view returns (address); function token1() external view returns (address); } //SPDX-License-Identifier: MIT pragma solidity =0.6.6; /// Emission manager as seen by other managers interface IEmissionManager { } //SPDX-License-Identifier: MIT pragma solidity =0.6.6; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "./access/Operatable.sol"; /// @title Synthetic token for the Klondike platform contract SyntheticToken is ERC20Burnable, Operatable { /// Creates a new synthetic token /// @param _name Name of the token /// @param _symbol Ticker for the token /// @param _decimals Number of decimals constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } /// Mints tokens to the recepient /// @param recipient The address of recipient /// @param amount The amount of tokens to mint function mint(address recipient, uint256 amount) public onlyOperator returns (bool) { _mint(recipient, amount); } /// Burns token from the caller /// @param amount The amount of tokens to burn function burn(uint256 amount) public override onlyOperator { super.burn(amount); } /// Burns token from address /// @param account The account to burn from /// @param amount The amount of tokens to burn /// @dev The allowance for sender in address account must be /// strictly >= amount. Otherwise the function call will fail. function burnFrom(address account, uint256 amount) public override onlyOperator { super.burnFrom(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity =0.6.6; import "@openzeppelin/contracts/access/Ownable.sol"; /// Introduces `Operator` role that can be changed only by Owner. abstract contract Operatable is Ownable { address public operator; constructor() internal { operator = msg.sender; } modifier onlyOperator() { require(msg.sender == operator, "Only operator can call this method"); _; } /// Set new operator /// @param newOperator New operator to be set /// @dev Only owner is allowed to call this method. function transferOperator(address newOperator) public onlyOwner { emit OperatorTransferred(operator, newOperator); operator = newOperator; } event OperatorTransferred( address indexed previousOperator, address indexed newOperator ); } // 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.6; /// Smelter can mint and burn tokens interface ISmelter { /// Burn SyntheticToken /// @param syntheticTokenAddress The address of the synthetic token /// @param owner Owner of the tokens to burn /// @param amount Amount to burn function burnSyntheticFrom( address syntheticTokenAddress, address owner, uint256 amount ) external; /// Mints synthetic token /// @param syntheticTokenAddress The address of the synthetic token /// @param receiver Address to receive minted token /// @param amount Amount to mint function mintSynthetic( address syntheticTokenAddress, address receiver, uint256 amount ) external; /// Check if address is token admin /// @param admin - address to check function isTokenAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/Context.sol"; import "./ERC20.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 { using SafeMath for uint256; /** * @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 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // 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: MIT pragma solidity =0.6.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./Operatable.sol"; contract MigratableOwnership is Ownable, ReentrancyGuard { /// Migrate ownership and operator of a set of tokens /// @param tokens a set of tokens to transfer ownership and operator to target /// @param target new owner and operator of the token function migrateOwnership(address[] memory tokens, address target) public onlyOwner nonReentrant { for (uint256 i = 0; i < tokens.length; i++) { Operatable token = Operatable(tokens[i]); if (token.owner() == address(this)) { token.transferOperator(target); token.transferOwnership(target); emit MigratedOwnership(msg.sender, address(token), target); } } } event MigratedOwnership( address indexed owner, address indexed token, address target ); }
Buy bonds with synthetic syntheticTokenAddress The address of the synthetic token amountOfSyntheticIn Amount of synthetic to sell minAmountBondsOut Minimum amount of bonds out Fails if the token is not managed
function buyBonds( address syntheticTokenAddress, uint256 amountOfSyntheticIn, uint256 minAmountBondsOut ) public nonReentrant managedToken(syntheticTokenAddress) inTimeBounds { tokenManager.updateOracle(syntheticTokenAddress); require( !pauseBuyBonds, "BondManager: Buying bonds is temporarily suspended" ); uint256 amountOfBonds = quoteBonds(syntheticTokenAddress, amountOfSyntheticIn); require( amountOfBonds >= minAmountBondsOut, "BondManager: number of bonds is less than minAmountBondsOut" ); tokenManager.burnSyntheticFrom( syntheticTokenAddress, msg.sender, amountOfSyntheticIn ); SyntheticToken bondToken = SyntheticToken(bondIndex[syntheticTokenAddress]); bondToken.mint(msg.sender, amountOfBonds); emit BoughtBonds(msg.sender, amountOfSyntheticIn, amountOfBonds); }
5,829,313
pragma solidity ^0.4.24; /// @title ERC-20 interface /// @dev Full ERC-20 interface is described at https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md. interface ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); } /// @title ERC-677 (excluding ERC-20) interface /// @dev Full ERC-677 interface is discussed at https://github.com/ethereum/EIPs/issues/677. interface ERC677 { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferAndCall(address to, uint256 value, bytes data) external returns (bool); } /// @title ERC-677 mint/burn/claim extension interface /// @dev Extension of ERC-677 interface for allowing using a token in Token Bridge. interface ERC677Bridgeable { event Mint(address indexed receiver, uint256 value); event Burn(address indexed burner, uint256 value); function mint(address receiver, uint256 value) external returns (bool); function burn(uint256 value) external; function claimTokens(address token, address to) external; } /// @title SafeMath /// @dev Math operations with safety checks that throw on error. library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /// @title SafeOwnable /// @dev The SafeOwnable contract has an owner address, and provides basic authorization control /// functions, this simplifies the implementation of "user permissions". contract SafeOwnable { // EVENTS event OwnershipProposed(address indexed previousOwner, address indexed newOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // PUBLIC FUNCTIONS /// @dev The SafeOwnable constructor sets the original `owner` of the contract to the sender account. constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /// @dev Allows the current owner to propose control of the contract to a new owner. /// @param newOwner The address to propose ownership to. function proposeOwnership(address newOwner) public onlyOwner { require(newOwner != address(0) && newOwner != _owner); _ownerCandidate = newOwner; emit OwnershipProposed(_owner, _ownerCandidate); } /// @dev Allows the current owner candidate to accept proposed ownership and set actual owner of a contract. function acceptOwnership() public onlyOwnerCandidate { emit OwnershipTransferred(_owner, _ownerCandidate); _owner = _ownerCandidate; _ownerCandidate = address(0); } /// @dev Returns the address of the owner. function owner() public view returns (address) { return _owner; } /// @dev Returns the address of the owner candidate. function ownerCandidate() public view returns (address) { return _ownerCandidate; } // MODIFIERS /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == _owner); _; } /// @dev Throws if called by any account other than the owner candidate. modifier onlyOwnerCandidate() { require(msg.sender == _ownerCandidate); _; } // FIELDS address internal _owner; address internal _ownerCandidate; } /// @title Standard ERC-20 token /// @dev Implementation of the basic ERC-20 token. contract TokenERC20 is ERC20 { using SafeMath for uint256; // PUBLIC FUNCTIONS /// @dev Transfers tokens to a specified address. /// @param to The address to transfer tokens to. /// @param value The amount of tokens to be transferred. /// @return A boolean that indicates if the operation was successful. function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /// @dev Transfers tokens from one address to another. /// @param from The address to transfer tokens from. /// @param to The address to transfer tokens to. /// @param value The amount of tokens to be transferred. /// @return A boolean that indicates if the operation was successful. function transferFrom(address from, address to, uint256 value) public returns (bool) { _decreaseAllowance(from, msg.sender, value); _transfer(from, to, value); return true; } /// @dev Approves a specified address to spend a 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 an unfortunate transaction ordering. One possible solution to mitigate this /// rare 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 Address which will be allowed to spend the tokens. /// @param value Amount of tokens to allow to be spent. /// @return A boolean that indicates if the operation was successful. function approve(address spender, uint256 value) public returns (bool) { _allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Increases the amount of tokens that an owner allowed to spent by the spender. /// Method approve() should be called when _allowances[spender] == 0. To decrement allowance /// 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 tokens. /// @param value The amount of tokens to increase the allowance by. /// @return A boolean that indicates if the operation was successful. function increaseAllowance(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _increaseAllowance(msg.sender, spender, value); return true; } /// @dev Decreases the amount of tokens that an owner allowed to spent by the spender. /// Method approve() should be called when _allowances[spender] == 0. To decrement allowance /// 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 tokens. /// @param value The amount of tokens to decrease the allowance by. /// @return A boolean that indicates if the operation was successful. function decreaseAllowance(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _decreaseAllowance(msg.sender, spender, value); return true; } /// @dev Returns total amount of tokens in existence. /// @return A uint256 representing the amount of tokens in existence. function totalSupply() public view returns (uint256) { return _totalSupply; } /// @dev Gets the balance of a specified address. /// @param owner The address to query the balance of. /// @return A uint256 representing the amount of tokens owned by the specified 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 spend by the spender. /// @param owner The address which owns the tokens. /// @param spender The address which will spend the tokens. /// @return A uint256 representing the amount of tokens still available to spend by the spender. function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } // INTERNAL FUNCTIONS /// @dev Transfers tokens from one address to another address. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param value The amount to be transferred. function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); require(value <= _balances[from]); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /// @dev Increases the amount of tokens that an owner allowed to spent by the spender. /// Method approve() should be called when _allowances[spender] == 0. To decrement allowance /// is better to use this function to avoid 2 calls (and wait until the first transaction is mined). /// @param owner The address which owns the tokens. /// @param spender The address which will spend the tokens. /// @param value The amount of tokens to increase the allowance by. function _increaseAllowance(address owner, address spender, uint256 value) internal { require(value > 0); _allowances[owner][spender] = _allowances[owner][spender].add(value); emit Approval(owner, spender, _allowances[owner][spender]); } /// @dev Decreases the amount of tokens that an owner allowed to spent by the spender. /// Method approve() should be called when _allowances[spender] == 0. To decrement allowance /// is better to use this function to avoid 2 calls (and wait until the first transaction is mined). /// @param owner The address which owns the tokens. /// @param spender The address which will spend the tokens. /// @param value The amount of tokens to decrease the allowance by. function _decreaseAllowance(address owner, address spender, uint256 value) internal { require(value > 0 && value <= _allowances[owner][spender]); _allowances[owner][spender] = _allowances[owner][spender].sub(value); emit Approval(owner, spender, _allowances[owner][spender]); } /// @dev Internal function that mints specified amount of tokens and assigns it to an address. /// This encapsulates the modification of balances such that the proper events are emitted. /// @param receiver The address that will receive the minted tokens. /// @param value The amount of tokens that will be minted. function _mint(address receiver, uint256 value) internal { require(receiver != address(0)); require(value > 0); _balances[receiver] = _balances[receiver].add(value); _totalSupply = _totalSupply.add(value); //_totalMinted = _totalMinted.add(value); emit Transfer(address(0), receiver, value); } /// @dev Internal function that burns specified amount of tokens of a given address. /// @param burner The address from which tokens will be burnt. /// @param value The amount of tokens that will be burnt. function _burn(address burner, uint256 value) internal { require(burner != address(0)); require(value > 0 && value <= _balances[burner]); _balances[burner] = _balances[burner].sub(value); _totalSupply = _totalSupply.sub(value); emit Transfer(burner, address(0), value); } /// @dev Internal function that burns specified amount of tokens of a given address, /// deducting from the sender's allowance for said account. Uses the internal burn function. /// @param burner The address from which tokens will be burnt. /// @param value The amount of tokens that will be burnt. function _burnFrom(address burner, uint256 value) internal { _decreaseAllowance(burner, msg.sender, value); _burn(burner, value); } // FIELDS uint256 internal _totalSupply; mapping (address => uint256) internal _balances; mapping (address => mapping(address => uint256)) internal _allowances; } /// @title Papyrus Token contract (PPR). contract PapyrusToken is SafeOwnable, TokenERC20, ERC677, ERC677Bridgeable { // EVENTS event ControlByOwnerRevoked(); event MintableChanged(bool mintable); event TransferableChanged(bool transferable); event ContractFallbackCallFailed(address from, address to, uint256 value); event BridgeContractChanged(address indexed previousBridgeContract, address indexed newBridgeContract); // PUBLIC FUNCTIONS constructor() public { _totalSupply = PPR_INITIAL_SUPPLY; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /// @dev Transfers tokens to a specified address with additional data if the recipient is a contact. /// @param to The address to transfer tokens to. /// @param value The amount of tokens to be transferred. /// @param data The extra data to be passed to the receiving contract. /// @return A boolean that indicates if the operation was successful. function transferAndCall(address to, uint256 value, bytes data) external canTransfer returns (bool) { require(to != address(this)); require(super.transfer(to, value)); emit Transfer(msg.sender, to, value, data); if (isContract(to)) { require(contractFallback(msg.sender, to, value, data)); } return true; } /// @dev Transfers tokens to a specified address. /// @param to The address to transfer tokens to. /// @param value The amount of tokens to be transferred. /// @return A boolean that indicates if the operation was successful. function transfer(address to, uint256 value) public canTransfer returns (bool) { require(super.transfer(to, value)); if (isContract(to) && !contractFallback(msg.sender, to, value, new bytes(0))) { if (to == _bridgeContract) { revert(); } emit ContractFallbackCallFailed(msg.sender, to, value); } return true; } /// @dev Transfers tokens from one address to another. /// @param from The address to transfer tokens from. /// @param to The address to transfer tokens to. /// @param value The amount of tokens to be transferred. /// @return A boolean that indicates if the operation was successful. function transferFrom(address from, address to, uint256 value) public canTransfer returns (bool) { require(super.transferFrom(from, to, value)); if (isContract(to) && !contractFallback(from, to, value, new bytes(0))) { if (to == _bridgeContract) { revert(); } emit ContractFallbackCallFailed(from, to, value); } return true; } /// @dev Transfers tokens to a specified addresses (optimized version for initial sending tokens). /// @param recipients Addresses to transfer tokens to. /// @param values Amounts of tokens to be transferred. /// @return A boolean that indicates if the operation was successful. function airdrop(address[] recipients, uint256[] values) public canTransfer returns (bool) { require(recipients.length == values.length); uint256 senderBalance = _balances[msg.sender]; for (uint256 i = 0; i < values.length; i++) { uint256 value = values[i]; address to = recipients[i]; require(senderBalance >= value); if (msg.sender != recipients[i]) { senderBalance = senderBalance - value; _balances[to] += value; } emit Transfer(msg.sender, to, value); } _balances[msg.sender] = senderBalance; return true; } /// @dev Mints specified amount of tokens and assigns it to a specified address. /// @param receiver The address that will receive the minted tokens. /// @param value The amount of tokens that will be minted. function mint(address receiver, uint256 value) public canMint returns (bool) { _mint(receiver, value); _totalMinted = _totalMinted.add(value); emit Mint(receiver, value); return true; } /// @dev Burns specified amount of tokens of the sender. /// @param value The amount of token to be burnt. function burn(uint256 value) public canBurn { _burn(msg.sender, value); _totalBurnt = _totalBurnt.add(value); emit Burn(msg.sender, value); } /// @dev Burns specified amount of tokens of the specified account. /// @param burner The address from which tokens will be burnt. /// @param value The amount of token to be burnt. function burnByOwner(address burner, uint256 value) public canBurnByOwner { _burn(burner, value); _totalBurnt = _totalBurnt.add(value); emit Burn(burner, value); } /// @dev Transfers funds stored on the token contract to specified recipient (required by token bridge). function claimTokens(address token, address to) public onlyOwnerOrBridgeContract { require(to != address(0)); if (token == address(0)) { to.transfer(address(this).balance); } else { ERC20 erc20 = ERC20(token); uint256 balance = erc20.balanceOf(address(this)); require(erc20.transfer(to, balance)); } } /// @dev Revokes control by owner so it is not possible to burn tokens from any account by contract owner. function revokeControlByOwner() public onlyOwner { require(_controllable); _controllable = false; emit ControlByOwnerRevoked(); } /// @dev Changes ability to mint tokens by permissioned accounts. function setMintable(bool mintable) public onlyOwner { require(_mintable != mintable); _mintable = mintable; emit MintableChanged(_mintable); } /// @dev Changes ability to transfer tokens by token holders. function setTransferable(bool transferable) public onlyOwner { require(_transferable != transferable); _transferable = transferable; emit TransferableChanged(_transferable); } /// @dev Changes address of token bridge contract. function setBridgeContract(address bridgeContract) public onlyOwner { require(_controllable); require(bridgeContract != address(0) && bridgeContract != _bridgeContract && isContract(bridgeContract)); emit BridgeContractChanged(_bridgeContract, bridgeContract); _bridgeContract = bridgeContract; } /// @dev Turn off renounceOwnership() method from Ownable contract. function renounceOwnership() public pure { revert(); } /// @dev Returns a boolean flag representing ability to burn tokens from any account by contract owner. /// @return A boolean that indicates if tokens can be burnt from any account by contract owner. function controllableByOwner() public view returns (bool) { return _controllable; } /// @dev Returns a boolean flag representing token mint ability. /// @return A boolean that indicates if tokens can be mintable by permissioned accounts. function mintable() public view returns (bool) { return _mintable; } /// @dev Returns a boolean flag representing token transfer ability. /// @return A boolean that indicates if tokens can be transferred by token holders. function transferable() public view returns (bool) { return _transferable; } /// @dev Returns an address of token bridge contract. /// @return An address of token bridge contract. function bridgeContract() public view returns (address) { return _bridgeContract; } /// @dev Returns total amount of minted tokens. /// @return A uint256 representing the amount of tokens were mint during token lifetime. function totalMinted() public view returns (uint256) { return _totalMinted; } /// @dev Returns total amount of burnt tokens. /// @return A uint256 representing the amount of tokens were burnt during token lifetime. function totalBurnt() public view returns (uint256) { return _totalBurnt; } /// @dev Returns version of token interfaces (required by token bridge). function getTokenInterfacesVersion() public pure returns (uint64, uint64, uint64) { uint64 major = 2; uint64 minor = 0; uint64 patch = 0; return (major, minor, patch); } // PRIVATE FUNCTIONS /// @dev Calls method onTokenTransfer() on specified contract address `receiver`. /// @return A boolean that indicates if the operation was successful. function contractFallback(address from, address receiver, uint256 value, bytes data) private returns (bool) { return receiver.call(abi.encodeWithSignature("onTokenTransfer(address,uint256,bytes)", from, value, data)); } /// @dev Determines if specified address is contract address. /// @return A boolean that indicates if specified address is contract address. function isContract(address account) private view returns (bool) { uint256 codeSize; assembly { codeSize := extcodesize(account) } return codeSize > 0; } // MODIFIERS modifier onlyOwnerOrBridgeContract() { require(msg.sender == _owner || msg.sender == _bridgeContract); _; } modifier canMint() { require(_mintable); require(msg.sender == _owner || msg.sender == _bridgeContract); _; } modifier canBurn() { require(msg.sender == _owner || msg.sender == _bridgeContract); _; } modifier canBurnByOwner() { require(msg.sender == _owner && _controllable); _; } modifier canTransfer() { require(_transferable || msg.sender == _owner); _; } // FIELDS // Standard fields used to describe the token string public constant name = "Papyrus Token"; string public constant symbol = "PPR"; uint8 public constant decimals = 18; // At the start of the token existence it is fully controllable by owner bool private _controllable = true; // At the start of the token existence it is mintable bool private _mintable = true; // At the start of the token existence it is not transferable bool private _transferable = false; // Address of token bridge contract address private _bridgeContract; // Total amount of tokens minted during token lifetime uint256 private _totalMinted; // Total amount of tokens burnt during token lifetime uint256 private _totalBurnt; // Amount of initially supplied tokens is constant and equals to 1,000,000,000 PPR uint256 private constant PPR_INITIAL_SUPPLY = 10**27; }
Revokes control by owner so it is not possible to burn tokens from any account by contract owner.
function revokeControlByOwner() public onlyOwner { require(_controllable); _controllable = false; emit ControlByOwnerRevoked(); }
12,553,093
./partial_match/40/0xF5282616a1F9CffFE24122a1A76B0bf2ce087357/sources/contracts/WagPool.sol
The operation of withdraw. _shares: Number of shares to withdraw _amount: Number of amount to withdraw/
function withdrawOperation(uint256 _shares, uint256 _amount) internal { UserInfo storage user = userInfo[msg.sender]; require(_shares <= user.shares, "Withdraw amount exceeds balance"); require(user.lockEndTime < block.timestamp, "Still in lock"); if (VCake != address(0)) { IVCake(VCake).withdraw(msg.sender); } uint256 sharesPercent = (_shares * PRECISION_FACTOR_SHARE) / user.shares; if (_shares == 0 && _amount > 0) { uint256 pool = balanceOf(); if (currentShare > user.shares) { currentShare = user.shares; } currentShare = (sharesPercent * user.shares) / PRECISION_FACTOR_SHARE; } uint256 currentAmount = (balanceOf() * currentShare) / totalShares; user.shares -= currentShare; totalShares -= currentShare; !freeWithdrawFeeUsers[msg.sender] && (block.timestamp < user.lastDepositedTime + withdrawFeePeriod) ) { uint256 feeRate = withdrawFee; if (_isContract(msg.sender)) { feeRate = withdrawFeeContract; } uint256 currentWithdrawFee = (currentAmount * feeRate) / 10000; token.safeTransfer(treasury, currentWithdrawFee); currentAmount -= currentWithdrawFee; } token.safeTransfer(msg.sender, currentAmount); if (user.shares > 0) { user.cakeAtLastUserAction = (user.shares * balanceOf()) / totalShares; user.cakeAtLastUserAction = 0; } user.lastUserActionTime = block.timestamp; emit Withdraw(msg.sender, currentAmount, currentShare); }
8,827,065
/// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import '@gnosis.pm/zodiac/contracts/core/Module.sol'; import './ProposalRelayer.sol'; /** * @title Snapshot X L1 execution Zodiac module * @author @Orland0x - <orlandothefraser@gmail.com> * @notice Trustless L1 execution of Snapshot X decisions via a Gnosis Safe * @dev Work in progress */ contract SnapshotXL1Executor is Module, SnapshotXProposalRelayer { /// @dev keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"); bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; /// @dev keccak256("Transaction(address to,uint256 value,bytes data,uint8 operation,uint256 nonce)"); bytes32 public constant TRANSACTION_TYPEHASH = 0x72e9670a7ee00f5fbf1049b8c38e3f22fab7e9b85029e85cf9412f17fdd5c2ad; /// Counter that is incremented each time a proposal is received. uint256 public proposalIndex; /// Mapping of whitelisted contracts (addresses should be L2 space contracts) mapping(uint256 => bool) public whitelistedSpaces; /// The state of a proposal index exists in one of the 5 categories. This can be queried using the getProposalState view function enum ProposalState { NotReceived, Received, Executing, Executed, Cancelled } /// Stores the execution details and execution progress of each proposal received struct ProposalExecution { // array of Transaction Hashes for each transaction in the proposal bytes32[] txHashes; // counter which stores the index of the next transaction in the proposal that should be executed uint256 executionCounter; // whether the proposal has been cancelled. Required to fully define the proposal state as a function of this struct bool cancelled; } /// Map of proposal index to the corresponding proposal execution struct mapping(uint256 => ProposalExecution) public proposalIndexToProposalExecution; /* EVENTS */ /** * @dev Emitted when a new module proxy instance has been deployed * @param initiator Address of contract deployer * @param _owner Address of the owner of this contract * @param _avatar Address that will ultimately execute function calls * @param _target Address that this contract will pass transactions to * @param _l2ExecutionRelayer Address of the StarkNet contract that will send execution details to this contract in a L2 -> L1 message * @param _starknetCore Address of the StarkNet Core contract */ event SnapshotXL1ExecutorSetUpComplete( address indexed initiator, address indexed _owner, address indexed _avatar, address _target, uint256 _l2ExecutionRelayer, address _starknetCore ); /** * @dev Emitted when a new proposal is received from StarkNet * @param proposalIndex Index of proposal */ event ProposalReceived(uint256 proposalIndex); /** * @dev Emitted when a Transaction in a proposal is executed. * @param proposalIndex Index of proposal * @param txHash The transaction hash * @notice Could remove to save some gas and only emit event when all txs are executed */ event TransactionExecuted(uint256 proposalIndex, bytes32 txHash); /** * @dev Emitted when all transactions in a proposal have been executed * @param proposalIndex Index of proposal */ event ProposalExecuted(uint256 proposalIndex); /** * @dev Emitted when a proposal get cancelled * @param proposalIndex Index of proposal */ event ProposalCancelled(uint256 proposalIndex); /* Constructor */ /** * @dev Constructs the master contract * @param _owner Address of the owner of this contract * @param _avatar Address that will ultimately execute function calls * @param _target Address that this contract will pass transactions to * @param _starknetCore Address of the StarkNet Core contract * @param _l2ExecutionRelayer Address of the StarkNet contract that will send execution details to this contract in a L2 -> L1 message * @param _l2SpacesToWhitelist Array of spaces deployed on L2 that are allowed to interact with this contract */ constructor( address _owner, address _avatar, address _target, address _starknetCore, uint256 _l2ExecutionRelayer, uint256[] memory _l2SpacesToWhitelist ) { bytes memory initParams = abi.encode( _owner, _avatar, _target, _starknetCore, _l2ExecutionRelayer, _l2SpacesToWhitelist ); setUp(initParams); } /** * @dev Proxy constructor * @param initParams Initialization parameters */ function setUp(bytes memory initParams) public override initializer { ( address _owner, address _avatar, address _target, address _starknetCore, uint256 _l2ExecutionRelayer, uint256[] memory _l2SpacesToWhitelist ) = abi.decode(initParams, (address, address, address, address, uint256, uint256[])); __Ownable_init(); transferOwnership(_owner); avatar = _avatar; target = _target; setUpSnapshotXProposalRelayer(_starknetCore, _l2ExecutionRelayer); for (uint256 i = 0; i < _l2SpacesToWhitelist.length; i++) { whitelistedSpaces[_l2SpacesToWhitelist[i]] = true; } emit SnapshotXL1ExecutorSetUpComplete( msg.sender, _owner, _avatar, _target, _l2ExecutionRelayer, _starknetCore ); } /* External */ /** * @dev Updates the list of accepted spaces on l2. Only callable by the `owner`. * @param toAdd List of addresses to add to the whitelist. * @param toRemove List of addressess to remove from the whitelist. */ function editWhitelist(uint256[] memory toAdd, uint256[] calldata toRemove) external onlyOwner { // Add the requested entries for (uint256 i = 0; i < toAdd.length; i++) { whitelistedSpaces[toAdd[i]] = true; } // Remove the requested entries for (uint256 i = 0; i < toRemove.length; i++) { whitelistedSpaces[toRemove[i]] = false; } } /** * @dev Initializes a new proposal execution struct on the receival of a completed proposal from StarkNet * @param executionHashLow Lowest 128 bits of the hash of all the transactions in the proposal * @param executionHashHigh Highest 128 bits of the hash of all the transactions in the proposal * @param proposalOutcome Whether the proposal was accepted / rejected / cancelled * @param _txHashes Array of transaction hashes in proposal */ function receiveProposal( uint256 callerAddress, uint256 proposalOutcome, uint256 executionHashLow, uint256 executionHashHigh, bytes32[] memory _txHashes ) external { //External call will fail if finalized proposal message was not received on L1. _receiveFinalizedProposal(callerAddress, proposalOutcome, executionHashLow, executionHashHigh); // require(whitelistedSpaces[callerAddress] == true, 'Invalid caller'); // require(proposalOutcome != 0, 'Proposal did not pass'); // require(_txHashes.length > 0, 'proposal must contain transactions'); // // Re-assemble the lowest and highest bytes to get the full execution hash // uint256 executionHash = (executionHashHigh << 128) + executionHashLow; // require(bytes32(executionHash) == keccak256(abi.encode(_txHashes)), 'Invalid execution'); // proposalIndexToProposalExecution[proposalIndex].txHashes = _txHashes; // proposalIndex++; emit ProposalReceived(proposalIndex); } /** * @dev Initializes a new proposal execution struct (To test execution without actually receiving message) * @param executionHash Hash of all the transactions in the proposal * @param proposalOutcome Whether proposal was accepted / rejected / cancelled * @param _txHashes Array of transaction hashes in proposal */ function receiveProposalTest( uint256 callerAddress, uint256 executionHash, uint256 proposalOutcome, bytes32[] memory _txHashes ) external { require(callerAddress != 0); require(proposalOutcome == 1, 'Proposal did not pass'); require(_txHashes.length > 0, 'proposal must contain transactions'); require(bytes32(executionHash) == keccak256(abi.encode(_txHashes)), 'Invalid execution'); proposalIndexToProposalExecution[proposalIndex].txHashes = _txHashes; proposalIndex++; emit ProposalReceived(proposalIndex); } /** * @dev Cancels a set of proposals * @param _proposalIndexes Array of proposal indexes that should be cancelled */ function cancelProposals(uint256[] memory _proposalIndexes) external onlyOwner { for (uint256 i = 0; i < _proposalIndexes.length; i++) { require( getProposalState(_proposalIndexes[i]) != ProposalState.NotReceived, 'Proposal not received, nothing to cancel' ); require( getProposalState(_proposalIndexes[i]) != ProposalState.Executed, 'Execution completed, nothing to cancel' ); require( proposalIndexToProposalExecution[_proposalIndexes[i]].cancelled == false, 'proposal is already cancelled' ); //to cancel a proposal, we can set the execution counter for the proposal to the number of transactions in the proposal. //We must also set a boolean in the Proposal Execution struct to true, without this there would be no way for the state to differentiate between a cancelled and an executed proposal. proposalIndexToProposalExecution[_proposalIndexes[i]] .executionCounter = proposalIndexToProposalExecution[_proposalIndexes[i]].txHashes.length; proposalIndexToProposalExecution[_proposalIndexes[i]].cancelled = true; emit ProposalCancelled(_proposalIndexes[i]); } } /** * @dev Executes a single transaction in a proposal * @param _proposalIndex Index of proposal * @param to the contract to be called by the avatar * @param value ether value to pass with the call * @param data the data to be executed from the call * @param operation Call or DelegateCall indicator */ function executeProposalTx( uint256 _proposalIndex, address to, uint256 value, bytes memory data, Enum.Operation operation ) public { bytes32 txHash = getTransactionHash(to, value, data, operation); require( proposalIndexToProposalExecution[_proposalIndex].txHashes[ proposalIndexToProposalExecution[_proposalIndex].executionCounter ] == txHash, 'Invalid transaction or invalid transaction order' ); proposalIndexToProposalExecution[_proposalIndex].executionCounter++; require(exec(to, value, data, operation), 'Module transaction failed'); emit TransactionExecuted(_proposalIndex, txHash); if (getProposalState(_proposalIndex) == ProposalState.Executed) { emit ProposalExecuted(_proposalIndex); } } /** * @dev Wrapper function around executeProposalTx that will execute all transactions in a proposal * @param _proposalIndex Index of proposal * @param tos Array of contracts to be called by the avatar * @param values Array of ether values to pass with the calls * @param data Array of data to be executed from the calls * @param operations Array of Call or DelegateCall indicators */ function executeProposalTxBatch( uint256 _proposalIndex, address[] memory tos, uint256[] memory values, bytes[] memory data, Enum.Operation[] memory operations ) external { for (uint256 i = 0; i < tos.length; i++) { executeProposalTx(_proposalIndex, tos[i], values[i], data[i], operations[i]); } } /* VIEW FUNCTIONS */ /** * @dev Returns state of proposal * @param _proposalIndex Index of proposal */ function getProposalState(uint256 _proposalIndex) public view returns (ProposalState) { ProposalExecution storage proposalExecution = proposalIndexToProposalExecution[_proposalIndex]; if (proposalExecution.txHashes.length == 0) { return ProposalState.NotReceived; } else if (proposalExecution.cancelled) { return ProposalState.Cancelled; } else if (proposalExecution.executionCounter == 0) { return ProposalState.Received; } else if (proposalExecution.txHashes.length == proposalExecution.executionCounter) { return ProposalState.Executed; } else { return ProposalState.Executing; } } /** * @dev Gets number of transactions in a proposal * @param _proposalIndex Index of proposal * @return numTx Number of transactions in the proposal */ function getNumOfTxInProposal(uint256 _proposalIndex) public view returns (uint256 numTx) { require(_proposalIndex < proposalIndex, 'Invalid Proposal Index'); return proposalIndexToProposalExecution[_proposalIndex].txHashes.length; } /** * @dev Gets hash of transaction in a proposal * @param _proposalIndex Index of proposal * @param txIndex Index of transaction in proposal * @param txHash Transaction Hash */ function getTxHash(uint256 _proposalIndex, uint256 txIndex) public view returns (bytes32 txHash) { require(_proposalIndex < proposalIndex, 'Invalid Proposal Index'); require(txIndex < proposalIndexToProposalExecution[_proposalIndex].txHashes.length); return proposalIndexToProposalExecution[_proposalIndex].txHashes[txIndex]; } /** * @dev Gets whether transaction has been executed * @param _proposalIndex Index of proposal * @param txIndex Index of transaction in proposal * @param isExecuted Is transaction executed */ function isTxExecuted(uint256 _proposalIndex, uint256 txIndex) public view returns (bool isExecuted) { require(_proposalIndex < proposalIndex, 'Invalid Proposal Index'); require(txIndex < proposalIndexToProposalExecution[_proposalIndex].txHashes.length); return proposalIndexToProposalExecution[_proposalIndex].executionCounter > txIndex; } /** * @dev Generates the data for the module transaction hash (required for signing) * @param to the contract to be called by the avatar * @param value ether value to pass with the call * @param data the data to be executed from the call * @param operation Call or DelegateCall indicator * @return txHashData Transaction hash data */ function generateTransactionHashData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 nonce ) public view returns (bytes memory txHashData) { uint256 chainId = block.chainid; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, chainId, this)); bytes32 transactionHash = keccak256( abi.encode(TRANSACTION_TYPEHASH, to, value, keccak256(data), operation, nonce) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, transactionHash); } /** * @dev Generates transaction hash * @param to the contract to be called by the avatar * @param value ether value to pass with the call * @param data the data to be executed from the call * @param operation Call or DelegateCall indicator * @return txHash Transaction hash */ function getTransactionHash( address to, uint256 value, bytes memory data, Enum.Operation operation ) public view returns (bytes32 txHash) { return keccak256(generateTransactionHashData(to, value, data, operation, 0)); } }
Updates the list of accepted spaces on l2. Only callable by the `owner`. toAdd List of addresses to add to the whitelist. toRemove List of addressess to remove from the whitelist./ Add the requested entries Remove the requested entries
function editWhitelist(uint256[] memory toAdd, uint256[] calldata toRemove) external onlyOwner { for (uint256 i = 0; i < toAdd.length; i++) { whitelistedSpaces[toAdd[i]] = true; } for (uint256 i = 0; i < toRemove.length; i++) { whitelistedSpaces[toRemove[i]] = false; } }
5,474,498
./full_match/1/0xbc11DDfBC71a1D91f34ffE4301aD772EAFF3119b/sources/artrix/bid.sol
update the Platform Address
function updatePlatformAddress(address newPlatformAddress) public onlyOwner() { require(newPlatformAddress != address(0)); platformAddress = newPlatformAddress; emit PlatformAddressUpdated(newPlatformAddress); }
4,874,524
pragma solidity ^0.5.0; import "../GyanCoin.sol"; import "../KarmaCoin.sol"; import "../ScholarshipContract.sol"; import "../ownership/PbOwnable.sol"; import "../ownership/rbac/RBAC.sol"; contract BaseQuestion is PbOwnable, RBAC { using SafeMath for uint256; GyanCoin public gyanCoin; KarmaCoin public karmaCoin; ScholarshipContract public scholarshipContract; struct Question { bytes32 hash; bytes32 communityId; address owner; uint256 gyan; uint256 timestamp; bool open; mapping(bytes32 => Answer) answers; bytes32[] answerIndex; bytes32[] topics; } struct Answer { address owner; bytes32 hash; uint256 timestamp; bool status; bool flag; } mapping(bytes32 => Question) questions; event QuestionCreate(bytes32 _id, bytes32 _communityId, address _owner, bytes32 _hash, uint256 _gyan, bytes32[] _topics, uint256 _timestamp, address _pbNode); event QuestionAddAnswer(bytes32 _id, bytes32 _questionId, address _owner, bytes32 _hash, uint256 _timestamp, address pbNode); event QuestionAcceptAnswer(bytes32 _id, bytes32 _questionId, address pbNode); event QuestionClose(bytes32 _id, address pbNode); event QuestionFlagAnswer(bytes32 _id, bytes32 _questionId, address pbNode); event QuestionUnFlagAnswer(bytes32 _id, bytes32 _questionId, address pbNode); constructor( GyanCoin _gyan, KarmaCoin _karma, ScholarshipContract _scholarship ) public { require(_gyan != GyanCoin(0)); require(_karma != KarmaCoin(0)); require(_scholarship != ScholarshipContract(0)); gyanCoin = _gyan; karmaCoin = _karma; scholarshipContract = _scholarship; } function create(bytes32 _id, bytes32 _communityId, address _owner, bytes32 _scholarshipId, bytes32 _hash, uint256 _gyan, bytes32[] memory _topics) public onlyRole(ROLE_PARTNER) returns (bool) { require(_id[0] != 0); require(questions[_id].timestamp == 0); require(_communityId[0] != 0); require(_owner != address(0)); require(_hash[0] != 0); require(_gyan > 0); require(_topics.length > 0); require(_gyan <= gyanCoin.fixedBalanceOf(_owner) || _gyan == 1); // check if enough gyan balance questions[_id].communityId = _communityId; questions[_id].owner = _owner; questions[_id].hash = _hash; questions[_id].gyan = _gyan; questions[_id].topics = _topics; questions[_id].timestamp = now; questions[_id].open = true; if (_scholarshipId == 'NA') { require(getKarmaToBurn(_gyan) <= karmaCoin.balanceOf(_owner)); // check if enough karma balance // Burn karma from peer wallet karmaCoin.burnFrom(_owner, getKarmaToBurn(_gyan)); } else { require(scholarshipContract.getTimestamp(_scholarshipId) != 0); require(scholarshipContract.getType(_scholarshipId) == 0x7075626c69630000000000000000000000000000000000000000000000000000); // Check if scholarship is public require(scholarshipContract.getParticipant(_scholarshipId, _owner) != 0); require(karmaCoin.balanceOf(scholarshipContract.getWalletAddress(_scholarshipId)) >= getKarmaToBurn(_gyan)); // check if this scholarship has enough karma balance // Burn karma from scholarship wallet karmaCoin.burnFrom(scholarshipContract.getWalletAddress(_scholarshipId), getKarmaToBurn(_gyan)); } emit QuestionCreate(_id, _communityId, _owner, _hash, _gyan, _topics, now, msg.sender); return true; } function addAnswer(bytes32 _id, bytes32 _questionId, address _owner, bytes32 _hash) public onlyRole(ROLE_PARTNER) returns (bool) { require(_id[0] != 0); require(questions[_questionId].timestamp != 0); // Question exists require(questions[_questionId].answers[_id].timestamp == 0); // Answer does not exist require(_owner != address(0)); require(questions[_questionId].open == true); require(_hash[0] != 0); questions[_questionId].answers[_id].owner = _owner; questions[_questionId].answers[_id].hash = _hash; questions[_questionId].answers[_id].timestamp = now; questions[_questionId].answerIndex.push(_id); emit QuestionAddAnswer(_id, _questionId, _owner, _hash, now, msg.sender); return true; } function acceptAnswer(bytes32 _id, bytes32 _questionId) public onlyRole(ROLE_PARTNER) returns (bool) { require(_id[0] != 0); require(questions[_questionId].timestamp != 0); // Question exists require(questions[_questionId].answers[_id].timestamp != 0); // Answer exists require(questions[_questionId].answers[_id].status == false); require(questions[_questionId].answers[_id].flag == false); questions[_questionId].answers[_id].status = true; questions[_questionId].open = false; // Add gyan to answerer gyanCoin.mintFor(questions[_questionId].answers[_id].owner, questions[_questionId].gyan); // Add gyan to questioner gyanCoin.mintFor(questions[_questionId].owner, questions[_questionId].gyan); emit QuestionAcceptAnswer(_id, _questionId, msg.sender); return true; } function flagAnswer(bytes32 _id, bytes32 _questionId) public onlyRole(ROLE_PARTNER) returns (bool) { require(_id[0] != 0); require(questions[_questionId].timestamp != 0); // Question exists require(questions[_questionId].answers[_id].timestamp != 0); // Answer exists require(questions[_questionId].answers[_id].flag == false); require(questions[_questionId].open == true); // Question is open questions[_questionId].answers[_id].flag = true; emit QuestionFlagAnswer(_id, _questionId, msg.sender); return true; } function unFlagAnswer(bytes32 _id, bytes32 _questionId) public onlyRole(ROLE_PARTNER) returns (bool) { require(_id[0] != 0); require(questions[_questionId].timestamp != 0); // Question exists require(questions[_questionId].answers[_id].timestamp != 0); // Answer exists require(questions[_questionId].answers[_id].flag == true); require(questions[_questionId].open == true); // Question is open questions[_questionId].answers[_id].flag = false; emit QuestionUnFlagAnswer(_id, _questionId, msg.sender); return true; } function close(bytes32 _id) public onlyRole(ROLE_PARTNER) returns (bool) { require(_id[0] != 0); require(questions[_id].timestamp != 0); // Question exists require(questions[_id].open == true); require(now >= questions[_id].timestamp + 1 days); // Its been more than 24 hours since question was asked if (questions[_id].answerIndex.length > 0) { uint256 gyanPerAnswer = questions[_id].gyan.div(questions[_id].answerIndex.length); for(uint i = 0; i < questions[_id].answerIndex.length; i++) { if (questions[_id].answers[questions[_id].answerIndex[i]].flag != true) { // Add gyan to answerer gyanCoin.mintFor(questions[_id].answers[questions[_id].answerIndex[i]].owner, gyanPerAnswer); // Add gyan to questioner gyanCoin.mintFor(questions[_id].owner, gyanPerAnswer); } } questions[_id].open = false; } else { questions[_id].open = false; } emit QuestionClose(_id, msg.sender); return true; } function getQuestion(bytes32 _id) public view returns (bytes32, address, bytes32, uint256, bytes32[] memory, uint256) { // Solidity does not yet support returning structs to web3 return (questions[_id].communityId, questions[_id].owner, questions[_id].hash, questions[_id].gyan, questions[_id].topics, questions[_id].timestamp); } function getAnswers(bytes32 _id) public view returns (bytes32[] memory) { // Solidity does not yet support returning structs to web3 return questions[_id].answerIndex; } // Pure functions function getKarmaToBurn(uint256 _gyan) public view returns (uint256) { //TODO : put logic here to dynamically calculate Karma value based on gyan uint256 dailyKarmaMint = (karmaCoin.totalSupply().mul(5).div(100)).div(365); uint256 dailyGyanEarn = gyanCoin.yesterdayMint(); //uint256 dailyGyanEarn = 1000; return _gyan.mul(dailyKarmaMint.div(dailyGyanEarn)); } }
Add gyan to answerer Add gyan to questioner
function acceptAnswer(bytes32 _id, bytes32 _questionId) public onlyRole(ROLE_PARTNER) returns (bool) { require(_id[0] != 0); require(questions[_questionId].answers[_id].status == false); require(questions[_questionId].answers[_id].flag == false); questions[_questionId].answers[_id].status = true; questions[_questionId].open = false; gyanCoin.mintFor(questions[_questionId].answers[_id].owner, questions[_questionId].gyan); gyanCoin.mintFor(questions[_questionId].owner, questions[_questionId].gyan); emit QuestionAcceptAnswer(_id, _questionId, msg.sender); return true; }
6,435,551
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.4; library EthAddressLib { /** * @dev returns the address used within the protocol to identify ETH * @return the address assigned to ETH */ function ethAddress() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } 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; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a <= b ? a : b; } function abs(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return b - a; } return a - b; } } contract Exponential { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; using SafeMath for uint256; function getExp(uint256 num, uint256 denom) public pure returns (uint256 rational) { rational = num.mul(expScale).div(denom); } function getDiv(uint256 num, uint256 denom) public pure returns (uint256 rational) { rational = num.mul(expScale).div(denom); } function addExp(uint256 a, uint256 b) public pure returns (uint256 result) { result = a.add(b); } function subExp(uint256 a, uint256 b) public pure returns (uint256 result) { result = a.sub(b); } function mulExp(uint256 a, uint256 b) public pure returns (uint256) { uint256 doubleScaledProduct = a.mul(b); uint256 doubleScaledProductWithHalfScale = halfExpScale.add( doubleScaledProduct ); return doubleScaledProductWithHalfScale.div(expScale); } function divExp(uint256 a, uint256 b) public pure returns (uint256) { return getDiv(a, b); } function mulExp3( uint256 a, uint256 b, uint256 c ) public pure returns (uint256) { return mulExp(mulExp(a, b), c); } function mulScalar(uint256 a, uint256 scalar) public pure returns (uint256 scaled) { scaled = a.mul(scalar); } function mulScalarTruncate(uint256 a, uint256 scalar) public pure returns (uint256) { uint256 product = mulScalar(a, scalar); return truncate(product); } function mulScalarTruncateAddUInt( uint256 a, uint256 scalar, uint256 addend ) public pure returns (uint256) { uint256 product = mulScalar(a, scalar); return truncate(product).add(addend); } function divScalarByExpTruncate(uint256 scalar, uint256 divisor) public pure returns (uint256) { uint256 fraction = divScalarByExp(scalar, divisor); return truncate(fraction); } function divScalarByExp(uint256 scalar, uint256 divisor) public pure returns (uint256) { uint256 numerator = expScale.mul(scalar); return getExp(numerator, divisor); } function divScalar(uint256 a, uint256 scalar) public pure returns (uint256) { return a.div(scalar); } function truncate(uint256 exp) public pure returns (uint256) { return exp.div(expScale); } } 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. */ function decimals() external view returns (uint8); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface IFToken is IERC20 { function mint(address user, uint256 amount) external returns (bytes memory); function borrow(address borrower, uint256 borrowAmount) external returns (bytes memory); function withdraw( address payable withdrawer, uint256 withdrawTokensIn, uint256 withdrawAmountIn ) external returns (uint256, bytes memory); function underlying() external view returns (address); function accrueInterest() external; function getAccountState(address account) external view returns ( uint256, uint256, uint256 ); function MonitorEventCallback( address who, bytes32 funcName, bytes calldata payload ) external; //用户存借取还操作后的兑换率 function exchangeRateCurrent() external view returns (uint256 exchangeRate); function repay(address borrower, uint256 repayAmount) external returns (uint256, bytes memory); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateStored() external view returns (uint256 exchangeRate); function liquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address fTokenCollateral ) external returns (bytes memory); function borrowBalanceCurrent(address account) external returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external; function _addReservesFresh(uint256 addAmount) external; function cancellingOut(address striker) external returns (bool strikeOk, bytes memory strikeLog); function APR() external view returns (uint256); function APY() external view returns (uint256); function calcBalanceOfUnderlying(address owner) external view returns (uint256); function borrowSafeRatio() external view returns (uint256); function tokenCash(address token, address account) external view returns (uint256); function getBorrowRate() external view returns (uint256); function addTotalCash(uint256 _addAmount) external; function subTotalCash(uint256 _subAmount) external; function totalCash() external view returns (uint256); function totalReserves() external view returns (uint256); function totalBorrows() external view returns (uint256); } interface IOracle { function get(address token) external view returns (uint256, bool); } 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); } } } } 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" ); } } } enum RewardType { DefaultType, Deposit, Borrow, Withdraw, Repay, Liquidation, TokenIn, //入金,为还款和存款的组合 TokenOut //出金, 为取款和借款的组合 } interface IBank { function MonitorEventCallback(bytes32 funcName, bytes calldata payload) external; function deposit(address token, uint256 amount) external payable; function borrow(address token, uint256 amount) external; function withdraw(address underlying, uint256 withdrawTokens) external; function withdrawUnderlying(address underlying, uint256 amount) external; function repay(address token, uint256 amount) external payable; function liquidateBorrow( address borrower, address underlyingBorrow, address underlyingCollateral, uint256 repayAmount ) external payable; function tokenIn(address token, uint256 amountIn) external payable; function tokenOut(address token, uint256 amountOut) external; function cancellingOut(address token) external; function paused() external view returns (bool); } interface IRewardPool { function theForceToken() external view returns (address); function bankController() external view returns (address); function admin() external view returns (address); function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function withdraw() external; function setTheForceToken(address _theForceToken) external; function setBankController(address _bankController) external; function reward(address who, uint256 amount) external; } 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; } contract BankController is Exponential, Initializable { using SafeERC20 for IERC20; using SafeMath for uint256; struct Market { // 原生币种对应的 fToken 地址 address fTokenAddress; // 币种是否可用 bool isValid; // 该币种所拥有的质押能力 uint256 collateralAbility; // 市场所参与的用户 mapping(address => bool) accountsIn; // 该币种的清算奖励 uint256 liquidationIncentive; } // 原生币种地址 => 币种信息 mapping(address => Market) public markets; address public bankEntryAddress; // bank主合约入口地址 address public theForceToken; // 奖励的FOR token地址 //返利百分比,根据用户存,借,取,还花费的gas返还对应价值比例的奖励token, 奖励FOR数量 = ETH价值 * rewardFactor / price(for), 1e18 scale mapping(uint256 => uint256) public rewardFactors; // RewardType ==> rewardFactor (1e18 scale); // 用户地址 =》 币种地址(用户参与的币种) mapping(address => IFToken[]) public accountAssets; IFToken[] public allMarkets; address[] public allUnderlyingMarkets; IOracle public oracle; address public mulsig; //FIXME: 统一权限管理 modifier auth { require( msg.sender == admin || msg.sender == bankEntryAddress, "msg.sender need admin or bank" ); _; } function setBankEntryAddress(address _newBank) external auth { bankEntryAddress = _newBank; } function setTheForceToken(address _theForceToken) external auth { theForceToken = _theForceToken; } function setRewardFactorByType(uint256 rewaradType, uint256 factor) external auth { rewardFactors[rewaradType] = factor; } function marketsContains(address fToken) public view returns (bool) { uint256 len = allMarkets.length; for (uint256 i = 0; i < len; ++i) { if (address(allMarkets[i]) == fToken) { return true; } } return false; } uint256 public closeFactor; address public admin; address public proposedAdmin; // 将FOR奖励池单独放到另外一个合约中 address public rewardPool; uint256 public transferEthGasCost; /// @notice Emitted when borrow cap for a token is changed event NewBorrowCap(address indexed token, uint newBorrowCap); /// @notice Emitted when supply cap for a token is changed event NewSupplyCap(address indexed token, uint newSupplyCap); // @notice Borrow caps enforced by borrowAllowed for each token address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; // @notice Supply caps enforced by mintAllowed for each token address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint) public supplyCaps; /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param tokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(address[] calldata tokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin, "only admin can set borrow caps"); uint numMarkets = tokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[tokens[i]] = newBorrowCaps[i]; emit NewBorrowCap(tokens[i], newBorrowCaps[i]); } } /** * @notice Set the given supply caps for the given cToken markets. supplying that brings total supplys to or above supply cap will revert. * @dev Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. * @param tokens The addresses of the markets (tokens) to change the supply caps for * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying. */ function _setMarketSupplyCaps(address[] calldata tokens, uint[] calldata newSupplyCaps) external { require(msg.sender == admin, "only admin can set supply caps"); uint numMarkets = tokens.length; uint numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { supplyCaps[tokens[i]] = newSupplyCaps[i]; emit NewSupplyCap(tokens[i], newSupplyCaps[i]); } } // _setMarketBorrowSupplyCaps = _setMarketBorrowCaps + _setMarketSupplyCaps function _setMarketBorrowSupplyCaps(address[] calldata tokens, uint[] calldata newBorrowCaps, uint[] calldata newSupplyCaps) external { require(msg.sender == admin, "only admin can set borrow/supply caps"); uint numMarkets = tokens.length; uint numBorrowCaps = newBorrowCaps.length; uint numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps && numMarkets == numSupplyCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[tokens[i]] = newBorrowCaps[i]; supplyCaps[tokens[i]] = newSupplyCaps[i]; emit NewBorrowCap(tokens[i], newBorrowCaps[i]); emit NewSupplyCap(tokens[i], newSupplyCaps[i]); } } function initialize(address _mulsig) public initializer { admin = msg.sender; mulsig = _mulsig; transferEthGasCost = 5000; } modifier onlyMulSig { require(msg.sender == mulsig, "require admin"); _; } modifier onlyAdmin { require(msg.sender == admin, "require admin"); _; } modifier onlyFToken(address fToken) { require(marketsContains(fToken), "only supported fToken"); _; } event AddTokenToMarket(address underlying, address fToken); function proposeNewAdmin(address admin_) external onlyMulSig { proposedAdmin = admin_; } function claimAdministration() external { require(msg.sender == proposedAdmin, "Not proposed admin."); admin = proposedAdmin; proposedAdmin = address(0); } // 获取原生 token 对应的 fToken 地址 function getFTokeAddress(address underlying) public view returns (address) { return markets[underlying].fTokenAddress; } /** * @notice Returns the assets an account has entered 返回该账户已经参与的币种 * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (IFToken[] memory) { IFToken[] memory assetsIn = accountAssets[account]; return assetsIn; } function checkAccountsIn(address account, IFToken fToken) external view returns (bool) { return markets[IFToken(address(fToken)).underlying()].accountsIn[account]; } function userEnterMarket(IFToken fToken, address borrower) internal { Market storage marketToJoin = markets[fToken.underlying()]; require(marketToJoin.isValid, "Market not valid"); if (marketToJoin.accountsIn[borrower]) { return; } marketToJoin.accountsIn[borrower] = true; accountAssets[borrower].push(fToken); } function transferCheck( address fToken, address src, address dst, uint256 transferTokens ) external onlyFToken(msg.sender) { withdrawCheck(fToken, src, transferTokens); userEnterMarket(IFToken(fToken), dst); } function withdrawCheck( address fToken, address withdrawer, uint256 withdrawTokens ) public view returns (uint256) { require( markets[IFToken(fToken).underlying()].isValid, "Market not valid" ); (uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity( withdrawer, IFToken(fToken), withdrawTokens, 0 ); require(sumCollaterals >= sumBorrows, "Cannot withdraw tokens"); } // 接收转账 function transferIn( address account, address underlying, uint256 amount ) public payable { if (underlying != EthAddressLib.ethAddress()) { require(msg.value == 0, "ERC20 do not accecpt ETH."); uint256 balanceBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransferFrom(account, address(this), amount); uint256 balanceAfter = IERC20(underlying).balanceOf(address(this)); require( balanceAfter - balanceBefore == amount, "TransferIn amount not valid" ); // erc 20 => transferFrom } else { // 接收 eth 转账,已经通过 payable 转入 require(msg.value >= amount, "Eth value is not enough"); if (msg.value > amount) { //send back excess ETH uint256 excessAmount = msg.value.sub(amount); //solium-disable-next-line (bool result, ) = account.call{ value: excessAmount, gas: transferEthGasCost }(""); require(result, "Transfer of ETH failed"); } } } // 向用户转账 function transferToUser( address underlying, address payable account, uint256 amount ) external onlyFToken(msg.sender) { require( markets[IFToken(msg.sender).underlying()].isValid, "TransferToUser not allowed" ); transferToUserInternal(underlying, account, amount); } function transferToUserInternal( address underlying, address payable account, uint256 amount ) internal { if (underlying != EthAddressLib.ethAddress()) { // erc 20 // ERC20(token).safeTransfer(user, _amount); IERC20(underlying).safeTransfer(account, amount); } else { (bool result, ) = account.call{ value: amount, gas: transferEthGasCost }(""); require(result, "Transfer of ETH failed"); } } //1:1返还 function calcRewardAmount( uint256 gasSpend, uint256 gasPrice, address _for ) public view returns (uint256) { (uint256 _ethPrice, bool _ethValid) = fetchAssetPrice( EthAddressLib.ethAddress() ); (uint256 _forPrice, bool _forValid) = fetchAssetPrice(_for); if (!_ethValid || !_forValid || IERC20(_for).decimals() != 18) { return 0; } return gasSpend.mul(gasPrice).mul(_ethPrice).div(_forPrice); } //0.5 * 1e18, 表返还0.5ETH价值的FOR //1.5 * 1e18, 表返还1.5倍ETH价值的FOR function calcRewardAmountByFactor( uint256 gasSpend, uint256 gasPrice, address _for, uint256 factor ) public view returns (uint256) { return calcRewardAmount(gasSpend, gasPrice, _for).mul(factor).div(1e18); } function setRewardPool(address _rewardPool) external onlyAdmin { rewardPool = _rewardPool; } function setTransferEthGasCost(uint256 _transferEthGasCost) external onlyAdmin { transferEthGasCost = _transferEthGasCost; } function rewardForByType( address account, uint256 gasSpend, uint256 gasPrice, uint256 rewardType ) external auth { uint256 amount = calcRewardAmountByFactor( gasSpend, gasPrice, theForceToken, rewardFactors[rewardType] ); amount = SafeMath.min( amount, IERC20(theForceToken).balanceOf(rewardPool) ); if (amount > 0) { IRewardPool(rewardPool).reward(account, amount); } } // 获取实际原生代币的余额 function getCashPrior(address underlying) public view returns (uint256) { IFToken fToken = IFToken(getFTokeAddress(underlying)); return fToken.totalCash(); } // 获取将要更新后的原生代币的余额(预判) function getCashAfter(address underlying, uint256 transferInAmount) external view returns (uint256) { return getCashPrior(underlying).add(transferInAmount); } function mintCheck(address underlying, address minter, uint256 amount) external { require( markets[IFToken(msg.sender).underlying()].isValid, "MintCheck fails" ); require(markets[underlying].isValid, "Market not valid"); uint supplyCap = supplyCaps[underlying]; // Supply cap of 0 corresponds to unlimited supplying if (supplyCap != 0) { uint totalSupply = IFToken(msg.sender).totalSupply(); uint _exchangeRate = IFToken(msg.sender).exchangeRateStored(); // 兑换率乘总发行ftoken数量,得到原生token数量 uint256 totalUnderlyingSupply = mulScalarTruncate(_exchangeRate, totalSupply); uint nextTotalUnderlyingSupply = totalUnderlyingSupply.add(amount); require(nextTotalUnderlyingSupply < supplyCap, "market supply cap reached"); } if (!markets[underlying].accountsIn[minter]) { userEnterMarket(IFToken(getFTokeAddress(underlying)), minter); } } function borrowCheck( address account, address underlying, address fToken, uint256 borrowAmount ) external { address underlying = IFToken(msg.sender).underlying(); require( markets[underlying].isValid, "BorrowCheck fails" ); uint borrowCap = borrowCaps[underlying]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = IFToken(msg.sender).totalBorrows(); uint nextTotalBorrows = totalBorrows.add(borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } require(markets[underlying].isValid, "Market not valid"); (, bool valid) = fetchAssetPrice(underlying); require(valid, "Price is not valid"); if (!markets[underlying].accountsIn[account]) { userEnterMarket(IFToken(getFTokeAddress(underlying)), account); } // 校验用户流动性,liquidity (uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity( account, IFToken(fToken), 0, borrowAmount ); require(sumBorrows > 0, "borrow value too low"); require(sumCollaterals >= sumBorrows, "insufficient liquidity"); } function repayCheck(address underlying) external view { require(markets[underlying].isValid, "Market not valid"); } // 获取用户总体的存款和借款情况 function getTotalDepositAndBorrow(address account) public view returns (uint256, uint256) { return getUserLiquidity(account, IFToken(0), 0, 0); } // 获取账户流动性 function getAccountLiquidity(address account) public view returns (uint256 liquidity, uint256 shortfall) { (uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity( account, IFToken(0), 0, 0 ); // These are safe, as the underflow condition is checked first if (sumCollaterals > sumBorrows) { return (sumCollaterals - sumBorrows, 0); } else { return (0, sumBorrows - sumCollaterals); } } // 不包含FToken的流动性 function getAccountLiquidityExcludeDeposit(address account, address token) public view returns (uint256, uint256) { IFToken fToken = IFToken(getFTokeAddress(token)); (uint256 sumCollaterals, uint256 sumBorrows) = getUserLiquidity( account, fToken, fToken.balanceOf(account), //用户的fToken数量 0 ); // These are safe, as the underflow condition is checked first if (sumCollaterals > sumBorrows) { return (sumCollaterals - sumBorrows, 0); } else { return (0, sumBorrows - sumCollaterals); } } // Get price of oracle function fetchAssetPrice(address token) public view returns (uint256, bool) { require(address(oracle) != address(0), "oracle not set"); return oracle.get(token); } function setOracle(address _oracle) external onlyAdmin { oracle = IOracle(_oracle); } function _supportMarket( IFToken fToken, uint256 _collateralAbility, uint256 _liquidationIncentive ) public onlyAdmin { address underlying = fToken.underlying(); require(!markets[underlying].isValid, "martket existed"); markets[underlying] = Market({ isValid: true, collateralAbility: _collateralAbility, fTokenAddress: address(fToken), liquidationIncentive: _liquidationIncentive }); addTokenToMarket(underlying, address(fToken)); } function addTokenToMarket(address underlying, address fToken) internal { for (uint256 i = 0; i < allUnderlyingMarkets.length; i++) { require( allUnderlyingMarkets[i] != underlying, "token exists" ); require(allMarkets[i] != IFToken(fToken), "token exists"); } allMarkets.push(IFToken(fToken)); allUnderlyingMarkets.push(underlying); emit AddTokenToMarket(underlying, fToken); } function _setCollateralAbility( address underlying, uint256 newCollateralAbility ) external onlyAdmin { require(markets[underlying].isValid, "Market not valid"); Market storage market = markets[underlying]; market.collateralAbility = newCollateralAbility; } function setCloseFactor(uint256 _closeFactor) external onlyAdmin { closeFactor = _closeFactor; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() external view returns (IFToken[] memory) { return allMarkets; } function seizeCheck(address cTokenCollateral, address cTokenBorrowed) external view onlyFToken(msg.sender) { require( markets[IFToken(cTokenCollateral).underlying()].isValid && markets[IFToken(cTokenBorrowed).underlying()].isValid, "Seize market not valid" ); } struct LiquidityLocals { uint256 sumCollateral; uint256 sumBorrows; uint256 fTokenBalance; uint256 borrowBalance; uint256 exchangeRate; uint256 oraclePrice; uint256 collateralAbility; uint256 collateral; } function getUserLiquidity( address account, IFToken fTokenNow, uint256 withdrawTokens, uint256 borrowAmount ) public view returns (uint256, uint256) { // 用户参与的每个币种 IFToken[] memory assets = accountAssets[account]; LiquidityLocals memory vars; // 对于每个币种 for (uint256 i = 0; i < assets.length; i++) { IFToken asset = assets[i]; // 获取 fToken 的余额和兑换率 (vars.fTokenBalance, vars.borrowBalance, vars.exchangeRate) = asset .getAccountState(account); // 该币种的质押率 vars.collateralAbility = markets[asset.underlying()] .collateralAbility; // 获取币种价格 (uint256 oraclePrice, bool valid) = fetchAssetPrice( asset.underlying() ); require(valid, "Price is not valid"); vars.oraclePrice = oraclePrice; uint256 fixUnit = calcExchangeUnit(address(asset)); uint256 exchangeRateFixed = mulScalar(vars.exchangeRate, fixUnit); vars.collateral = mulExp3( vars.collateralAbility, exchangeRateFixed, vars.oraclePrice ); vars.sumCollateral = mulScalarTruncateAddUInt( vars.collateral, vars.fTokenBalance, vars.sumCollateral ); vars.borrowBalance = vars.borrowBalance.mul(fixUnit); vars.sumBorrows = mulScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrows ); // 借款和取款的时候,将当前要操作的数量,直接计算在账户流动性里面 if (asset == fTokenNow) { // 取款 vars.sumBorrows = mulScalarTruncateAddUInt( vars.collateral, withdrawTokens, vars.sumBorrows ); borrowAmount = borrowAmount.mul(fixUnit); // 借款 vars.sumBorrows = mulScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrows ); } } return (vars.sumCollateral, vars.sumBorrows); } //不包含某一token的流动性 function getUserLiquidityExcludeToken( address account, IFToken excludeToken, IFToken fTokenNow, uint256 withdrawTokens, uint256 borrowAmount ) external view returns (uint256, uint256) { // 用户参与的每个币种 IFToken[] memory assets = accountAssets[account]; LiquidityLocals memory vars; // 对于每个币种 for (uint256 i = 0; i < assets.length; i++) { IFToken asset = assets[i]; //不包含token if (address(asset) == address(excludeToken)) { continue; } // 获取 fToken 的余额和兑换率 (vars.fTokenBalance, vars.borrowBalance, vars.exchangeRate) = asset .getAccountState(account); // 该币种的质押率 vars.collateralAbility = markets[asset.underlying()] .collateralAbility; // 获取币种价格 (uint256 oraclePrice, bool valid) = fetchAssetPrice( asset.underlying() ); require(valid, "Price is not valid"); vars.oraclePrice = oraclePrice; uint256 fixUnit = calcExchangeUnit(address(asset)); uint256 exchangeRateFixed = mulScalar( vars.exchangeRate, fixUnit ); vars.collateral = mulExp3( vars.collateralAbility, exchangeRateFixed, vars.oraclePrice ); vars.sumCollateral = mulScalarTruncateAddUInt( vars.collateral, vars.fTokenBalance, vars.sumCollateral ); vars.sumBorrows = mulScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrows ); // 借款和取款的时候,将当前要操作的数量,直接计算在账户流动性里面 if (asset == fTokenNow) { // 取款 vars.sumBorrows = mulScalarTruncateAddUInt( vars.collateral, withdrawTokens, vars.sumBorrows ); borrowAmount = borrowAmount.mul(fixUnit); // 借款 vars.sumBorrows = mulScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrows ); } } return (vars.sumCollateral, vars.sumBorrows); } function tokenDecimals(address token) public view returns (uint256) { return token == EthAddressLib.ethAddress() ? 18 : uint256(IERC20(token).decimals()); } //计算user的取款指定token的最大数量 function calcMaxWithdrawAmount(address user, address token) public view returns (uint256) { (uint256 depoistValue, uint256 borrowValue) = getTotalDepositAndBorrow( user ); if (depoistValue <= borrowValue) { return 0; } uint256 netValue = subExp(depoistValue, borrowValue); // redeemValue = netValue / collateralAblility; uint256 redeemValue = divExp( netValue, markets[token].collateralAbility ); (uint256 oraclePrice, bool valid) = fetchAssetPrice(token); require(valid, "Price is not valid"); uint fixUnit = 10 ** SafeMath.abs(18, tokenDecimals(token)); uint256 redeemAmount = divExp(redeemValue, oraclePrice).div(fixUnit); IFToken fToken = IFToken(getFTokeAddress(token)); redeemAmount = SafeMath.min( redeemAmount, fToken.calcBalanceOfUnderlying(user) ); return redeemAmount; } function calcMaxBorrowAmount(address user, address token) public view returns (uint256) { ( uint256 depoistValue, uint256 borrowValue ) = getAccountLiquidityExcludeDeposit(user, token); if (depoistValue <= borrowValue) { return 0; } uint256 netValue = subExp(depoistValue, borrowValue); (uint256 oraclePrice, bool valid) = fetchAssetPrice(token); require(valid, "Price is not valid"); uint fixUnit = 10 ** SafeMath.abs(18, tokenDecimals(token)); uint256 borrowAmount = divExp(netValue, oraclePrice).div(fixUnit); return borrowAmount; } function calcMaxBorrowAmountWithRatio(address user, address token) public view returns (uint256) { IFToken fToken = IFToken(getFTokeAddress(token)); return SafeMath.mul(calcMaxBorrowAmount(user, token), 1e18).div(fToken.borrowSafeRatio()); } function calcMaxCashOutAmount(address user, address token) public view returns (uint256) { return addExp( calcMaxWithdrawAmount(user, token), calcMaxBorrowAmountWithRatio(user, token) ); } function isFTokenValid(address fToken) external view returns (bool) { return markets[IFToken(fToken).underlying()].isValid; } function liquidateBorrowCheck( address fTokenBorrowed, address fTokenCollateral, address borrower, address liquidator, uint256 repayAmount ) external onlyFToken(msg.sender) { (, uint256 shortfall) = getAccountLiquidity(borrower); require(shortfall != 0, "Insufficient shortfall"); userEnterMarket(IFToken(fTokenCollateral), liquidator); uint256 borrowBalance = IFToken(fTokenBorrowed).borrowBalanceStored( borrower ); uint256 maxClose = mulScalarTruncate(closeFactor, borrowBalance); require(repayAmount <= maxClose, "Too much repay"); } function calcExchangeUnit(address fToken) public view returns (uint256) { uint256 fTokenDecimals = uint256(IFToken(fToken).decimals()); uint256 underlyingDecimals = IFToken(fToken).underlying() == EthAddressLib.ethAddress() ? 18 : uint256(IERC20(IFToken(fToken).underlying()).decimals()); return 10**SafeMath.abs(fTokenDecimals, underlyingDecimals); } function liquidateTokens( address fTokenBorrowed, address fTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256) { (uint256 borrowPrice, bool borrowValid) = fetchAssetPrice( IFToken(fTokenBorrowed).underlying() ); (uint256 collateralPrice, bool collateralValid) = fetchAssetPrice( IFToken(fTokenCollateral).underlying() ); require(borrowValid && collateralValid, "Price not valid"); /* * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint256 exchangeRate = IFToken(fTokenCollateral).exchangeRateStored(); uint256 fixCollateralUnit = calcExchangeUnit(fTokenCollateral); uint256 fixBorrowlUnit = calcExchangeUnit(fTokenBorrowed); uint256 numerator = mulExp( markets[IFToken(fTokenCollateral).underlying()] .liquidationIncentive, borrowPrice ); exchangeRate = exchangeRate.mul(fixCollateralUnit); actualRepayAmount = actualRepayAmount.mul(fixBorrowlUnit); uint256 denominator = mulExp(collateralPrice, exchangeRate); uint256 seizeTokens = mulScalarTruncate( divExp(numerator, denominator), actualRepayAmount ); return seizeTokens; } function _setLiquidationIncentive( address underlying, uint256 _liquidationIncentive ) public onlyAdmin { markets[underlying].liquidationIncentive = _liquidationIncentive; } struct ReserveWithdrawalLogStruct { address token_address; uint256 reserve_withdrawed; uint256 cheque_token_value; uint256 loan_interest_rate; uint256 global_token_reserved; } function reduceReserves( address underlying, address payable account, uint256 reduceAmount ) public onlyMulSig { IFToken fToken = IFToken(getFTokeAddress(underlying)); fToken._reduceReserves(reduceAmount); transferToUserInternal(underlying, account, reduceAmount); fToken.subTotalCash(reduceAmount); ReserveWithdrawalLogStruct memory rds = ReserveWithdrawalLogStruct( underlying, reduceAmount, fToken.exchangeRateStored(), fToken.getBorrowRate(), fToken.tokenCash(underlying, address(this)) ); IBank(bankEntryAddress).MonitorEventCallback( "ReserveWithdrawal", abi.encode(rds) ); } function batchReduceReserves( address[] calldata underlyings, address payable account, uint256[] calldata reduceAmounts ) external onlyMulSig { require(underlyings.length == reduceAmounts.length, "length not match"); uint256 n = underlyings.length; for (uint256 i = 0; i < n; i++) { reduceReserves(underlyings[i], account, reduceAmounts[i]); } } function batchReduceAllReserves( address[] calldata underlyings, address payable account ) external onlyMulSig { uint256 n = underlyings.length; for (uint i = 0; i < n; i++) { IFToken fToken = IFToken(getFTokeAddress(underlyings[i])); uint256 amount = SafeMath.min(fToken.totalReserves(), fToken.tokenCash(underlyings[i], address(this))); if (amount > 0) { reduceReserves(underlyings[i], account, amount); } } } function batchReduceAllReserves( address payable account ) external onlyMulSig { uint256 n = allUnderlyingMarkets.length; for (uint i = 0; i < n; i++) { address underlying = allUnderlyingMarkets[i]; IFToken fToken = IFToken(getFTokeAddress(underlying)); uint256 amount = SafeMath.min(fToken.totalReserves(), fToken.tokenCash(underlying, address(this))); if (amount > 0) { reduceReserves(underlying, account, amount); } } } struct ReserveDepositLogStruct { address token_address; uint256 reserve_funded; uint256 cheque_token_value; uint256 loan_interest_rate; uint256 global_token_reserved; } function addReserves(address underlying, uint256 addAmount) external payable { IFToken fToken = IFToken(getFTokeAddress(underlying)); fToken._addReservesFresh(addAmount); transferIn(msg.sender, underlying, addAmount); fToken.addTotalCash(addAmount); ReserveDepositLogStruct memory rds = ReserveDepositLogStruct( underlying, addAmount, fToken.exchangeRateStored(), fToken.getBorrowRate(), fToken.tokenCash(underlying, address(this)) ); IBank(bankEntryAddress).MonitorEventCallback( "ReserveDeposit", abi.encode(rds) ); } }
Set the given supply caps for the given cToken markets. supplying that brings total supplys to or above supply cap will revert. Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. tokens The addresses of the markets (tokens) to change the supply caps for newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying./
function _setMarketSupplyCaps(address[] calldata tokens, uint[] calldata newSupplyCaps) external { require(msg.sender == admin, "only admin can set supply caps"); uint numMarkets = tokens.length; uint numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { supplyCaps[tokens[i]] = newSupplyCaps[i]; emit NewSupplyCap(tokens[i], newSupplyCaps[i]); } }
7,767,924
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/MerkleClaimer.sol
Returns Merkle Eligibilities/
function ReadEligibility ( uint ClaimIndex, address Wallet, uint[] calldata TokenIDs, bytes32[][] calldata Proofs ) public view returns (User memory) { return User ( ReadEligibilityMerkleClaim(ClaimIndex, Wallet, TokenIDs, Proofs), UserPurchasedAmount[ClaimIndex][Wallet] ); }
8,470,525
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(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 MUL487(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 DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(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 MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE513(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"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(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.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(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. // 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).ISCONTRACT107(), "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"); } } } 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract 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_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function LOG714(uint p0, bool p1, bool p2, bool p3) internal view {
14,087,769
./full_match/1/0x51e63665AC51D0313A042d89DEd26763936C0D12/sources/contracts/NeozenMythics.sol
Process minting _amount The amount to mint/
function _processMint(uint256 _amount) internal { address sender = _msgSenderERC721A(); addressToMinted[sender] += _amount; _mint(sender, _amount); }
8,329,495
// File: contracts/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: contracts/SafeMath.sol pragma solidity ^0.5.16; /** * @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: contracts/IERC20.sol pragma solidity 0.5.16; /** * @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: contracts/ReentrancyGuard.sol pragma solidity =0.5.16; contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } } // File: contracts/Ownable.sol pragma solidity =0.5.16; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { _owner = msg.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 msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Halt.sol pragma solidity =0.5.16; contract Halt is Ownable { bool private halted = false; modifier notHalted() { require(!halted,"This contract is halted"); _; } modifier isHalted() { require(halted,"This contract is not halted"); _; } /// @notice function Emergency situation that requires /// @notice contribution period to stop or not. function setHalt(bool halt) public onlyOwner { halted = halt; } } // File: contracts/whiteList.sol pragma solidity >=0.5.16; /** * SPDX-License-Identifier: GPL-3.0-or-later * FinNexus * Copyright (C) 2020 FinNexus Options Protocol */ /** * @dev Implementation of a whitelist which filters a eligible uint32. */ library whiteListUint32 { /** * @dev add uint32 into white list. * @param whiteList the storage whiteList. * @param temp input value */ function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{ if (!isEligibleUint32(whiteList,temp)){ whiteList.push(temp); } } /** * @dev remove uint32 from whitelist. */ function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible uint256. */ library whiteListUint256 { // add whiteList function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{ if (!isEligibleUint256(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible address. */ library whiteListAddress { // add whiteList function addWhiteListAddress(address[] storage whiteList,address temp) internal{ if (!isEligibleAddress(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } // File: contracts/Operator.sol pragma solidity =0.5.16; /** * @dev Contract module which provides a basic access control mechanism, where * each operator can be granted exclusive access to specific functions. * */ contract Operator is Ownable { mapping(uint256=>address) private _operators; /** * @dev modifier, Only indexed operator can be granted exclusive access to specific functions. * */ modifier onlyOperator(uint256 index) { require(_operators[index] == msg.sender,"Operator: caller is not the eligible Operator"); _; } /** * @dev modify indexed operator by owner. * */ function setOperator(uint256 index,address addAddress)public onlyOwner{ _operators[index] = addAddress; } function getOperator(uint256 index)public view returns (address) { return _operators[index]; } } // File: contracts/multiSignatureClient.sol pragma solidity =0.5.16; interface IMultiSignature{ function getValidSignature(bytes32 msghash,uint256 lastIndex) external view returns(uint256); } contract multiSignatureClient{ bytes32 private constant multiSignaturePositon = keccak256("org.Finnexus.multiSignature.storage"); constructor(address multiSignature) public { require(multiSignature != address(0),"multiSignatureClient : Multiple signature contract address is zero!"); saveValue(multiSignaturePositon,uint256(multiSignature)); } function getMultiSignatureAddress()public view returns (address){ return address(getValue(multiSignaturePositon)); } modifier validCall(){ checkMultiSignature(); _; } function checkMultiSignature() internal { uint256 value; assembly { value := callvalue() } bytes32 msgHash = keccak256(abi.encodePacked(msg.sender, address(this),value,msg.data)); address multiSign = getMultiSignatureAddress(); uint256 index = getValue(msgHash); uint256 newIndex = IMultiSignature(multiSign).getValidSignature(msgHash,index); require(newIndex > 0, "multiSignatureClient : This tx is not aprroved"); saveValue(msgHash,newIndex); } function saveValue(bytes32 position,uint256 value) internal { assembly { sstore(position, value) } } function getValue(bytes32 position) internal view returns (uint256 value) { assembly { value := sload(position) } } } // File: contracts/MinePoolData.sol pragma solidity =0.5.16; contract MinePoolData is multiSignatureClient,Operator,Halt,ReentrancyGuard { address public phx ; address payable public lp; // address public rewardDistribution; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public rewardRate; uint256 public rewardPerduration; //reward token number per duration uint256 public duration; mapping(address => uint256) public rewards; mapping(address => uint256) public userRewardPerTokenPaid; uint256 public periodFinish; uint256 public startTime; uint256 internal totalsupply; mapping(address => uint256) internal balances; uint256 public _phxFeeRatio ;//= 50;//5% uint256 public _htFeeAmount ;//= 1e16; address payable public _feeReciever; } // File: contracts/LPTokenWrapper.sol pragma solidity =0.5.16; contract LPTokenWrapper is MinePoolData { using SafeMath for uint256; function totalSupply() public view returns(uint256) { return totalsupply; } function balanceOf(address account) public view returns(uint256) { return balances[account]; } function stake(uint256 amount) internal { if(lp==address(0)) { require(msg.value>0,"stake input value is is 0"); amount = msg.value; address payable poolAddr = address(uint160(address(this))); address(poolAddr).transfer(amount); } else { require(amount > 0, "cannot stake 0"); uint256 preBalance = IERC20(lp).balanceOf(address(this)); IERC20(lp).transferFrom(msg.sender,address(this), amount); uint256 afterBalance = IERC20(lp).balanceOf(address(this)); require(afterBalance-preBalance==amount,"token stake transfer error!"); } totalsupply = totalsupply.add(amount); balances[msg.sender] = balances[msg.sender].add(amount); } function unstake (uint256 amount) internal { totalsupply = totalsupply.sub(amount); balances[msg.sender] = balances[msg.sender].sub(amount); if(lp==address(0)) { msg.sender.transfer(amount); } else { uint256 preBalance = IERC20(lp).balanceOf(address(this)); IERC20(lp).transfer(msg.sender, amount); uint256 afterBalance = IERC20(lp).balanceOf(address(this)); require(preBalance - afterBalance==amount,"token unstake transfer error!"); } } } // File: contracts/MinePoolDelegate.sol pragma solidity ^0.5.16; contract MinePool is LPTokenWrapper { event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event HisReward(address indexed user, uint256 indexed reward,uint256 indexed idx); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { require(now >= startTime,"not reach start time"); rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } constructor(address _multiSignature) multiSignatureClient(_multiSignature) public { } function update() onlyOwner public{ //for the future use } function setPoolMineAddress(address payable _liquidpool,address _phxaddress) public onlyOwner{ // require(_liquidpool != address(0)); require(_phxaddress != address(0)); lp = _liquidpool; phx = _phxaddress; } function setMineRate(uint256 _reward,uint256 _duration) public onlyOwner updateReward(address(0)){ //require(_reward>0); require(_duration>0); //token number per seconds rewardRate = _reward.div(_duration); // require(rewardRate > 0); rewardPerduration = _reward; duration = _duration; } function setPeriodFinish(uint256 startime,uint256 endtime)public onlyOwner updateReward(address(0)) { //the setting time must pass timebeing require(startime >=now); require(endtime > startTime); //set new finish time lastUpdateTime = startime; periodFinish = endtime; startTime = startime; } /** * @dev getting back the left mine token * @param reciever the reciever for getting back mine token */ function getbackLeftMiningToken(address payable reciever) public onlyOperator(0) validCall { uint256 bal = IERC20(phx).balanceOf(address(this)); IERC20(phx).transfer(reciever,bal); if(lp==address(0)){ reciever.transfer(address(this).balance); } } function setFeePara(uint256 phxFeeRatio,uint256 htFeeAmount,address payable feeReciever) onlyOwner public { if(phxFeeRatio>0) { _phxFeeRatio = phxFeeRatio; } if(htFeeAmount >0 ) { _htFeeAmount = htFeeAmount; } if(feeReciever != address(0)){ _feeReciever = feeReciever; } } function collectFee(address mineCoin,uint256 amount) internal returns (uint256){ if(_phxFeeRatio==0) { return amount; } require(msg.value>=_htFeeAmount,"need input ht coin value 0.01"); //charged ht fee _feeReciever.transfer(_htFeeAmount); if (mineCoin != address(0)){ //charge phx token fee uint256 fee = amount.mul(_phxFeeRatio).div(1000); IERC20 token = IERC20(mineCoin); uint256 preBalance = token.balanceOf(address(this)); //ERC20(this).safeTransfer(token,_feeReciever,fee); token.transfer(_feeReciever, fee); uint256 afterBalance = token.balanceOf(address(this)); require(preBalance - afterBalance == fee,"settlement token transfer error!"); return amount.sub(fee); } return amount; } //////////////////////////public function///////////////////////////////// function lastTimeRewardApplicable() public view returns(uint256) { uint256 timestamp = Math.max(block.timestamp,startTime); return Math.min(timestamp,periodFinish); } function rewardPerToken() public view returns(uint256) { if (totalSupply() == 0 || now < startTime) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(totalSupply()) ); } function earned(address account) internal view returns(uint256) { return balanceOf(account).mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } //keep same name with old version function totalRewards(address account) public view returns(uint256) { return earned(account); } function stake(uint256 amount,bytes memory data) public updateReward(msg.sender) payable notHalted nonReentrant { require(now < periodFinish,"over finish time");//do not allow to stake after finish super.stake(amount); emit Staked(msg.sender, amount); } function unstake(uint256 amount,bytes memory data) public updateReward(msg.sender) payable notHalted nonReentrant { require(amount > 0, "Cannot withdraw 0"); super.unstake(amount); emit Withdrawn(msg.sender, amount); } function exit() public notHalted nonReentrant { unstake(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) payable notHalted nonReentrant { uint256 reward = earned(msg.sender); if (reward > 0) { //get fee for reciever //reward = collectFee(phx,reward); rewards[msg.sender] = 0; uint256 preBalance = IERC20(phx).balanceOf(address(this)); IERC20(phx).transfer(msg.sender, reward); uint256 afterBalance = IERC20(phx).balanceOf(address(this)); require(preBalance - afterBalance==reward,"phx award transfer error!"); emit RewardPaid(msg.sender, reward); } } /** * @return Total number of distribution tokens balance. */ function distributionBalance() public view returns (uint256) { return IERC20(phx).balanceOf(address(this)); } /** * @param addr The user to look up staking information for. * @return The number of staking tokens deposited for addr. */ function totalStakedFor(address addr) public view returns (uint256) { return super.balanceOf(addr); } /** * @dev all stake token. * @return The number of staking tokens */ function getMineInfo() public view returns (uint256,uint256,uint256,uint256) { return (rewardPerduration,duration,startTime,periodFinish); } function getVersion() public view returns (uint256) { return 1; } /////////////////////////////////////////////////////////////////////////////////////// function deposit(uint256 _pid, uint256 _amount) public payable { bytes memory data = new bytes(1); stake(_amount,data); } function withdraw(uint256 _pid, uint256 _amount) public payable{ if(_amount==0) { getReward(); }else { bytes memory data = new bytes(1); unstake(_amount,data); } } function allPendingReward(uint256 _pid,address _user) public view returns(uint256,uint256,uint256){ return (totalStakedFor(_user),totalRewards(_user),0); } function totalStaked(uint256 _pid) public view returns (uint256){ return super.totalSupply(); } }
return Total number of distribution tokens balance./
function distributionBalance() public view returns (uint256) { return IERC20(phx).balanceOf(address(this)); }
14,804,352
./full_match/1/0x492B6F8A53D1c42cC2DD352788a6C02c557BE9F5/sources/contracts/integrations/curve/common/Stablz3CRVMetaPoolIntegration.sol
Withdraw stablecoins _stablecoin chosen stablecoin to withdraw _lpTokens LP amount to remove _minAmount minimum amount of _stablecoin to receive return received Amount of _stablecoin received from withdrawing _lpToken
function _farmWithdrawal(address _stablecoin, uint _lpTokens, uint _minAmount) internal override returns (uint received) { ICurve3CRVGauge(CRV_GAUGE).withdraw(_lpTokens); IERC20(CRV_META_POOL).safeIncreaseAllowance(CRV_DEPOSIT_ZAP, _lpTokens); received = ICurve3CRVDepositZap(CRV_DEPOSIT_ZAP).remove_liquidity_one_coin(CRV_META_POOL, _lpTokens, _getStablecoinIndex(_stablecoin), _minAmount); }
3,190,066
./full_match/1/0xC41575D0CF4A630B7992c675D760939E1402151C/sources/src/brokerbot/Brokerbot.sol
secondsPerStep should be negative for downwards drift
function setDrift(uint256 secondsPerStep, int256 _driftIncrement) external onlyOwner { anchorPrice(getPrice()); timeToDrift = secondsPerStep; driftIncrement = _driftIncrement; emit DriftSet(secondsPerStep, _driftIncrement); }
3,147,873
pragma solidity >=0.4.24; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ //Operation variables uint constant M = 3; //Number of confirmations require to stop operation bool private operational = true; // Blocks all state changes throughout the contract if false address[] multiCalls = new address[](0); address private contractOwner; // Account used to deploy contract FlightSuretyData flightSuretyData; // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; // Fee to be paid when registering airline uint256 public constant REGISTRATION_FEE_AIRLINES = 10 ether; // Maximum insurance fee that can be accepted uint256 public constant MAX_INSURANCE_PASSENGER = 1 ether; // Number of airlines that can register before consensus requirement uint256 public constant AIRLINE_NUM_BEFORE_CONS = 4; address[] consensusVotes = new address[](0); //Array to record votes for Consensus struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; string flightNumber; } mapping(bytes32 => Flight) private flights; /********************************************************************************************/ /* Events */ /********************************************************************************************/ event AirlineRegistered(address _airline); //Event triggered when Airline is Registered event AirlineFunded(address _airline); //Event triggered when Airline is Funded event InsureesCredited(string _flightNumber); //Event triggered when Passenger is paid insurance event PassengerInsured(); //Event triggered when passenger purchases insurance event FlightRegistered(string _flight);//Event triggered when flight is registered /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the flight to be registered before it can be insured */ modifier requireIsFlightRegistered(address airline, string memory flight, uint time) { require(isFlightRegistered(airline, flight, time) == true, "Flight is not insured"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address dataContract) public { contractOwner = msg.sender; flightSuretyData = FlightSuretyData(dataContract); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns(bool) { return operational; // Modify to call data contract's status } function isFlightRegistered ( address airline, string memory flight, uint timestamp ) public view returns(bool) { bytes32 key = getFlightKey(airline, flight, timestamp); return flights[key].isRegistered; // Modify to call data contract's status } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireIsOperational { require(mode != operational, "New mode must be different from existing mode"); require(flightSuretyData.isFunded(msg.sender), "Caller is not a funded airline."); bool isDuplicate = false; for(uint c=0; c<multiCalls.length; c++) { if (multiCalls[c] == msg.sender) { isDuplicate = true; break; } } require(!isDuplicate, "Caller has already called this function."); multiCalls.push(msg.sender); if (multiCalls.length >= M) { operational = mode; multiCalls = new address[](0); } } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * */ function registerAirline ( address _airline ) requireIsOperational external { //Check how many airlines registered uint256 number = flightSuretyData._getRegisteredAirlinesNum(); bool register = true; //success = false; uint votes = 0; // if number of airlines registered is greater than 4 perform the consensus check if(number >= AIRLINE_NUM_BEFORE_CONS){ //check if caller is a registered airlines bool isRegistered = flightSuretyData.isRegistered(msg.sender); require(isRegistered == true, "Caller is not a registered airline"); bool isDuplicate = false; register = false; for(uint c = 0; c < consensusVotes.length; c++) { if (consensusVotes[c] == msg.sender) { isDuplicate = true; break; } } require(!isDuplicate, "Caller has already called this function."); consensusVotes.push(msg.sender); votes = consensusVotes.length; uint check = number.div(2); if (votes >= check) { register = true; consensusVotes = new address[](0); } } if(register == true) { flightSuretyData.registerAirline(_airline, msg.sender); emit AirlineRegistered(_airline); } } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund () external payable requireIsOperational { require(msg.value == REGISTRATION_FEE_AIRLINES, "Not enough Ether to fund airline. Requires 10 ETH" ); require(flightSuretyData.isFunded(msg.sender) == false, "Airline is already funded"); flightSuretyData.fund(REGISTRATION_FEE_AIRLINES, msg.sender); address(flightSuretyData).transfer(REGISTRATION_FEE_AIRLINES); emit AirlineFunded(msg.sender); } /** * @dev Register a future flight for insuring. * */ function registerFlight ( uint256 time, address _airline, string flightNumber ) external requireIsOperational { require(isFlightRegistered(_airline, flightNumber, time) == false, "This flight is already registered"); bytes32 key = getFlightKey(_airline, flightNumber, time); flights[key] = Flight({isRegistered: true, statusCode: STATUS_CODE_UNKNOWN, updatedTimestamp: time, airline: _airline, flightNumber: flightNumber}); emit FlightRegistered(flightNumber); } /** * @dev Insure passenger for a future flight. * */ function insurePassenger ( string flight, uint256 time, address airline, address passenger ) external payable requireIsOperational //requireIsFlightRegistered(airline, flight, time) { require(msg.value <= MAX_INSURANCE_PASSENGER, "Passengers can pay a max of 1 ETH"); address(flightSuretyData).transfer(msg.value); flightSuretyData.buy(flight, time, passenger, msg.sender, msg.value); emit PassengerInsured(); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus ( string memory flight, uint8 statusCode ) internal { if(statusCode == STATUS_CODE_LATE_AIRLINE){ //flightSuretyData.creditInsurees(flight); address[] memory passengers = flightSuretyData.getPassengersInsured(flight); uint amount = 0; address passenger; uint index; //passengers = flightSuretyData.FlightPassengers[flight]; for(uint i = 0; i < passengers.length; i++){ passenger = passengers[i]; amount = flightSuretyData.GetInsuredAmount(flight, passenger); amount = amount.mul(15).div(10); flightSuretyData.SetInsuredAmount(flight, passenger, amount); } emit InsureesCredited(flight); } } /* function claimFlightInsurance () public { address memory direccio = flightsuretydata.getFlightInsurance(msg.sender); uint8 status = flights[direccio].statusCode; passenger = flights[direccio]; timeStamp = direccio []; string storage airlineName = trav []; uint price = direccio []; if(keccak256(status) == keccak256(ACTIVE)){ uint8 flightStatus = STATUS_CODE_LATE_AIRLINE; if(flightStatus == STATUS_CODE_LATE_AIRLINE){ flightSuretyData.addCreditToPassenger(msg.sender, SafeMath.div( SafeMath.mul(3,price),2)); flightSuretyData.setFlightInsuranceStatus(msg.sender, INACTIVE_FLIGHT_DELAYED); } else if (now < timeStamp){ flightSuretyData.setFlightInsuranceStatus(msg.sender, INACTIVE_EXPIRED); } } }*/ /** * @dev Called when passenger wants to withdraw insurance payout * */ function withdrawPayout() external { flightSuretyData.withdraw(msg.sender); } /** * @dev Called when passenger wants to withdraw insurance payout * */ function getFlightsInsured ( address passenger, string flight ) external returns ( bool status ) { status = flightSuretyData.getFlightsInsured(passenger, flight); } function getFlightAmountInsured ( string flight ) external view returns ( uint amount ) { amount = flightSuretyData.getFlightAmountInsured(flight); } function getPassengerCredits ( address passenger ) external view requireIsOperational returns ( uint amount ) { return flightSuretyData.getPassengerCredits(passenger); } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, string flight, uint256 timestamp ) external { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({requester: msg.sender, isOpen: true}); emit OracleRequest(index, airline, flight, timestamp); } //Returns Contract Balance function getContractBalance() external view returns(uint balance) { return flightSuretyData.getContractBalance(); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 public constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) public oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); event OracleRegistered(address oracle); // Register an oracle with the contract function registerOracle() external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({isRegistered: true, indexes: indexes}); emit OracleRegistered(msg.sender); } function getMyIndexes ( ) view external returns(uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(flight, statusCode); } } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) public returns ( uint8[3] memory ) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) public returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion } contract FlightSuretyData { function registerAirline (address _airline, address caller) external; function _getRegisteredAirlinesNum() external returns(uint number); function fund (uint256 fundAmt, address sender) public; function creditInsurees (string flight) external; // function getFlightInsurance(address owner_) public returns (Passenger _passenger); function isRegistered(address _airline) public returns(bool _reg); function isFunded(address _airline) public returns(bool _reg); function buy(string flight, uint256 time, address passenger, address sender, uint256 amount) public; function withdraw(address payee) external payable; function getFlightsInsured(address passenger, string flight) external returns(bool status); function getFlightAmountInsured(string flight) external view returns(uint amount) ; function getPassengerCredits(address passenger) external view returns(uint amount); function getContractBalance() external view returns(uint balance); function getPassengersInsured(string flight) external returns(address[] passengers); function GetInsuredAmount(string flight, address passenger) external returns(uint amount); function SetInsuredAmount(string flight, address passenger, uint amount) external; }
Add an airline to the registration queue/Check how many airlines registeredsuccess = false; if number of airlines registered is greater than 4 perform the consensus checkcheck if caller is a registered airlines
function registerAirline ( address _airline ) requireIsOperational external { uint256 number = flightSuretyData._getRegisteredAirlinesNum(); bool register = true; uint votes = 0; if(number >= AIRLINE_NUM_BEFORE_CONS){ bool isRegistered = flightSuretyData.isRegistered(msg.sender); require(isRegistered == true, "Caller is not a registered airline"); bool isDuplicate = false; register = false; for(uint c = 0; c < consensusVotes.length; c++) { if (consensusVotes[c] == msg.sender) { isDuplicate = true; break; } } require(!isDuplicate, "Caller has already called this function."); consensusVotes.push(msg.sender); votes = consensusVotes.length; uint check = number.div(2); if (votes >= check) { register = true; consensusVotes = new address[](0); } } if(register == true) { flightSuretyData.registerAirline(_airline, msg.sender); emit AirlineRegistered(_airline); } }
1,035,318
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "../interface/RocketStorageInterface.sol"; /// @title Base settings / modifiers for each contract in Rocket Pool /// @author David Rugendyke abstract contract RocketBase { // Calculate using this as the base uint256 constant calcBase = 1 ether; // Version of the contract uint8 public version; // The main storage contract where primary persistant storage is maintained RocketStorageInterface rocketStorage = RocketStorageInterface(0); /*** Modifiers **********************************************************/ /** * @dev Throws if called by any sender that doesn't match a Rocket Pool network contract */ modifier onlyLatestNetworkContract() { require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract"); _; } /** * @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract */ modifier onlyLatestContract(string memory _contractName, address _contractAddress) { require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract"); _; } /** * @dev Throws if called by any sender that isn't a registered node */ modifier onlyRegisteredNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress))), "Invalid node"); _; } /** * @dev Throws if called by any sender that isn't a trusted node DAO member */ modifier onlyTrustedNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("dao.trustednodes.", "member", _nodeAddress))), "Invalid trusted node"); _; } /** * @dev Throws if called by any sender that isn't a registered minipool */ modifier onlyRegisteredMinipool(address _minipoolAddress) { require(getBool(keccak256(abi.encodePacked("minipool.exists", _minipoolAddress))), "Invalid minipool"); _; } /** * @dev Throws if called by any account other than a guardian account (temporary account allowed access to settings before DAO is fully enabled) */ modifier onlyGuardian() { require(msg.sender == rocketStorage.getGuardian(), "Account is not a temporary guardian"); _; } /*** Methods **********************************************************/ /// @dev Set the main Rocket Storage address constructor(RocketStorageInterface _rocketStorageAddress) { // Update the contract address rocketStorage = RocketStorageInterface(_rocketStorageAddress); } /// @dev Get the address of a network contract by name function getContractAddress(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Check it require(contractAddress != address(0x0), "Contract not found"); // Return return contractAddress; } /// @dev Get the address of a network contract by name (returns address(0x0) instead of reverting if contract does not exist) function getContractAddressUnsafe(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Return return contractAddress; } /// @dev Get the name of a network contract by address function getContractName(address _contractAddress) internal view returns (string memory) { // Get the contract name string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress))); // Check it require(bytes(contractName).length > 0, "Contract not found"); // Return return contractName; } /// @dev Get revert error message from a .call method function getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /*** Rocket Storage Methods ****************************************/ // Note: Unused helpers have been removed to keep contract sizes down /// @dev Storage get methods function getAddress(bytes32 _key) internal view returns (address) { return rocketStorage.getAddress(_key); } function getUint(bytes32 _key) internal view returns (uint) { return rocketStorage.getUint(_key); } function getString(bytes32 _key) internal view returns (string memory) { return rocketStorage.getString(_key); } function getBytes(bytes32 _key) internal view returns (bytes memory) { return rocketStorage.getBytes(_key); } function getBool(bytes32 _key) internal view returns (bool) { return rocketStorage.getBool(_key); } function getInt(bytes32 _key) internal view returns (int) { return rocketStorage.getInt(_key); } function getBytes32(bytes32 _key) internal view returns (bytes32) { return rocketStorage.getBytes32(_key); } /// @dev Storage set methods function setAddress(bytes32 _key, address _value) internal { rocketStorage.setAddress(_key, _value); } function setUint(bytes32 _key, uint _value) internal { rocketStorage.setUint(_key, _value); } function setString(bytes32 _key, string memory _value) internal { rocketStorage.setString(_key, _value); } function setBytes(bytes32 _key, bytes memory _value) internal { rocketStorage.setBytes(_key, _value); } function setBool(bytes32 _key, bool _value) internal { rocketStorage.setBool(_key, _value); } function setInt(bytes32 _key, int _value) internal { rocketStorage.setInt(_key, _value); } function setBytes32(bytes32 _key, bytes32 _value) internal { rocketStorage.setBytes32(_key, _value); } /// @dev Storage delete methods function deleteAddress(bytes32 _key) internal { rocketStorage.deleteAddress(_key); } function deleteUint(bytes32 _key) internal { rocketStorage.deleteUint(_key); } function deleteString(bytes32 _key) internal { rocketStorage.deleteString(_key); } function deleteBytes(bytes32 _key) internal { rocketStorage.deleteBytes(_key); } function deleteBool(bytes32 _key) internal { rocketStorage.deleteBool(_key); } function deleteInt(bytes32 _key) internal { rocketStorage.deleteInt(_key); } function deleteBytes32(bytes32 _key) internal { rocketStorage.deleteBytes32(_key); } /// @dev Storage arithmetic methods function addUint(bytes32 _key, uint256 _amount) internal { rocketStorage.addUint(_key, _amount); } function subUint(bytes32 _key, uint256 _amount) internal { rocketStorage.subUint(_key, _amount); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "../../RocketBase.sol"; import "../../../interface/dao/node/RocketDAONodeTrustedInterface.sol"; import "../../../interface/dao/node/RocketDAONodeTrustedProposalsInterface.sol"; import "../../../interface/dao/node/RocketDAONodeTrustedActionsInterface.sol"; import "../../../interface/dao/node/RocketDAONodeTrustedUpgradeInterface.sol"; import "../../../interface/dao/node/settings/RocketDAONodeTrustedSettingsInterface.sol"; import "../../../interface/dao/node/settings/RocketDAONodeTrustedSettingsProposalsInterface.sol"; import "../../../interface/dao/RocketDAOProposalInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // The Trusted Node DAO Proposals contract RocketDAONodeTrustedProposals is RocketBase, RocketDAONodeTrustedProposalsInterface { using SafeMath for uint; // The namespace for any data stored in the trusted node DAO (do not change) string constant daoNameSpace = "dao.trustednodes."; // Only allow certain contracts to execute methods modifier onlyExecutingContracts() { // Methods are either executed by bootstrapping methods in rocketDAONodeTrusted or by people executing passed proposals in rocketDAOProposal require(msg.sender == getContractAddress("rocketDAONodeTrusted") || msg.sender == getContractAddress("rocketDAOProposal"), "Sender is not permitted to access executing methods"); _; } // Construct constructor(RocketStorageInterface _rocketStorageAddress) RocketBase(_rocketStorageAddress) { // Version version = 1; } /*** Proposals **********************/ // Create a DAO proposal with calldata, if successful will be added to a queue where it can be executed // A general message can be passed by the proposer along with the calldata payload that can be executed if the proposal passes function propose(string memory _proposalMessage, bytes memory _payload) override external onlyTrustedNode(msg.sender) onlyLatestContract("rocketDAONodeTrustedProposals", address(this)) returns (uint256) { // Load contracts RocketDAOProposalInterface daoProposal = RocketDAOProposalInterface(getContractAddress("rocketDAOProposal")); RocketDAONodeTrustedInterface daoNodeTrusted = RocketDAONodeTrustedInterface(getContractAddress("rocketDAONodeTrusted")); RocketDAONodeTrustedSettingsProposalsInterface rocketDAONodeTrustedSettingsProposals = RocketDAONodeTrustedSettingsProposalsInterface(getContractAddress("rocketDAONodeTrustedSettingsProposals")); // Check this user can make a proposal now require(daoNodeTrusted.getMemberLastProposalTime(msg.sender).add(rocketDAONodeTrustedSettingsProposals.getCooldownTime()) <= block.timestamp, "Member has not waited long enough to make another proposal"); // Require the min amount of members are in to make a proposal require(daoNodeTrusted.getMemberCount() >= daoNodeTrusted.getMemberMinRequired(), "Min member count not met to allow proposals to be added"); // Record the last time this user made a proposal setUint(keccak256(abi.encodePacked(daoNameSpace, "member.proposal.lasttime", msg.sender)), block.timestamp); // Create the proposal return daoProposal.add(msg.sender, "rocketDAONodeTrustedProposals", _proposalMessage, block.timestamp.add(rocketDAONodeTrustedSettingsProposals.getVoteDelayTime()), rocketDAONodeTrustedSettingsProposals.getVoteTime(), rocketDAONodeTrustedSettingsProposals.getExecuteTime(), daoNodeTrusted.getMemberQuorumVotesRequired(), _payload); } // Vote on a proposal function vote(uint256 _proposalID, bool _support) override external onlyTrustedNode(msg.sender) onlyLatestContract("rocketDAONodeTrustedProposals", address(this)) { // Load contracts RocketDAOProposalInterface daoProposal = RocketDAOProposalInterface(getContractAddress("rocketDAOProposal")); RocketDAONodeTrustedInterface daoNodeTrusted = RocketDAONodeTrustedInterface(getContractAddress("rocketDAONodeTrusted")); // Did they join after this proposal was created? If so, they can't vote or it'll throw off the set proposalVotesRequired require(daoNodeTrusted.getMemberJoinedTime(msg.sender) < daoProposal.getCreated(_proposalID), "Member cannot vote on proposal created before they became a member"); // Vote now, one vote per trusted node member daoProposal.vote(msg.sender, 1 ether, _proposalID, _support); } // Cancel a proposal function cancel(uint256 _proposalID) override external onlyTrustedNode(msg.sender) onlyLatestContract("rocketDAONodeTrustedProposals", address(this)) { // Load contracts RocketDAOProposalInterface daoProposal = RocketDAOProposalInterface(getContractAddress("rocketDAOProposal")); // Cancel now, will succeed if it is the original proposer daoProposal.cancel(msg.sender, _proposalID); } // Execute a proposal function execute(uint256 _proposalID) override external onlyLatestContract("rocketDAONodeTrustedProposals", address(this)) { // Load contracts RocketDAOProposalInterface daoProposal = RocketDAOProposalInterface(getContractAddress("rocketDAOProposal")); // Execute now daoProposal.execute(_proposalID); } /*** Proposal - Members **********************/ // A new DAO member being invited, can only be done via a proposal or in bootstrap mode // Provide an ID that indicates who is running the trusted node and the address of the registered node that they wish to propose joining the dao function proposalInvite(string memory _id, string memory _url, address _nodeAddress) override external onlyExecutingContracts onlyRegisteredNode(_nodeAddress) { // Their proposal executed, record the block setUint(keccak256(abi.encodePacked(daoNameSpace, "member.executed.time", "invited", _nodeAddress)), block.timestamp); // Ok all good, lets get their invitation and member data setup // They are initially only invited to join, so their membership isn't set as true until they accept it in RocketDAONodeTrustedActions _memberInit(_id, _url, _nodeAddress); } // A current member proposes leaving the trusted node DAO, when successful they will be allowed to collect their RPL bond function proposalLeave(address _nodeAddress) override external onlyExecutingContracts onlyTrustedNode(_nodeAddress) { // Load contracts RocketDAONodeTrustedInterface daoNodeTrusted = RocketDAONodeTrustedInterface(getContractAddress("rocketDAONodeTrusted")); // Check this wouldn't dip below the min required trusted nodes (also checked when the node has a successful proposal and attempts to exit) require(daoNodeTrusted.getMemberCount() > daoNodeTrusted.getMemberMinRequired(), "Member count will fall below min required"); // Their proposal to leave has been accepted, record the block setUint(keccak256(abi.encodePacked(daoNameSpace, "member.executed.time", "leave", _nodeAddress)), block.timestamp); } // Propose to kick a current member from the DAO with an optional RPL bond fine function proposalKick(address _nodeAddress, uint256 _rplFine) override external onlyExecutingContracts onlyTrustedNode(_nodeAddress) { // Load contracts RocketDAONodeTrustedInterface daoNodeTrusted = RocketDAONodeTrustedInterface(getContractAddress("rocketDAONodeTrusted")); RocketDAONodeTrustedActionsInterface daoActionsContract = RocketDAONodeTrustedActionsInterface(getContractAddress("rocketDAONodeTrustedActions")); // How much is their RPL bond? uint256 rplBondAmount = daoNodeTrusted.getMemberRPLBondAmount(_nodeAddress); // Check fine amount can be covered require(_rplFine <= rplBondAmount, "RPL Fine must be lower or equal to the RPL bond amount of the node being kicked"); // Set their bond amount minus the fine setUint(keccak256(abi.encodePacked(daoNameSpace, "member.bond.rpl", _nodeAddress)), rplBondAmount.sub(_rplFine)); // Kick them now daoActionsContract.actionKick(_nodeAddress, _rplFine); } /*** Proposal - Settings ***************/ // Change one of the current uint256 settings of the DAO function proposalSettingUint(string memory _settingContractName, string memory _settingPath, uint256 _value) override external onlyExecutingContracts() { // Load contracts RocketDAONodeTrustedSettingsInterface rocketDAONodeTrustedSettings = RocketDAONodeTrustedSettingsInterface(getContractAddress(_settingContractName)); // Lets update rocketDAONodeTrustedSettings.setSettingUint(_settingPath, _value); } // Change one of the current bool settings of the DAO function proposalSettingBool(string memory _settingContractName, string memory _settingPath, bool _value) override external onlyExecutingContracts() { // Load contracts RocketDAONodeTrustedSettingsInterface rocketDAONodeTrustedSettings = RocketDAONodeTrustedSettingsInterface(getContractAddress(_settingContractName)); // Lets update rocketDAONodeTrustedSettings.setSettingBool(_settingPath, _value); } /*** Proposal - Upgrades ***************/ // Upgrade contracts or ABI's if the DAO agrees function proposalUpgrade(string memory _type, string memory _name, string memory _contractAbi, address _contractAddress) override external onlyExecutingContracts() { // Load contracts RocketDAONodeTrustedUpgradeInterface rocketDAONodeTrustedUpgradeInterface = RocketDAONodeTrustedUpgradeInterface(getContractAddress("rocketDAONodeTrustedUpgrade")); // Lets update rocketDAONodeTrustedUpgradeInterface.upgrade(_type, _name, _contractAbi, _contractAddress); } /*** Internal ***************/ // Add a new potential members data, they are not official members yet, just propsective function _memberInit(string memory _id, string memory _url, address _nodeAddress) private onlyRegisteredNode(_nodeAddress) { // Load contracts RocketDAONodeTrustedInterface daoNodeTrusted = RocketDAONodeTrustedInterface(getContractAddress("rocketDAONodeTrusted")); // Check current node status require(!daoNodeTrusted.getMemberIsValid(_nodeAddress), "This node is already part of the trusted node DAO"); // Verify the ID is min 3 chars require(bytes(_id).length >= 3, "The ID for this new member must be at least 3 characters"); // Check URL length require(bytes(_url).length >= 6, "The URL for this new member must be at least 6 characters"); // Member initial data, not official until the bool is flagged as true setBool(keccak256(abi.encodePacked(daoNameSpace, "member", _nodeAddress)), false); setAddress(keccak256(abi.encodePacked(daoNameSpace, "member.address", _nodeAddress)), _nodeAddress); setString(keccak256(abi.encodePacked(daoNameSpace, "member.id", _nodeAddress)), _id); setString(keccak256(abi.encodePacked(daoNameSpace, "member.url", _nodeAddress)), _url); setUint(keccak256(abi.encodePacked(daoNameSpace, "member.bond.rpl", _nodeAddress)), 0); setUint(keccak256(abi.encodePacked(daoNameSpace, "member.joined.time", _nodeAddress)), 0); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketStorageInterface { // Deploy status function getDeployedStatus() external view returns (bool); // Guardian function getGuardian() external view returns(address); function setGuardian(address _newAddress) external; function confirmGuardian() external; // Getters function getAddress(bytes32 _key) external view returns (address); function getUint(bytes32 _key) external view returns (uint); function getString(bytes32 _key) external view returns (string memory); function getBytes(bytes32 _key) external view returns (bytes memory); function getBool(bytes32 _key) external view returns (bool); function getInt(bytes32 _key) external view returns (int); function getBytes32(bytes32 _key) external view returns (bytes32); // Setters function setAddress(bytes32 _key, address _value) external; function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string calldata _value) external; function setBytes(bytes32 _key, bytes calldata _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; // Deleters function deleteAddress(bytes32 _key) external; function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; // Arithmetic function addUint(bytes32 _key, uint256 _amount) external; function subUint(bytes32 _key, uint256 _amount) external; // Protected storage function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address); function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address); function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external; function confirmWithdrawalAddress(address _nodeAddress) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAOProposalInterface { // Possible states that a proposal may be in enum ProposalState { Pending, Active, Cancelled, Defeated, Succeeded, Expired, Executed } function getTotal() external view returns (uint256); function getDAO(uint256 _proposalID) external view returns (string memory); function getProposer(uint256 _proposalID) external view returns (address); function getMessage(uint256 _proposalID) external view returns (string memory); function getStart(uint256 _proposalID) external view returns (uint256); function getEnd(uint256 _proposalID) external view returns (uint256); function getExpires(uint256 _proposalID) external view returns (uint256); function getCreated(uint256 _proposalID) external view returns (uint256); function getVotesFor(uint256 _proposalID) external view returns (uint256); function getVotesAgainst(uint256 _proposalID) external view returns (uint256); function getVotesRequired(uint256 _proposalID) external view returns (uint256); function getCancelled(uint256 _proposalID) external view returns (bool); function getExecuted(uint256 _proposalID) external view returns (bool); function getPayload(uint256 _proposalID) external view returns (bytes memory); function getReceiptHasVoted(uint256 _proposalID, address _nodeAddress) external view returns (bool); function getReceiptSupported(uint256 _proposalID, address _nodeAddress) external view returns (bool); function getState(uint256 _proposalID) external view returns (ProposalState); function add(address _member, string memory _dao, string memory _message, uint256 _startBlock, uint256 _durationBlocks, uint256 _expiresBlocks, uint256 _votesRequired, bytes memory _payload) external returns (uint256); function vote(address _member, uint256 _votes, uint256 _proposalID, bool _support) external; function cancel(address _member, uint256 _proposalID) external; function execute(uint256 _proposalID) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAONodeTrustedActionsInterface { function actionJoin() external; function actionJoinRequired(address _nodeAddress) external; function actionLeave(address _rplBondRefundAddress) external; function actionKick(address _nodeAddress, uint256 _rplFine) external; function actionChallengeMake(address _nodeAddress) external payable; function actionChallengeDecide(address _nodeAddress) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAONodeTrustedInterface { function getBootstrapModeDisabled() external view returns (bool); function getMemberQuorumVotesRequired() external view returns (uint256); function getMemberAt(uint256 _index) external view returns (address); function getMemberCount() external view returns (uint256); function getMemberMinRequired() external view returns (uint256); function getMemberIsValid(address _nodeAddress) external view returns (bool); function getMemberLastProposalTime(address _nodeAddress) external view returns (uint256); function getMemberID(address _nodeAddress) external view returns (string memory); function getMemberUrl(address _nodeAddress) external view returns (string memory); function getMemberJoinedTime(address _nodeAddress) external view returns (uint256); function getMemberProposalExecutedTime(string memory _proposalType, address _nodeAddress) external view returns (uint256); function getMemberRPLBondAmount(address _nodeAddress) external view returns (uint256); function getMemberIsChallenged(address _nodeAddress) external view returns (bool); function getMemberUnbondedValidatorCount(address _nodeAddress) external view returns (uint256); function incrementMemberUnbondedValidatorCount(address _nodeAddress) external; function decrementMemberUnbondedValidatorCount(address _nodeAddress) external; function bootstrapMember(string memory _id, string memory _url, address _nodeAddress) external; function bootstrapSettingUint(string memory _settingContractName, string memory _settingPath, uint256 _value) external; function bootstrapSettingBool(string memory _settingContractName, string memory _settingPath, bool _value) external; function bootstrapUpgrade(string memory _type, string memory _name, string memory _contractAbi, address _contractAddress) external; function bootstrapDisable(bool _confirmDisableBootstrapMode) external; function memberJoinRequired(string memory _id, string memory _url) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAONodeTrustedProposalsInterface { function propose(string memory _proposalMessage, bytes memory _payload) external returns (uint256); function vote(uint256 _proposalID, bool _support) external; function cancel(uint256 _proposalID) external; function execute(uint256 _proposalID) external; function proposalInvite(string memory _id, string memory _url, address _nodeAddress) external; function proposalLeave(address _nodeAddress) external; function proposalKick(address _nodeAddress, uint256 _rplFine) external; function proposalSettingUint(string memory _settingContractName, string memory _settingPath, uint256 _value) external; function proposalSettingBool(string memory _settingContractName, string memory _settingPath, bool _value) external; function proposalUpgrade(string memory _type, string memory _name, string memory _contractAbi, address _contractAddress) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAONodeTrustedUpgradeInterface { function upgrade(string memory _type, string memory _name, string memory _contractAbi, address _contractAddress) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAONodeTrustedSettingsInterface { function getSettingUint(string memory _settingPath) external view returns (uint256); function setSettingUint(string memory _settingPath, uint256 _value) external; function getSettingBool(string memory _settingPath) external view returns (bool); function setSettingBool(string memory _settingPath, bool _value) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAONodeTrustedSettingsProposalsInterface { function getCooldownTime() external view returns(uint256); function getVoteTime() external view returns(uint256); function getVoteDelayTime() external view returns(uint256); function getExecuteTime() external view returns(uint256); function getActionTime() external view returns(uint256); }
Vote on a proposal Load contracts Did they join after this proposal was created? If so, they can't vote or it'll throw off the set proposalVotesRequired Vote now, one vote per trusted node member
function vote(uint256 _proposalID, bool _support) override external onlyTrustedNode(msg.sender) onlyLatestContract("rocketDAONodeTrustedProposals", address(this)) { RocketDAOProposalInterface daoProposal = RocketDAOProposalInterface(getContractAddress("rocketDAOProposal")); RocketDAONodeTrustedInterface daoNodeTrusted = RocketDAONodeTrustedInterface(getContractAddress("rocketDAONodeTrusted")); require(daoNodeTrusted.getMemberJoinedTime(msg.sender) < daoProposal.getCreated(_proposalID), "Member cannot vote on proposal created before they became a member"); daoProposal.vote(msg.sender, 1 ether, _proposalID, _support); }
292,898
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // 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); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol // 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); } } } } // File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/utils/Strings.sol // 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); } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @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 {} } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds" ); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/SamuraiSquirrels.sol pragma solidity >=0.7.0 <0.9.0; contract SamuraiSquirrels is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.08 ether; uint256 public maxSupply = 1250; uint256 public maxMintAmount = 20; bool public revealed = false; string public notRevealedUri; // Two whitelists and one public and an marketing mint bool public marketingMinting = true; bool public earlyBirdMinting = false; bool public whitelistMinting = false; bool public publicMinting = false; bool public mintLimitActive = true; mapping(address => bool) earlyBirdList; mapping(address => bool) whitelist; mapping(address => bool) alreadyMinted; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } modifier onlyOwnerOrDev() { require( owner() == msg.sender || msg.sender == 0x4cd9a216788Ec125d4f107d3c0fC394cB2eBA9a4, "Ownable: caller is not the owner or dev" ); _; } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public (Public Mint) function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(publicMinting, "Error: Public minting is not active yet."); require(_mintAmount > 0, "Error: You need to mint atleast one token."); require(_mintAmount <= maxMintAmount, "Error: Maximum limit surpassed"); require(supply + _mintAmount <= maxSupply, "Error: Not enough supply"); if (msg.sender != owner()) { require( msg.value >= cost * _mintAmount, "Error: costs are higher per NFT." ); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } // public (Early Bird Mint) 150 to mint function earlyBirdMint() public payable { uint256 supply = totalSupply(); require( earlyBirdMinting, "Error: Early Bird minting is not active yet." ); require(supply < 250, "Error: Maximum limit surpassed"); // max total mints is 100 marketing, 150 earlybird, require( earlyBirdList[msg.sender], "Error: Sender is not on the Early Bird List!" ); if (mintLimitActive) { require( !alreadyMinted[msg.sender], "Error: Sender already minted one token" ); } if (msg.sender != owner()) { require(msg.value >= cost, "Error: costs are higher per NFT."); } _safeMint(msg.sender, supply + 1); alreadyMinted[msg.sender] = true; } // public (Early Bird Mint) 150 to mint function whitelistMint() public payable { uint256 supply = totalSupply(); require( whitelistMinting, "Error: Whitelist minting is not active yet." ); require(supply < 650, "Error: Maximum limit surpassed"); // max total mints is 100 marketing, 150 earlybird, 400 in whitelist require(whitelist[msg.sender], "Sender is not on the whitelist!"); if (mintLimitActive) { require( !alreadyMinted[msg.sender], "Sender already minted one token" ); } if (msg.sender != owner()) { require(msg.value >= cost, "Error: costs are higher per NFT."); } _safeMint(msg.sender, supply + 1); alreadyMinted[msg.sender] = true; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, tokenId.toString(), baseExtension ) ) : ""; } // public marketing mint 100 function marketingMint() public payable onlyOwnerOrDev { uint256 supply = totalSupply(); require( marketingMinting, "Error: Marketing minting is not active yet." ); require(supply < 100, "Error you may only mint 100 NFTs"); // max total mints is 100 marketing for (uint256 i = 1; i <= 100; i++) { _safeMint(msg.sender, supply + i); } } function addToWhitelist(address[] calldata addressToAdd) external onlyOwner { for (uint256 i = 0; i < addressToAdd.length; i++) { whitelist[addressToAdd[i]] = true; } } function addToEarlyBirdlist(address[] calldata addressToAdd) external onlyOwner { for (uint256 i = 0; i < addressToAdd.length; i++) { earlyBirdList[addressToAdd[i]] = true; } } function setCost(uint256 _newCost) external onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } // should be public // // // // // // // // // // // function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } // // // // // // // // // // // function setBaseExtension(string memory _newBaseExtension) external onlyOwner { baseExtension = _newBaseExtension; } function setMarketingMinting(bool _state) external onlyOwner { marketingMinting = _state; } function setHiddenReveal(bool _state) external onlyOwner { revealed = _state; } function setEarlyBirdMinting(bool _state) external onlyOwner { earlyBirdMinting = _state; } function setWhitelistMinting(bool _state) external onlyOwner { whitelistMinting = _state; } function setPublicMinting(bool _state) external onlyOwner { publicMinting = _state; } function setMintLimitActive(bool _state) external onlyOwner { mintLimitActive = _state; } function withdraw() public payable onlyOwner { // ============================================================================= (bool hs, ) = payable(0x4cd9a216788Ec125d4f107d3c0fC394cB2eBA9a4).call{ value: (address(this).balance * 75) / 100 }(""); require(hs); // ============================================================================= // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } }
public marketing mint 100
function marketingMint() public payable onlyOwnerOrDev { uint256 supply = totalSupply(); require( marketingMinting, "Error: Marketing minting is not active yet." ); for (uint256 i = 1; i <= 100; i++) { _safeMint(msg.sender, supply + i); } }
13,664,872
./full_match/288/0x9284863F131f0145C8F22905C62504E9fD06AB2E/sources/contracts/Ola/Peripheral/ComptrollerPeripherals/RainMaker/SingleAssetDynamicRainMaker.sol
Set COMP speeds for a multiple markets _cTokens The markets whose COMP speeds to update _compSupplySpeeds New COMP speed per market _compBorrowSpeeds New COMP speed per market/
function _setDynamicCompSpeeds(CToken[] calldata _cTokens, uint[] calldata _compSupplySpeeds, uint[] calldata _compBorrowSpeeds) external { require(_cTokens.length == _compSupplySpeeds.length, "markets and supply speeds should be 1:1"); require(_cTokens.length == _compBorrowSpeeds.length, "markets and borrow speeds should be 1:1"); require(isAdmin(), "only admin can set comp speed"); for (uint i = 0; i < _cTokens.length; i++) { CToken cToken = _cTokens[i]; require(isListed[address(cToken)], "market not listed"); setCompSupplySpeedInternal(cToken, _compSupplySpeeds[i]); setCompBorrowSpeedInternal(cToken, _compBorrowSpeeds[i]); } }
7,104,169
./full_match/3/0x93766d16886Aeb9d9Bd2c6efcd2DDdf19d2ad832/sources/browser/Fungi.sol
converts 90% into dividends, spreads the rest among shareholders weiprice = Sp + ShpSh/M - P weiprice = Sp-t + (Sh-t)(pSh + fM/(Sh-t))/M - (P - ((t-f) + tpSh/M))
function sell(uint256 _tokens) external { uint256 fee = _tokens.div(10); uint256 withdrawed = _tokens.sub(fee); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_tokens); totalSupply = totalSupply.sub(_tokens); emit Transfer(msg.sender, address(0), _tokens); sharesOf[msg.sender] = sharesOf[msg.sender].sub(_tokens); totalShares = totalShares.sub(_tokens); uint256 payout = withdrawed.add(_tokens.mul(profitPerShare).div(multiplicator)); payoutsOf[msg.sender] = payoutsOf[msg.sender].signedSub(payout); }
14,231,153
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; /// @title simple voting + project proposal dapp /// @author Taehoon Kim contract Voting is ReentrancyGuard{ /// @notice implements both project suggestion and voting /// @notice imports Openzeppelin libraries as safety measures. /// @notice For this specific usage, SafeMath might have been not that necessary using Address for address; using SafeMath for uint256; using SafeMath for int256; /// @notice 'Project' struct variable definition. /// @notice stores both the description of the project and vote results struct Project{ string description; uint256 total_votes; // total votes = likes + dislikes + unsure uint256 likes; uint256 dislikes; uint256 unsure; } ///@notice public variables mapping(uint256 => mapping(address => bool)) public Proj_to_voted; // mapping var. to check whether a user voted for the project(proposal) address public Owner; // owner of the contract mapping(uint256 => Project) public Projects; // project id -> project mapping(address => uint256) public Proposed; // counting how many projects/proposals were suggested by a user uint256 public Project_num; // variable to track the number of proposals suggested (from all users) uint256 public Proposal_limit; // per-person limit for suggesting new proposals ///@notice initialization, sets 1) the owner, 2) per-person proposal limit 3) starting number of proposals (zero..) constructor(){ Owner = msg.sender; Proposal_limit=3; Project_num = 0; } //modifiers ///@notice checking if msg. sender is the owner modifier isOwner(){ require(Owner == msg.sender, "you need to be the owner to execute this function"); _; } ///@notice checking if msg. sender has already voted for the proposal ///@param proj_id id of the project modifier not_voted_for(uint256 proj_id){ require(Proj_to_voted[proj_id][msg.sender] ==false, "you've already voted for this project"); _; } ///@notice checking if msg.sender hasn't gone over the proposal limit ///@param add address of the msg.sender modifier less_than_limit(address add){ require(Proposed[add]<= Proposal_limit-1, "exceeding the upper limit for number of proposable projects"); _; } /// @notice checking if msg.sender is trying to vote for non-existing projects. /// @param proj_id id alias of the project to vote modifier existing_proj(uint256 proj_id){ require(proj_id <= Project_num-1, "project id exceeds the number of existing projects!"); _; } //events ///@notice logging if a project was successfully proposed(submitted...) ///@notice input parameters follow the struct definition of 'Project' variable. event registered_project(uint256 project_num, string description, uint256 total_votes, uint256 likes, uint256 dislikes, uint256 unsure); ///@notice logging when there is an increase in the number of proposed projects ///@param project_num integer value that tracks the number of projects event increased_proj_num(uint256 project_num); ///@notice logging if there is an increase in the number of proposed projects per user. ///@param proposed_num integer value that tracks the number of proposals per user event increased_proj_proposed(uint256 proposed_num); ///@notice logging if the voting was successfully done ///@param proj_id, project id and @param add msg.sender address event Voted(uint256 proj_id, address add); ///@notice logging the change in the upper limit for the number of proposals that can be suggested per person ///@param limit_val new integer value for the limit event changed_proposal_limit(uint256 limit_val); ///@notice logging if the voting was possible for that user (similar to the above "Voted" event) ///@notice only difference being that this event gets triggered right after voting function is triggered. ///@param proj_id id and @param add msg.sender address event logging_vote(uint256 proj_id, address add); //functions ///@notice main function to add project / proposal ///@param description string input to describe the project / proposal function add_project(string memory description) public less_than_limit(msg.sender) nonReentrant{ Projects[Project_num] = Project(description, 0,0,0,0); emit registered_project(Project_num, description, 0,0,0,0); Project_num++; //increment by 1 emit increased_proj_num(Project_num); Proposed[msg.sender]++; emit increased_proj_proposed(Proposed[msg.sender]); } ///@notice main function to cast a vote ///@param proj_id project id and @param vote_value vote values (1: like, 0 : indifferent, -1 : dislike) function vote(uint256 proj_id, int256 vote_value) public existing_proj(proj_id) not_voted_for(proj_id) nonReentrant{ Proj_to_voted[proj_id][msg.sender] = true; emit logging_vote(proj_id, msg.sender); Projects[proj_id].total_votes++; if(vote_value==-1){ Projects[proj_id].dislikes++; } else if(vote_value==1){ Projects[proj_id].likes++; } else if(vote_value==0){ Projects[proj_id].unsure++; } emit Voted(proj_id, msg.sender); } ///@notice function to change the upper limit (number of per-person proposable projects) ///@notice can only be triggered by the owner of the contract ///@param limit_val integer for the new limit ///@return the changed limit function change_proposal_limit(uint256 limit_val) public isOwner() returns (uint256){ Proposal_limit = limit_val; emit changed_proposal_limit(limit_val); return Proposal_limit; } ///@notice function to get number of currently existing projects ///@return number of existing projects function get_project_num() public view returns (uint256){ return Project_num; } ///@notice function to get current limit (per-person proposable number of projects) ///@return current upper limit function get_proposal_limit() public view returns (uint256){ return Proposal_limit; } }
function to get number of currently existing projectsreturn number of existing projects
function get_project_num() public view returns (uint256){ return Project_num; }
7,222,722
/** *Submitted for verification at Etherscan.io on 2020-06-09 */ /** *Submitted for verification at Etherscan.io on 2020-06-09 */ pragma solidity ^0.5.12; /** * @title Quotation data contract * @dev Verification of quotation contract */ contract NEST_3_OfferData { mapping (address => bool) addressMapping; // Deployed quote contracts NEST_2_Mapping mappingContract; // Mapping contract /** * @dev Initialization method * @param map Mapping contract address */ constructor(address map) public{ mappingContract = NEST_2_Mapping(map); } /** * @dev Initialization method * @param map Mapping contract address */ function changeMapping(address map) public onlyOwner { mappingContract = NEST_2_Mapping(map); } /** * @dev Initialization method * @param contractAddress Address of quotation contract * @return existence of quotation contract */ function checkContract(address contractAddress) public view returns (bool){ require(contractAddress != address(0x0)); return addressMapping[contractAddress]; } /** * @dev Add quote contract address * @param contractAddress Address of quotation contract */ function addContractAddress(address contractAddress) public { require(address(mappingContract.checkAddress("offerFactory")) == msg.sender); addressMapping[contractAddress] = true; } modifier onlyOwner(){ require(mappingContract.checkOwners(msg.sender) == true); _; } } /** * @title Quotation factory * @dev Quotation mining */ contract NEST_3_OfferFactory { using SafeMath for uint256; using address_make_payable for address; mapping(address => bool) tokenAllow; // Insured mining token NEST_2_Mapping mappingContract; // Mapping contract NEST_3_OfferData dataContract; // Data contract NEST_2_OfferPrice offerPrice; // Price contract NEST_3_OrePoolLogic orePoolLogic; // Mining contract NEST_NodeAssignment NNcontract; // NestNode contract ERC20 nestToken; // nestToken address abonusAddress; // Dividend pool address coderAddress; // Developer address uint256 miningETH = 10; // Quotation mining service charge mining proportion, 10 thousandths uint256 tranEth = 2; // Service charge proportion of the bill of lading, 2 1 uint256 blockLimit = 25; // Block interval upper limit uint256 tranAddition = 2; // Transaction bonus uint256 coderAmount = 5; // Developer ratio uint256 NNAmount = 15; // Guardian node proportion uint256 otherAmount = 80; // Distributable proportion uint256 leastEth = 10 ether; // Minimum offer eth uint256 offerSpan = 10 ether; // Quotation eth span // log Personal asset contract event offerTokenContractAddress(address contractAddress); // log Quotation contract, token address, ETH quantity, erc20 quantity event offerContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount); // log Transaction, transaction initiator, transaction token address, transaction token quantity, purchase token address, purchase token quantity, traded quotation contract address, traded user address event offerTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner); /** * @dev Initialization method * @param map Mapping contract address */ constructor (address map) public { mappingContract = NEST_2_Mapping(map); offerPrice = NEST_2_OfferPrice(address(mappingContract.checkAddress("offerPrice"))); orePoolLogic = NEST_3_OrePoolLogic(address(mappingContract.checkAddress("miningCalculation"))); abonusAddress = mappingContract.checkAddress("abonus"); nestToken = ERC20(mappingContract.checkAddress("nest")); NNcontract = NEST_NodeAssignment(address(mappingContract.checkAddress("nodeAssignment"))); coderAddress = mappingContract.checkAddress("coder"); dataContract = NEST_3_OfferData(address(mappingContract.checkAddress("offerData"))); } /** * @dev Change mapping contract * @param map Mapping contract address */ function changeMapping(address map) public onlyOwner { mappingContract = NEST_2_Mapping(map); offerPrice = NEST_2_OfferPrice(address(mappingContract.checkAddress("offerPrice"))); orePoolLogic = NEST_3_OrePoolLogic(address(mappingContract.checkAddress("miningCalculation"))); abonusAddress = mappingContract.checkAddress("abonus"); nestToken = ERC20(mappingContract.checkAddress("nest")); NNcontract = NEST_NodeAssignment(address(mappingContract.checkAddress("nodeAssignment"))); coderAddress = mappingContract.checkAddress("coder"); dataContract = NEST_3_OfferData(address(mappingContract.checkAddress("offerData"))); } /** * @dev Quotation mining * @param ethAmount ETH amount * @param erc20Amount erc20 amount * @param erc20Address erc20Token address */ function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable { require(address(msg.sender) == address(tx.origin)); uint256 ethMining = ethAmount.mul(miningETH).div(1000); require(msg.value == ethAmount.add(ethMining)); require(tokenAllow[erc20Address]); createOffer(ethAmount,erc20Amount,erc20Address,ethMining); orePoolLogic.oreDrawing.value(ethMining)(erc20Address); } /** * @dev Generate quote * @param ethAmount ETH amount * @param erc20Amount erc20 amount * @param erc20Address erc20Token address * @param mining Mining Commission */ function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, uint256 mining) private { require(ethAmount >= leastEth); require(ethAmount % offerSpan == 0); require(erc20Amount % (ethAmount.div(offerSpan)) == 0); require(erc20Amount > 0); ERC20 token = ERC20(erc20Address); require(token.balanceOf(address(msg.sender)) >= erc20Amount); require(token.allowance(address(msg.sender), address(this)) >= erc20Amount); NEST_3_OfferContract newContract = new NEST_3_OfferContract(ethAmount,erc20Amount,erc20Address,mining,address(mappingContract)); dataContract.addContractAddress(address(newContract)); emit offerContractAddress(address(newContract), address(erc20Address), ethAmount, erc20Amount); token.transferFrom(address(msg.sender), address(newContract), erc20Amount); newContract.offerAssets.value(ethAmount)(); offerPrice.addPrice(ethAmount,erc20Amount,erc20Address); } /** * @dev Take out quoted assets * @param contractAddress Address of quotation contract */ function turnOut(address contractAddress) public { require(address(msg.sender) == address(tx.origin)); require(dataContract.checkContract(contractAddress)); NEST_3_OfferContract offerContract = NEST_3_OfferContract(contractAddress); offerContract.turnOut(); uint256 miningEth = offerContract.checkServiceCharge(); uint256 blockNum = offerContract.checkBlockNum(); address tokenAddress = offerContract.checkTokenAddress(); if (miningEth > 0) { uint256 miningAmount = orePoolLogic.mining(miningEth, blockNum, address(this),tokenAddress); uint256 coder = miningAmount.mul(coderAmount).div(100); uint256 NN = miningAmount.mul(NNAmount).div(100); uint256 other = miningAmount.mul(otherAmount).div(100); nestToken.transfer(address(tx.origin), other); require(nestToken.approve(address(NNcontract), NN)); NNcontract.bookKeeping(NN); nestToken.transfer(coderAddress, coder); } } /** * @dev Transfer erc20 to buy eth * @param ethAmount Offer ETH amount * @param tokenAmount Offer erc20 amount * @param contractAddress Address of quotation contract * @param tranEthAmount ETH amount of transaction * @param tranTokenAmount erc20 amount of transaction * @param tranTokenAddress erc20Token address */ function ethTran(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin)); require(dataContract.checkContract(contractAddress)); require(ethAmount >= tranEthAmount.mul(tranAddition)); uint256 serviceCharge = tranEthAmount.mul(tranEth).div(1000); require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge)); require(tranEthAmount % offerSpan == 0); createOffer(ethAmount,tokenAmount,tranTokenAddress,0); NEST_3_OfferContract offerContract = NEST_3_OfferContract(contractAddress); offerContract.changeOfferEth.value(tranEthAmount)(tranTokenAmount, tranTokenAddress); offerPrice.changePrice(tranEthAmount,tranTokenAmount,tranTokenAddress,offerContract.checkBlockNum()); emit offerTran(address(tx.origin), address(0x0), tranEthAmount,address(tranTokenAddress),tranTokenAmount,contractAddress,offerContract.checkOwner()); repayEth(abonusAddress,serviceCharge); } /** * @dev Transfer eth to buy erc20 * @param ethAmount Offer ETH amount * @param tokenAmount Offer erc20 amount * @param contractAddress Address of quotation contract * @param tranEthAmount ETH amount of transaction * @param tranTokenAmount erc20 amount of transaction * @param tranTokenAddress erc20Token address */ function ercTran(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { require(address(msg.sender) == address(tx.origin)); require(dataContract.checkContract(contractAddress)); require(ethAmount >= tranEthAmount.mul(tranAddition)); uint256 serviceCharge = tranEthAmount.mul(tranEth).div(1000); require(msg.value == ethAmount.add(serviceCharge)); require(tranEthAmount % offerSpan == 0); createOffer(ethAmount,tokenAmount,tranTokenAddress,0); NEST_3_OfferContract offerContract = NEST_3_OfferContract(contractAddress); ERC20 token = ERC20(tranTokenAddress); require(token.balanceOf(address(msg.sender)) >= tranTokenAmount); require(token.allowance(address(msg.sender), address(this)) >= tranTokenAmount); token.transferFrom(address(msg.sender), address(offerContract), tranTokenAmount); offerContract.changeOfferErc(tranEthAmount,tranTokenAmount, tranTokenAddress); offerPrice.changePrice(tranEthAmount,tranTokenAmount,tranTokenAddress,offerContract.checkBlockNum()); emit offerTran(address(tx.origin),address(tranTokenAddress),tranTokenAmount, address(0x0), tranEthAmount,contractAddress,offerContract.checkOwner()); repayEth(abonusAddress,serviceCharge); } function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } // View block interval upper limit function checkBlockLimit() public view returns(uint256) { return blockLimit; } // View quotation handling fee function checkMiningETH() public view returns (uint256) { return miningETH; } // View transaction charges function checkTranEth() public view returns (uint256) { return tranEth; } // View whether token allows mining function checkTokenAllow(address token) public view returns(bool) { return tokenAllow[token]; } // View transaction bonus function checkTranAddition() public view returns(uint256) { return tranAddition; } // View development allocation proportion function checkCoderAmount() public view returns(uint256) { return coderAmount; } // View the allocation proportion of guardian nodes function checkNNAmount() public view returns(uint256) { return NNAmount; } // View user assignable proportion function checkOtherAmount() public view returns(uint256) { return otherAmount; } // View minimum quote eth function checkleastEth() public view returns(uint256) { return leastEth; } // View quote eth span function checkOfferSpan() public view returns(uint256) { return offerSpan; } function changeMiningETH(uint256 num) public onlyOwner { miningETH = num; } function changeTranEth(uint256 num) public onlyOwner { tranEth = num; } function changeBlockLimit(uint256 num) public onlyOwner { blockLimit = num; } function changeTokenAllow(address token, bool allow) public onlyOwner { tokenAllow[token] = allow; } function changeTranAddition(uint256 num) public onlyOwner { require(num > 0); tranAddition = num; } function changeInitialRatio(uint256 coderNum, uint256 NNNum, uint256 otherNum) public onlyOwner { require(coderNum > 0 && coderNum <= 5); require(NNNum > 0 && coderNum <= 15); require(coderNum.add(NNNum).add(otherNum) == 100); coderAmount = coderNum; NNAmount = NNNum; otherAmount = otherNum; } function changeLeastEth(uint256 num) public onlyOwner { require(num > 0); leastEth = num; } function changeOfferSpan(uint256 num) public onlyOwner { require(num > 0); offerSpan = num; } modifier onlyOwner(){ require(mappingContract.checkOwners(msg.sender) == true); _; } } /** * @title Quotation contract */ contract NEST_3_OfferContract { using SafeMath for uint256; using address_make_payable for address; address owner; // Owner uint256 ethAmount; // ETH amount uint256 tokenAmount; // Token amount address tokenAddress; // Token address uint256 dealEthAmount; // Transaction eth quantity uint256 dealTokenAmount; // Transaction token quantity uint256 blockNum; // This quotation block uint256 serviceCharge; // Service Charge bool hadReceive = false; // Received NEST_2_Mapping mappingContract; // Mapping contract NEST_3_OfferFactory offerFactory; // Quotation factory /** * @dev initialization * @param _ethAmount Offer ETH amount * @param _tokenAmount Offer erc20 amount * @param _tokenAddress Token address * @param miningEth Service Charge * @param map Mapping contract */ constructor (uint256 _ethAmount, uint256 _tokenAmount, address _tokenAddress, uint256 miningEth,address map) public { mappingContract = NEST_2_Mapping(address(map)); offerFactory = NEST_3_OfferFactory(address(mappingContract.checkAddress("offerFactory"))); require(msg.sender == address(offerFactory)); owner = address(tx.origin); ethAmount = _ethAmount; tokenAmount = _tokenAmount; tokenAddress = _tokenAddress; dealEthAmount = _ethAmount; dealTokenAmount = _tokenAmount; serviceCharge = miningEth; blockNum = block.number; } function offerAssets() public payable onlyFactory { require(ERC20(tokenAddress).balanceOf(address(this)) >= tokenAmount); } function changeOfferEth(uint256 _tokenAmount, address _tokenAddress) public payable onlyFactory { require(checkContractState() == 0); require(dealEthAmount >= msg.value); require(dealTokenAmount >= _tokenAmount); require(_tokenAddress == tokenAddress); require(_tokenAmount == dealTokenAmount.mul(msg.value).div(dealEthAmount)); ERC20(tokenAddress).transfer(address(tx.origin), _tokenAmount); dealEthAmount = dealEthAmount.sub(msg.value); dealTokenAmount = dealTokenAmount.sub(_tokenAmount); } function changeOfferErc(uint256 _ethAmount, uint256 _tokenAmount, address _tokenAddress) public onlyFactory { require(checkContractState() == 0); require(dealEthAmount >= _ethAmount); require(dealTokenAmount >= _tokenAmount); require(_tokenAddress == tokenAddress); require(_tokenAmount == dealTokenAmount.mul(_ethAmount).div(dealEthAmount)); repayEth(address(tx.origin), _ethAmount); dealEthAmount = dealEthAmount.sub(_ethAmount); dealTokenAmount = dealTokenAmount.sub(_tokenAmount); } function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } function turnOut() public onlyFactory { require(address(tx.origin) == owner); require(checkContractState() == 1); require(hadReceive == false); uint256 ethAssets; uint256 tokenAssets; (ethAssets, tokenAssets,) = checkAssets(); repayEth(owner, ethAssets); ERC20(address(tokenAddress)).transfer(owner, tokenAssets); hadReceive = true; } function checkContractState() public view returns (uint256) { if (block.number.sub(blockNum) > offerFactory.checkBlockLimit()) { return 1; } return 0; } function checkDealAmount() public view returns(uint256 leftEth, uint256 leftErc20, address erc20Address) { return (dealEthAmount, dealTokenAmount, tokenAddress); } function checkPrice() public view returns(uint256 _ethAmount, uint256 _tokenAmount, address _tokenAddress) { return (ethAmount, tokenAmount, tokenAddress); } function checkAssets() public view returns(uint256 _ethAmount, uint256 _tokenAmount, address _tokenAddress) { return (address(this).balance, ERC20(address(tokenAddress)).balanceOf(address(this)), address(tokenAddress)); } function checkTokenAddress() public view returns(address){ return tokenAddress; } function checkOwner() public view returns(address) { return owner; } function checkBlockNum() public view returns (uint256) { return blockNum; } function checkServiceCharge() public view returns(uint256) { return serviceCharge; } function checkHadReceive() public view returns(bool) { return hadReceive; } modifier onlyFactory(){ require(msg.sender == address(mappingContract.checkAddress("offerFactory"))); _; } } /** * @title Price contract */ contract NEST_2_OfferPrice{ using SafeMath for uint256; using address_make_payable for address; NEST_2_Mapping mappingContract; // Mapping contract NEST_3_OfferFactory offerFactory; // Quotation factory contract struct Price { // Price structure uint256 ethAmount; // ETH amount uint256 erc20Amount; // erc20 amount uint256 blockNum; // Last quotation block number, current price block } struct addressPrice { // Token price information structure mapping(uint256 => Price) tokenPrice; // Token price, Block number = > price Price latestPrice; // Latest price } mapping(address => addressPrice) tokenInfo; // Token price information uint256 priceCost = 0.01 ether; // Price charge uint256 priceCostUser = 2; // Price expense user proportion uint256 priceCostAbonus = 8; // Proportion of price expense dividend pool mapping(uint256 => mapping(address => address)) blockAddress; // Last person of block quotation address abonusAddress; // Dividend pool // Real time price toekn, ETH quantity, erc20 quantity event nowTokenPrice(address a, uint256 b, uint256 c); /** * @dev Initialization method * @param map Mapping contract address */ constructor (address map) public { mappingContract = NEST_2_Mapping(address(map)); offerFactory = NEST_3_OfferFactory(address(mappingContract.checkAddress("offerFactory"))); abonusAddress = address(mappingContract.checkAddress("abonus")); } /** * @dev Initialization method * @param map Mapping contract address */ function changeMapping(address map) public onlyOwner { mappingContract = NEST_2_Mapping(map); offerFactory = NEST_3_OfferFactory(address(mappingContract.checkAddress("offerFactory"))); abonusAddress = address(mappingContract.checkAddress("abonus")); } /** * @dev Increase price * @param _ethAmount ETH amount * @param _tokenAmount Token amount * @param _tokenAddress Token address */ function addPrice(uint256 _ethAmount, uint256 _tokenAmount, address _tokenAddress) public onlyFactory { uint256 blockLimit = offerFactory.checkBlockLimit(); uint256 middleBlock = block.number.sub(blockLimit); uint256 priceBlock = tokenInfo[_tokenAddress].latestPrice.blockNum; while(priceBlock >= middleBlock || tokenInfo[_tokenAddress].tokenPrice[priceBlock].ethAmount == 0){ priceBlock = tokenInfo[_tokenAddress].tokenPrice[priceBlock].blockNum; if (priceBlock == 0) { break; } } tokenInfo[_tokenAddress].latestPrice.ethAmount = tokenInfo[_tokenAddress].tokenPrice[priceBlock].ethAmount; tokenInfo[_tokenAddress].latestPrice.erc20Amount = tokenInfo[_tokenAddress].tokenPrice[priceBlock].erc20Amount; tokenInfo[_tokenAddress].tokenPrice[block.number].ethAmount = tokenInfo[_tokenAddress].tokenPrice[block.number].ethAmount.add(_ethAmount); // 11eth1 tokenInfo[_tokenAddress].tokenPrice[block.number].erc20Amount = tokenInfo[_tokenAddress].tokenPrice[block.number].erc20Amount.add(_tokenAmount); // 11ercrc201 if (tokenInfo[_tokenAddress].latestPrice.blockNum != block.number) { tokenInfo[_tokenAddress].tokenPrice[block.number].blockNum = tokenInfo[_tokenAddress].latestPrice.blockNum; // 1111111111 tokenInfo[_tokenAddress].latestPrice.blockNum = block.number; // 111111111 } blockAddress[block.number][_tokenAddress] = address(tx.origin); emit nowTokenPrice(_tokenAddress,tokenInfo[_tokenAddress].latestPrice.ethAmount, tokenInfo[_tokenAddress].latestPrice.erc20Amount); } /** * @dev Update price * @param _tokenAddress Token address * @return ethAmount ETH amount * @return erc20Amount Token amount * @return token Token address */ function updateAndCheckPriceNow(address _tokenAddress) public payable returns(uint256 ethAmount, uint256 erc20Amount, address token) { if (msg.sender != tx.origin && msg.sender != address(offerFactory)) { require(msg.value == priceCost); } uint256 blockLimit = offerFactory.checkBlockLimit(); uint256 middleBlock = block.number.sub(blockLimit); uint256 priceBlock = tokenInfo[_tokenAddress].latestPrice.blockNum; while(priceBlock >= middleBlock || tokenInfo[_tokenAddress].tokenPrice[priceBlock].ethAmount == 0){ priceBlock = tokenInfo[_tokenAddress].tokenPrice[priceBlock].blockNum; if (priceBlock == 0) { break; } } tokenInfo[_tokenAddress].latestPrice.ethAmount = tokenInfo[_tokenAddress].tokenPrice[priceBlock].ethAmount; tokenInfo[_tokenAddress].latestPrice.erc20Amount = tokenInfo[_tokenAddress].tokenPrice[priceBlock].erc20Amount; if (msg.value > 0) { repayEth(abonusAddress, msg.value.mul(priceCostAbonus).div(10)); repayEth(blockAddress[priceBlock][_tokenAddress], msg.value.mul(priceCostUser).div(10)); } return (tokenInfo[_tokenAddress].latestPrice.ethAmount,tokenInfo[_tokenAddress].latestPrice.erc20Amount, _tokenAddress); } function repayEth(address accountAddress, uint256 asset) private { address payable addr = accountAddress.make_payable(); addr.transfer(asset); } /** * @dev Change price * @param _ethAmount ETH amount * @param _tokenAmount Token amount * @param _tokenAddress Token address * @param blockNum Block number */ function changePrice(uint256 _ethAmount, uint256 _tokenAmount, address _tokenAddress, uint256 blockNum) public onlyFactory { tokenInfo[_tokenAddress].tokenPrice[blockNum].ethAmount = tokenInfo[_tokenAddress].tokenPrice[blockNum].ethAmount.sub(_ethAmount); tokenInfo[_tokenAddress].tokenPrice[blockNum].erc20Amount = tokenInfo[_tokenAddress].tokenPrice[blockNum].erc20Amount.sub(_tokenAmount); } function checkPriceForBlock(address tokenAddress, uint256 blockNum) public view returns (uint256 ethAmount, uint256 erc20Amount, uint256 frontBlock) { require(msg.sender == tx.origin); return (tokenInfo[tokenAddress].tokenPrice[blockNum].ethAmount, tokenInfo[tokenAddress].tokenPrice[blockNum].erc20Amount,tokenInfo[tokenAddress].tokenPrice[blockNum].blockNum); } function checkPriceNow(address tokenAddress) public view returns (uint256 ethAmount, uint256 erc20Amount,uint256 frontBlock) { require(msg.sender == tx.origin); return (tokenInfo[tokenAddress].latestPrice.ethAmount,tokenInfo[tokenAddress].latestPrice.erc20Amount,tokenInfo[tokenAddress].latestPrice.blockNum); } function checkPriceHistoricalAverage(address tokenAddress, uint256 blockNum) public view returns (uint256) { require(msg.sender == tx.origin); uint256 blockLimit = offerFactory.checkBlockLimit(); uint256 middleBlock = block.number.sub(blockLimit); uint256 priceBlock = tokenInfo[tokenAddress].latestPrice.blockNum; while(priceBlock >= middleBlock){ priceBlock = tokenInfo[tokenAddress].tokenPrice[priceBlock].blockNum; if (priceBlock == 0) { break; } } uint256 frontBlock = priceBlock; uint256 price = 0; uint256 priceTimes = 0; while(frontBlock >= blockNum){ uint256 erc20Amount = tokenInfo[tokenAddress].tokenPrice[frontBlock].erc20Amount; uint256 ethAmount = tokenInfo[tokenAddress].tokenPrice[frontBlock].ethAmount; price = price.add(erc20Amount.mul(1 ether).div(ethAmount)); priceTimes = priceTimes.add(1); frontBlock = tokenInfo[tokenAddress].tokenPrice[frontBlock].blockNum; if (frontBlock == 0) { break; } } return price.div(priceTimes); } function checkPriceForBlockPay(address tokenAddress, uint256 blockNum) public payable returns (uint256 ethAmount, uint256 erc20Amount, uint256 frontBlock) { require(msg.value == priceCost); require(tokenInfo[tokenAddress].tokenPrice[blockNum].ethAmount != 0); repayEth(abonusAddress, msg.value.mul(priceCostAbonus).div(10)); repayEth(blockAddress[blockNum][tokenAddress], msg.value.mul(priceCostUser).div(10)); return (tokenInfo[tokenAddress].tokenPrice[blockNum].ethAmount, tokenInfo[tokenAddress].tokenPrice[blockNum].erc20Amount,tokenInfo[tokenAddress].tokenPrice[blockNum].blockNum); } function checkPriceHistoricalAveragePay(address tokenAddress, uint256 blockNum) public payable returns (uint256) { require(msg.value == priceCost); uint256 blockLimit = offerFactory.checkBlockLimit(); uint256 middleBlock = block.number.sub(blockLimit); uint256 priceBlock = tokenInfo[tokenAddress].latestPrice.blockNum; while(priceBlock >= middleBlock){ priceBlock = tokenInfo[tokenAddress].tokenPrice[priceBlock].blockNum; if (priceBlock == 0) { break; } } repayEth(abonusAddress, msg.value.mul(priceCostAbonus).div(10)); repayEth(blockAddress[priceBlock][tokenAddress], msg.value.mul(priceCostUser).div(10)); uint256 frontBlock = priceBlock; uint256 price = 0; uint256 priceTimes = 0; while(frontBlock >= blockNum){ uint256 erc20Amount = tokenInfo[tokenAddress].tokenPrice[frontBlock].erc20Amount; uint256 ethAmount = tokenInfo[tokenAddress].tokenPrice[frontBlock].ethAmount; price = price.add(erc20Amount.mul(1 ether).div(ethAmount)); priceTimes = priceTimes.add(1); frontBlock = tokenInfo[tokenAddress].tokenPrice[frontBlock].blockNum; if (frontBlock == 0) { break; } } return price.div(priceTimes); } function checkLatestBlock(address token) public view returns(uint256) { return tokenInfo[token].latestPrice.blockNum; } function changePriceCost(uint256 amount) public onlyOwner { require(amount > 0); priceCost = amount; } function checkPriceCost() public view returns(uint256) { return priceCost; } function changePriceCostProportion(uint256 user, uint256 abonus) public onlyOwner { require(user.add(abonus) == 10); priceCostUser = user; priceCostAbonus = abonus; } function checkPriceCostProportion() public view returns(uint256 user, uint256 abonus) { return (priceCostUser, priceCostAbonus); } modifier onlyFactory(){ require(msg.sender == address(mappingContract.checkAddress("offerFactory"))); _; } modifier onlyOwner(){ require(mappingContract.checkOwners(msg.sender) == true); _; } } contract NEST_NodeAssignment { function bookKeeping(uint256 amount) public; } contract NEST_3_OrePoolLogic { function oreDrawing(address token) public payable; function mining(uint256 amount, uint256 blockNum, address target, address token) public returns(uint256); } contract NEST_2_Mapping { function checkAddress(string memory name) public view returns (address contractAddress); function checkOwners(address man) public view returns (bool); } library address_make_payable { function make_payable(address x) internal pure returns (address payable) { return address(uint160(x)); } } contract ERC20 { function totalSupply() public view returns (uint supply); function balanceOf( address who ) public view returns (uint value); function allowance( address owner, address spender ) public view returns (uint _allowance); function transfer( address to, uint256 value) external; function transferFrom( address from, address to, uint value) public; function approve( address spender, uint value ) public returns (bool ok); event Transfer( address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
Increase price _ethAmount ETH amount _tokenAmount Token amount _tokenAddress Token address/
function addPrice(uint256 _ethAmount, uint256 _tokenAmount, address _tokenAddress) public onlyFactory { uint256 blockLimit = offerFactory.checkBlockLimit(); uint256 middleBlock = block.number.sub(blockLimit); uint256 priceBlock = tokenInfo[_tokenAddress].latestPrice.blockNum; while(priceBlock >= middleBlock || tokenInfo[_tokenAddress].tokenPrice[priceBlock].ethAmount == 0){ priceBlock = tokenInfo[_tokenAddress].tokenPrice[priceBlock].blockNum; if (priceBlock == 0) { break; } } tokenInfo[_tokenAddress].latestPrice.ethAmount = tokenInfo[_tokenAddress].tokenPrice[priceBlock].ethAmount; tokenInfo[_tokenAddress].latestPrice.erc20Amount = tokenInfo[_tokenAddress].tokenPrice[priceBlock].erc20Amount; while(priceBlock >= middleBlock || tokenInfo[_tokenAddress].tokenPrice[priceBlock].ethAmount == 0){ priceBlock = tokenInfo[_tokenAddress].tokenPrice[priceBlock].blockNum; if (priceBlock == 0) { break; } } tokenInfo[_tokenAddress].latestPrice.ethAmount = tokenInfo[_tokenAddress].tokenPrice[priceBlock].ethAmount; tokenInfo[_tokenAddress].latestPrice.erc20Amount = tokenInfo[_tokenAddress].tokenPrice[priceBlock].erc20Amount; if (tokenInfo[_tokenAddress].latestPrice.blockNum != block.number) { } blockAddress[block.number][_tokenAddress] = address(tx.origin); emit nowTokenPrice(_tokenAddress,tokenInfo[_tokenAddress].latestPrice.ethAmount, tokenInfo[_tokenAddress].latestPrice.erc20Amount); }
12,642,496
./full_match/1/0x591C4ABF20f61A8b0Ee06A5a2d2D2337241FE970/sources/contracts/SafEth/SafEth.sol
- stakes into all derivatives _minOut - minimum amount of safEth to receive or revert price - price safEth price passed from approxPrice() return mintedAmount - amount of safEth token minted/
function doMultiStake( uint256 _minOut, uint256 price ) private returns (uint256 mintedAmount) { if (enabledDerivativeCount == 0) revert NoEnabledDerivatives(); uint256 totalStakeValueEth = 0; uint256 amountStaked = 0; for (uint256 i = 0; i < enabledDerivativeCount; i++) { uint256 index = enabledDerivatives[i]; uint256 weight = derivatives[index].weight; if (weight == 0) continue; IDerivative derivative = derivatives[index].derivative; uint256 ethAmount = i == enabledDerivativeCount - 1 ? msg.value - amountStaked : (msg.value * weight) / totalWeight; amountStaked += ethAmount; uint256 derivativeReceivedEthValue = (derivative.ethPerDerivative( true ) * depositAmount); totalStakeValueEth += derivativeReceivedEthValue; } mintedAmount = (totalStakeValueEth) / price; if (mintedAmount < _minOut) revert MintedAmountTooLow(); _mint(msg.sender, mintedAmount); emit Staked( msg.sender, msg.value, totalStakeValueEth / 1e18, price, false ); }
3,148,267
./full_match/1/0x4a7285cB7Ddcc9Ca37b152fac8B868411bC66bd1/sources/contracts/ponzai_test.sol
Function to update the maximum transaction amount, only callable by the contract owner.
function setMaxTxAmount(uint256 _maxTxAmount) public onlyOwner { maxTxAmount = _maxTxAmount; }
2,897,781
/** *Submitted for verification at Etherscan.io on 2021-09-20 */ // SPDX-License-Identifier: NONE pragma solidity 0.7.6; // Part: IERC20Permit /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // Part: LixirErrors library LixirErrors { function require_INSUFFICIENT_BALANCE(bool cond) internal pure { require(cond, 'INSUFFICIENT_BALANCE'); } function require_INSUFFICIENT_ALLOWANCE(bool cond) internal pure { require(cond, 'INSUFFICIENT_ALLOWANCE'); } function require_PERMIT_EXPIRED(bool cond) internal pure { require(cond, 'PERMIT_EXPIRED'); } function require_INVALID_SIGNATURE(bool cond) internal pure { require(cond, 'INVALID_SIG'); } function require_XFER_ZERO_ADDRESS(bool cond) internal pure { require(cond, 'XFER_ZERO_ADDRESS'); } function require_INSUFFICIENT_INPUT_AMOUNT(bool cond) internal pure { require(cond, 'INSUFFICIENT_INPUT_AMOUNT'); } function require_INSUFFICIENT_OUTPUT_AMOUNT(bool cond) internal pure { require(cond, 'INSUFFICIENT_OUTPUT_AMOUNT'); } function require_INSUFFICIENT_ETH(bool cond) internal pure { require(cond, 'INSUFFICIENT_ETH'); } function require_MAX_SUPPLY(bool cond) internal pure { require(cond, 'MAX_SUPPLY'); } } // Part: LixirRoles library LixirRoles { bytes32 constant gov_role = keccak256('v1_gov_role'); bytes32 constant delegate_role = keccak256('v1_delegate_role'); bytes32 constant vault_role = keccak256('v1_vault_role'); bytes32 constant strategist_role = keccak256('v1_strategist_role'); bytes32 constant pauser_role = keccak256('v1_pauser_role'); bytes32 constant keeper_role = keccak256('v1_keeper_role'); bytes32 constant deployer_role = keccak256('v1_deployer_role'); bytes32 constant strategy_role = keccak256('v1_strategy_role'); bytes32 constant vault_implementation_role = keccak256('v1_vault_implementation_role'); bytes32 constant eth_vault_implementation_role = keccak256('v1_eth_vault_implementation_role'); bytes32 constant factory_role = keccak256('v1_factory_role'); bytes32 constant fee_setter_role = keccak256('fee_setter_role'); } // Part: OpenZeppelin/[email protected]/Address /** * @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); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @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; } } // Part: OpenZeppelin/[email protected]/EnumerableSet /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: SafeCast /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y); } function abs(int256 y) internal pure returns (uint256 z) { z = y < 0 ? uint256(-y) : uint256(y); } } // Part: Uniswap/[email protected]/FixedPoint128 /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // Part: Uniswap/[email protected]/FixedPoint96 /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // Part: Uniswap/[email protected]/FullMath /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // Part: Uniswap/[email protected]/IUniswapV3MintCallback /// @title Callback for IUniswapV3PoolActions#mint /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; } // Part: Uniswap/[email protected]/IUniswapV3PoolActions /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // Part: Uniswap/[email protected]/IUniswapV3PoolDerivedState /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // Part: Uniswap/[email protected]/IUniswapV3PoolEvents /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // Part: Uniswap/[email protected]/IUniswapV3PoolImmutables /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // Part: Uniswap/[email protected]/IUniswapV3PoolOwnerActions /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // Part: Uniswap/[email protected]/IUniswapV3PoolState /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // Part: Uniswap/[email protected]/LowGasSafeMath /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // Part: Uniswap/[email protected]/TickMath /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // Part: Uniswap/[email protected]/UnsafeMath /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } // Part: Uniswap/[email protected]/PoolAddress /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // Part: Uniswap/[email protected]/PositionKey library PositionKey { /// @dev Returns the key of the position in the core library function compute( address owner, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, tickLower, tickUpper)); } } // Part: Uniswap/[email protected]/TransferHelper library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // Part: ILixirVaultToken interface ILixirVaultToken is IERC20, IERC20Permit {} // Part: OpenZeppelin/[email protected]/AccessControl /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // Part: OpenZeppelin/[email protected]/Initializable /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // Part: OpenZeppelin/[email protected]/Pausable /** * @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()); } } // Part: SqrtPriceMath /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } /// @notice Gets the next sqrt price given an input amount of token0 or token1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of token0, or token1, is being swapped in /// @param zeroForOne Whether the amount in is token0 or token1 /// @return sqrtQX96 The price after adding the input amount to token0 or token1 function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of token0 or token1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of token0, or token1, is being swapped out /// @param zeroForOne Whether the amount out is token0 or token1 /// @return sqrtQX96 The price after removing the output amount of token0 or token1 function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Helper that gets signed token0 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { return liquidity < 0 ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } /// @notice Helper that gets signed token1 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { return liquidity < 0 ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } } // Part: Uniswap/[email protected]/IUniswapV3Pool /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // Part: Uniswap/[email protected]/IWETH9 /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // Part: Uniswap/[email protected]/LiquidityAmounts /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // Part: EIP712Initializable /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Initializable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; constructor(string memory version) { _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); } /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712__initialize(string memory name) internal initializer { _HASHED_NAME = keccak256(bytes(name)); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256( abi.encode( _TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked('\x19\x01', _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // Part: ILixirVault interface ILixirVault is ILixirVaultToken { function initialize( string memory name, string memory symbol, address _token0, address _token1, address _strategist, address _keeper, address _strategy ) external; function token0() external view returns (IERC20); function token1() external view returns (IERC20); function activeFee() external view returns (uint24); function activePool() external view returns (IUniswapV3Pool); function strategist() external view returns (address); function strategy() external view returns (address); function keeper() external view returns (address); function setKeeper(address _keeper) external; function setStrategist(address _strategist) external; function setStrategy(address _strategy) external; function setPerformanceFee(uint24 newFee) external; function emergencyExit() external; function unpause() external; function mainPosition() external view returns (int24 tickLower, int24 tickUpper); function rangePosition() external view returns (int24 tickLower, int24 tickUpper); function rebalance( int24 mainTickLower, int24 mainTickUpper, int24 rangeTickLower0, int24 rangeTickUpper0, int24 rangeTickLower1, int24 rangeTickUpper1, uint24 fee ) external; function withdraw( uint256 shares, uint256 amount0Min, uint256 amount1Min, address receiver, uint256 deadline ) external returns (uint256 amount0Out, uint256 amount1Out); function withdrawFrom( address withdrawer, uint256 shares, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external returns (uint256 amount0Out, uint256 amount1Out); function deposit( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external returns ( uint256 shares, uint256 amount0, uint256 amount1 ); function calculateTotalsFromTick(int24 virtualTick) external view returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ); } // Part: LixirRegistry /** @notice an access control contract with roles used to handle permissioning throughout the `Vault` and `Strategy` contracts. */ contract LixirRegistry is AccessControl { address public immutable uniV3Factory; IWETH9 public immutable weth9; /// king bytes32 public constant gov_role = keccak256('v1_gov_role'); /// same privileges as `gov_role` bytes32 public constant delegate_role = keccak256('v1_delegate_role'); /// configuring options within the strategy contract & vault bytes32 public constant strategist_role = keccak256('v1_strategist_role'); /// can `emergencyExit` a vault bytes32 public constant pauser_role = keccak256('v1_pauser_role'); /// can `rebalance` the vault via the strategy contract bytes32 public constant keeper_role = keccak256('v1_keeper_role'); /// can `createVault`s from the factory contract bytes32 public constant deployer_role = keccak256('v1_deployer_role'); /// verified vault in the registry bytes32 public constant vault_role = keccak256('v1_vault_role'); /// can initialize vaults bytes32 public constant strategy_role = keccak256('v1_strategy_role'); bytes32 public constant vault_implementation_role = keccak256('v1_vault_implementation_role'); bytes32 public constant eth_vault_implementation_role = keccak256('v1_eth_vault_implementation_role'); /// verified vault factory in the registry bytes32 public constant factory_role = keccak256('v1_factory_role'); /// can `setPerformanceFee` on a vault bytes32 public constant fee_setter_role = keccak256('fee_setter_role'); address public feeTo; address public emergencyReturn; uint24 public constant PERFORMANCE_FEE_PRECISION = 1e6; event FeeToChanged(address indexed previousFeeTo, address indexed newFeeTo); event EmergencyReturnChanged( address indexed previousEmergencyReturn, address indexed newEmergencyReturn ); constructor( address _governance, address _delegate, address _uniV3Factory, address _weth9 ) { uniV3Factory = _uniV3Factory; weth9 = IWETH9(_weth9); _setupRole(gov_role, _governance); _setupRole(delegate_role, _delegate); // gov is its own admin _setRoleAdmin(gov_role, gov_role); _setRoleAdmin(delegate_role, gov_role); _setRoleAdmin(strategist_role, delegate_role); _setRoleAdmin(fee_setter_role, delegate_role); _setRoleAdmin(pauser_role, delegate_role); _setRoleAdmin(keeper_role, delegate_role); _setRoleAdmin(deployer_role, delegate_role); _setRoleAdmin(factory_role, delegate_role); _setRoleAdmin(strategy_role, delegate_role); _setRoleAdmin(vault_implementation_role, delegate_role); _setRoleAdmin(eth_vault_implementation_role, delegate_role); _setRoleAdmin(vault_role, factory_role); } function addRole(bytes32 role, bytes32 roleAdmin) public { require(isGovOrDelegate(msg.sender)); require(getRoleAdmin(role) == bytes32(0) && getRoleMemberCount(role) == 0); _setRoleAdmin(role, roleAdmin); } function isGovOrDelegate(address account) public view returns (bool) { return hasRole(gov_role, account) || hasRole(delegate_role, account); } function setFeeTo(address _feeTo) external { require(isGovOrDelegate(msg.sender)); address previous = feeTo; feeTo = _feeTo; emit FeeToChanged(previous, _feeTo); } function setEmergencyReturn(address _emergencyReturn) external { require(isGovOrDelegate(msg.sender)); address previous = emergencyReturn; emergencyReturn = _emergencyReturn; emit EmergencyReturnChanged(previous, _emergencyReturn); } } // Part: ILixirVaultETH interface ILixirVaultETH is ILixirVault { enum TOKEN {ZERO, ONE} function WETH_TOKEN() external view returns (TOKEN); function depositETH( uint256 amountDesired, uint256 amountEthMin, uint256 amountMin, address recipient, uint256 deadline ) external payable returns ( uint256 shares, uint256 amountEthIn, uint256 amountIn ); function withdrawETHFrom( address withdrawer, uint256 shares, uint256 amountEthMin, uint256 amountMin, address payable recipient, uint256 deadline ) external returns (uint256 amountEthOut, uint256 amountOut); function withdrawETH( uint256 shares, uint256 amountEthMin, uint256 amountMin, address payable recipient, uint256 deadline ) external returns (uint256 amountEthOut, uint256 amountOut); receive() external payable; } // Part: LixirBase /** @notice An abstract contract that gives access to the registry and contains common modifiers for restricting access to functions based on role. */ abstract contract LixirBase { LixirRegistry public immutable registry; constructor(address _registry) { registry = LixirRegistry(_registry); } modifier onlyRole(bytes32 role) { require(registry.hasRole(role, msg.sender)); _; } modifier onlyGovOrDelegate { require(registry.isGovOrDelegate(msg.sender)); _; } modifier hasRole(bytes32 role, address account) { require(registry.hasRole(role, account)); _; } } // Part: LixirVaultToken /** * @title Highly opinionated token implementation * @author Balancer Labs * @dev * - Includes functions to increase and decrease allowance as a workaround * for the well-known issue with `approve`: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not * decreased by calls to transferFrom * - Lets a token holder use `transferFrom` to send their own tokens, * without first setting allowance * - Emits 'Approval' events whenever allowance is changed by `transferFrom` */ contract LixirVaultToken is ILixirVaultToken, EIP712Initializable { using SafeMath for uint256; // State variables uint8 private constant _DECIMALS = 18; mapping(address => uint256) private _balance; mapping(address => mapping(address => uint256)) _allowance; uint256 private _totalSupply; string private _name; string private _symbol; mapping(address => uint256) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPE_HASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); constructor() EIP712Initializable('1') {} // Function declarations function __LixirVaultToken__initialize( string memory tokenName, string memory tokenSymbol ) internal initializer { __EIP712__initialize(tokenName); _name = tokenName; _symbol = tokenSymbol; } // External functions function allowance(address owner, address spender) public view override returns (uint256) { return _allowance[owner][spender]; } function balanceOf(address account) external view override returns (uint256) { return _balance[account]; } function approve(address spender, uint256 amount) external override returns (bool) { _setAllowance(msg.sender, spender, amount); return true; } function increaseApproval(address spender, uint256 amount) external returns (bool) { _setAllowance( msg.sender, spender, _allowance[msg.sender][spender].add(amount) ); return true; } function decreaseApproval(address spender, uint256 amount) external returns (bool) { uint256 currentAllowance = _allowance[msg.sender][spender]; if (amount >= currentAllowance) { _setAllowance(msg.sender, spender, 0); } else { _setAllowance(msg.sender, spender, currentAllowance.sub(amount)); } return true; } function transfer(address recipient, uint256 amount) external override returns (bool) { _move(msg.sender, recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { uint256 currentAllowance = _allowance[sender][msg.sender]; LixirErrors.require_INSUFFICIENT_ALLOWANCE( msg.sender == sender || currentAllowance >= amount ); _move(sender, recipient, amount); if (msg.sender != sender && currentAllowance != type(uint256).max) { // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount _setAllowance(sender, msg.sender, currentAllowance - amount); } return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time LixirErrors.require_PERMIT_EXPIRED(block.timestamp <= deadline); uint256 nonce = _nonces[owner]; bytes32 structHash = keccak256( abi.encode(_PERMIT_TYPE_HASH, owner, spender, value, nonce, deadline) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ecrecover(hash, v, r, s); LixirErrors.require_INVALID_SIGNATURE( signer != address(0) && signer == owner ); _nonces[owner] = nonce + 1; _setAllowance(owner, spender, value); } // Public functions function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _DECIMALS; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function nonces(address owner) external view override returns (uint256) { return _nonces[owner]; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } // Internal functions function _beforeMintCallback(address recipient, uint256 amount) internal virtual {} function _mintPoolTokens(address recipient, uint256 amount) internal { _beforeMintCallback(recipient, amount); _balance[recipient] = _balance[recipient].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0), recipient, amount); } function _burnPoolTokens(address sender, uint256 amount) internal { uint256 currentBalance = _balance[sender]; LixirErrors.require_INSUFFICIENT_BALANCE(currentBalance >= amount); _balance[sender] = currentBalance - amount; _totalSupply = _totalSupply.sub(amount); emit Transfer(sender, address(0), amount); } function _move( address sender, address recipient, uint256 amount ) internal { uint256 currentBalance = _balance[sender]; LixirErrors.require_INSUFFICIENT_BALANCE(currentBalance >= amount); // Prohibit transfers to the zero address to avoid confusion with the // Transfer event emitted by `_burnPoolTokens` LixirErrors.require_XFER_ZERO_ADDRESS(recipient != address(0)); _balance[sender] = currentBalance - amount; _balance[recipient] = _balance[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _setAllowance( address owner, address spender, uint256 amount ) internal { _allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } } // Part: LixirVault contract LixirVault is ILixirVault, LixirVaultToken, LixirBase, IUniswapV3MintCallback, Pausable { using LowGasSafeMath for uint256; using SafeCast for uint256; using SafeCast for int256; using SafeCast for uint128; IERC20 public override token0; IERC20 public override token1; uint24 public override activeFee; IUniswapV3Pool public override activePool; address public override strategy; address public override strategist; address public override keeper; Position public override mainPosition; Position public override rangePosition; uint24 public performanceFee; uint24 immutable PERFORMANCE_FEE_PRECISION; address immutable uniV3Factory; event Deposit( address indexed depositor, address indexed recipient, uint256 shares, uint256 amount0In, uint256 amount1In, uint256 total0, uint256 total1 ); event Withdraw( address indexed withdrawer, address indexed recipient, uint256 shares, uint256 amount0Out, uint256 amount1Out ); event Rebalance( int24 mainTickLower, int24 mainTickUpper, int24 rangeTickLower, int24 rangeTickUpper, uint24 newFee, uint256 total0, uint256 total1 ); event PerformanceFeeSet(uint24 oldFee, uint24 newFee); event StrategySet(address oldStrategy, address newStrategy); struct DepositPositionData { uint128 LDelta; int24 tickLower; int24 tickUpper; } enum POSITION {MAIN, RANGE} // details about the uniswap position struct Position { // the tick range of the position int24 tickLower; int24 tickUpper; } constructor(address _registry) LixirBase(_registry) { PERFORMANCE_FEE_PRECISION = LixirRegistry(_registry) .PERFORMANCE_FEE_PRECISION(); uniV3Factory = LixirRegistry(_registry).uniV3Factory(); } /** @notice sets fields in the contract and initializes the `LixirVaultToken` */ function initialize( string memory name, string memory symbol, address _token0, address _token1, address _strategist, address _keeper, address _strategy ) public virtual override hasRole(LixirRoles.strategist_role, _strategist) hasRole(LixirRoles.keeper_role, _keeper) hasRole(LixirRoles.strategy_role, _strategy) initializer { require(_token0 < _token1); __LixirVaultToken__initialize(name, symbol); token0 = IERC20(_token0); token1 = IERC20(_token1); strategist = _strategist; keeper = _keeper; strategy = _strategy; } modifier onlyStrategist() { require(msg.sender == strategist); _; } modifier onlyStrategy() { require(msg.sender == strategy); _; } modifier notExpired(uint256 deadline) { require(block.timestamp <= deadline, 'Expired'); _; } /** @dev calculates shares, totals, etc. to mint the proper amount of `LixirVaultToken`s to `recipient` */ function _depositStepOne( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient ) internal returns ( DepositPositionData memory mainData, DepositPositionData memory rangeData, uint256 shares, uint256 amount0In, uint256 amount1In, uint256 total0, uint256 total1 ) { uint256 _totalSupply = totalSupply(); mainData = DepositPositionData({ LDelta: 0, tickLower: mainPosition.tickLower, tickUpper: mainPosition.tickUpper }); rangeData = DepositPositionData({ LDelta: 0, tickLower: rangePosition.tickLower, tickUpper: rangePosition.tickUpper }); if (_totalSupply == 0) { (shares, mainData.LDelta, amount0In, amount1In) = calculateInitialDeposit( amount0Desired, amount1Desired ); total0 = amount0In; total1 = amount1In; } else { uint128 mL; uint128 rL; { (uint160 sqrtRatioX96, int24 tick) = getSqrtRatioX96AndTick(); (total0, total1, mL, rL) = _calculateTotals( sqrtRatioX96, tick, mainData, rangeData ); } (shares, amount0In, amount1In) = calcSharesAndAmounts( amount0Desired, amount1Desired, total0, total1, _totalSupply ); mainData.LDelta = uint128(FullMath.mulDiv(mL, shares, _totalSupply)); rangeData.LDelta = uint128(FullMath.mulDiv(rL, shares, _totalSupply)); } LixirErrors.require_INSUFFICIENT_OUTPUT_AMOUNT( amount0Min <= amount0In && amount1Min <= amount1In ); _mintPoolTokens(recipient, shares); } /** @dev this function deposits the tokens into the UniV3 pool */ function _depositStepTwo( DepositPositionData memory mainData, DepositPositionData memory rangeData, address recipient, uint256 shares, uint256 amount0In, uint256 amount1In, uint256 total0, uint256 total1 ) internal { uint128 mLDelta = mainData.LDelta; if (0 < mLDelta) { activePool.mint( address(this), mainData.tickLower, mainData.tickUpper, mLDelta, '' ); } uint128 rLDelta = rangeData.LDelta; if (0 < rLDelta) { activePool.mint( address(this), rangeData.tickLower, rangeData.tickUpper, rLDelta, '' ); } emit Deposit( address(msg.sender), address(recipient), shares, amount0In, amount1In, total0, total1 ); } /** @notice deposit's the callers ERC20 tokens into the vault, mints them `LixirVaultToken`s, and adds their liquidity to the UniswapV3 pool. @param amount0Desired Amount of token 0 desired by user @param amount1Desired Amount of token 1 desired by user @param amount0Min Minimum amount of token 0 desired by user @param amount1Min Minimum amount of token 1 desired by user @param recipient The address for which the liquidity will be created @param deadline Blocktimestamp that this must execute before @return shares @return amount0In how much token0 was actually deposited @return amount1In how much token1 was actually deposited */ function deposit( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external override whenNotPaused notExpired(deadline) returns ( uint256 shares, uint256 amount0In, uint256 amount1In ) { DepositPositionData memory mainData; DepositPositionData memory rangeData; uint256 total0; uint256 total1; ( mainData, rangeData, shares, amount0In, amount1In, total0, total1 ) = _depositStepOne( amount0Desired, amount1Desired, amount0Min, amount1Min, recipient ); if (0 < amount0In) { // token0.transferFrom(msg.sender, address(this), amount0In); TransferHelper.safeTransferFrom( address(token0), msg.sender, address(this), amount0In ); } if (0 < amount1In) { // token1.transferFrom(msg.sender, address(this), amount1In); TransferHelper.safeTransferFrom( address(token1), msg.sender, address(this), amount1In ); } _depositStepTwo( mainData, rangeData, recipient, shares, amount0In, amount1In, total0, total1 ); } function _withdrawStep( address withdrawer, uint256 shares, uint256 amount0Min, uint256 amount1Min, address recipient ) internal returns (uint256 amount0Out, uint256 amount1Out) { uint256 _totalSupply = totalSupply(); _burnPoolTokens(withdrawer, shares); // does balance check (, int24 tick, , , , , ) = activePool.slot0(); // if withdrawing everything, then burn and collect the all positions // else, calculate their share and return it if (shares == _totalSupply) { if (!paused()) { burnCollectPositions(); } amount0Out = token0.balanceOf(address(this)); amount1Out = token1.balanceOf(address(this)); } else { { uint256 e0 = token0.balanceOf(address(this)); amount0Out = e0 > 0 ? FullMath.mulDiv(e0, shares, _totalSupply) : 0; uint256 e1 = token1.balanceOf(address(this)); amount1Out = e1 > 0 ? FullMath.mulDiv(e1, shares, _totalSupply) : 0; } if (!paused()) { { (uint256 ma0Out, uint256 ma1Out) = burnAndCollect(mainPosition, tick, shares, _totalSupply); amount0Out = amount0Out.add(ma0Out); amount1Out = amount1Out.add(ma1Out); } { (uint256 ra0Out, uint256 ra1Out) = burnAndCollect(rangePosition, tick, shares, _totalSupply); amount0Out = amount0Out.add(ra0Out); amount1Out = amount1Out.add(ra1Out); } } } LixirErrors.require_INSUFFICIENT_OUTPUT_AMOUNT( amount0Min <= amount0Out && amount1Min <= amount1Out ); emit Withdraw( address(msg.sender), address(recipient), shares, amount0Out, amount1Out ); } modifier canSpend(address withdrawer, uint256 shares) { uint256 currentAllowance = _allowance[withdrawer][msg.sender]; LixirErrors.require_INSUFFICIENT_ALLOWANCE( msg.sender == withdrawer || currentAllowance >= shares ); if (msg.sender != withdrawer && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != withdrawer then currentAllowance >= shares _setAllowance(withdrawer, msg.sender, currentAllowance - shares); } _; } /** @notice withdraws the desired shares from the vault on behalf of another account @dev same as `withdraw` except this can be called from an `approve`d address @param withdrawer the address to withdraw from @param shares number of shares to withdraw @param amount0Min Minimum amount of token 0 desired by user @param amount1Min Minimum amount of token 1 desired by user @param recipient address to recieve token0 and token1 withdrawals @param deadline blocktimestamp that this must execute by @return amount0Out how much token0 was actually withdrawn @return amount1Out how much token1 was actually withdrawn */ function withdrawFrom( address withdrawer, uint256 shares, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external override canSpend(withdrawer, shares) returns (uint256 amount0Out, uint256 amount1Out) { (amount0Out, amount1Out) = _withdraw( withdrawer, shares, amount0Min, amount1Min, recipient, deadline ); } /** @notice withdraws the desired shares from the vault and transfers to caller. @dev `_withdrawStep` calculates how much the caller is owed @dev `_withdraw` transfers the tokens to the caller @param shares number of shares to withdraw @param amount0Min Minimum amount of token 0 desired by user @param amount1Min Minimum amount of token 1 desired by user @param recipient address to recieve token0 and token1 withdrawals @param deadline blocktimestamp that this must execute by @return amount0Out how much token0 was actually withdrawn @return amount1Out how much token1 was actually withdrawn */ function withdraw( uint256 shares, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external override returns (uint256 amount0Out, uint256 amount1Out) { (amount0Out, amount1Out) = _withdraw( msg.sender, shares, amount0Min, amount1Min, recipient, deadline ); } function _withdraw( address withdrawer, uint256 shares, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) internal notExpired(deadline) returns (uint256 amount0Out, uint256 amount1Out) { (amount0Out, amount1Out) = _withdrawStep( withdrawer, shares, amount0Min, amount1Min, recipient ); if (0 < amount0Out) { TransferHelper.safeTransfer(address(token0), recipient, amount0Out); } if (0 < amount1Out) { TransferHelper.safeTransfer(address(token1), recipient, amount1Out); } } function setPerformanceFee(uint24 newFee) external override onlyRole(LixirRoles.fee_setter_role) { require(newFee < PERFORMANCE_FEE_PRECISION); emit PerformanceFeeSet(performanceFee, newFee); performanceFee = newFee; } function _setPool(uint24 fee) internal { activePool = IUniswapV3Pool( PoolAddress.computeAddress( uniV3Factory, PoolAddress.getPoolKey(address(token0), address(token1), fee) ) ); require(Address.isContract(address(activePool))); activeFee = fee; } function setKeeper(address _keeper) external override onlyStrategist hasRole(LixirRoles.keeper_role, _keeper) { keeper = _keeper; } function setStrategy(address _strategy) external override onlyStrategist hasRole(LixirRoles.strategy_role, _strategy) { emit StrategySet(strategy, _strategy); strategy = _strategy; } function setStrategist(address _strategist) external override onlyGovOrDelegate hasRole(LixirRoles.strategist_role, _strategist) { strategist = _strategist; } function emergencyExit() external override whenNotPaused onlyRole(LixirRoles.pauser_role) { burnCollectPositions(); _pause(); } function unpause() external override whenPaused onlyGovOrDelegate { _unpause(); } /** @notice burns all positions collects any fees accrued since last `rebalance` and mints new positions. @dev This function is not called by an external account, but instead by the strategy contract, which automatically calculates the proper positions to mint. */ function rebalance( int24 mainTickLower, int24 mainTickUpper, int24 rangeTickLower0, int24 rangeTickUpper0, int24 rangeTickLower1, int24 rangeTickUpper1, uint24 fee ) external override onlyStrategy whenNotPaused { require( TickMath.MIN_TICK <= mainTickLower && mainTickUpper <= TickMath.MAX_TICK && mainTickLower < mainTickUpper && TickMath.MIN_TICK <= rangeTickLower0 && rangeTickUpper0 <= TickMath.MAX_TICK && rangeTickLower0 < rangeTickUpper0 && TickMath.MIN_TICK <= rangeTickLower1 && rangeTickUpper1 <= TickMath.MAX_TICK && rangeTickLower1 < rangeTickUpper1 ); /// if a pool has been previously set, then take the performance fee accrued since last `rebalance` /// and burn and collect all positions. if (address(activePool) != address(0)) { _takeFee(); burnCollectPositions(); } /// if the strategist has changed the pool fee tier (e.g. 0.05%, 0.3%, 1%), then change the pool if (fee != activeFee) { _setPool(fee); } uint256 total0 = token0.balanceOf(address(this)); uint256 total1 = token1.balanceOf(address(this)); Position memory mainData = Position(mainTickLower, mainTickUpper); Position memory rangeData0 = Position(rangeTickLower0, rangeTickUpper0); Position memory rangeData1 = Position(rangeTickLower1, rangeTickUpper1); mintPositions(total0, total1, mainData, rangeData0, rangeData1); emit Rebalance( mainTickLower, mainTickUpper, rangePosition.tickLower, rangePosition.tickUpper, fee, total0, total1 ); } function mintPositions( uint256 amount0, uint256 amount1, Position memory mainData, Position memory rangeData0, Position memory rangeData1 ) internal { (uint160 sqrtRatioX96, ) = getSqrtRatioX96AndTick(); mainPosition.tickLower = mainData.tickLower; mainPosition.tickUpper = mainData.tickUpper; if (0 < amount0 || 0 < amount1) { uint128 mL = LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(mainData.tickLower), TickMath.getSqrtRatioAtTick(mainData.tickUpper), amount0, amount1 ); if (0 < mL) { activePool.mint( address(this), mainData.tickLower, mainData.tickUpper, mL, '' ); } } amount0 = token0.balanceOf(address(this)); amount1 = token1.balanceOf(address(this)); uint128 rL; Position memory rangeData; if (0 < amount0 || 0 < amount1) { uint128 rL0 = LiquidityAmounts.getLiquidityForAmount0( TickMath.getSqrtRatioAtTick(rangeData0.tickLower), TickMath.getSqrtRatioAtTick(rangeData0.tickUpper), amount0 ); uint128 rL1 = LiquidityAmounts.getLiquidityForAmount1( TickMath.getSqrtRatioAtTick(rangeData1.tickLower), TickMath.getSqrtRatioAtTick(rangeData1.tickUpper), amount1 ); /// only one range position will ever have liquidity (if any) if (rL1 < rL0) { rL = rL0; rangeData = rangeData0; } else if (0 < rL1) { rangeData = rangeData1; rL = rL1; } } else { rangeData = Position(0, 0); } rangePosition.tickLower = rangeData.tickLower; rangePosition.tickUpper = rangeData.tickUpper; if (0 < rL) { activePool.mint( address(this), rangeData.tickLower, rangeData.tickUpper, rL, '' ); } } function _takeFee() internal { uint24 _perfFee = performanceFee; address _feeTo = registry.feeTo(); if (_feeTo != address(0) && 0 < _perfFee) { (uint160 sqrtRatioX96, int24 tick) = getSqrtRatioX96AndTick(); ( , uint256 total0, uint256 total1, uint256 tokensOwed0, uint256 tokensOwed1 ) = calculatePositionInfo( tick, sqrtRatioX96, mainPosition.tickLower, mainPosition.tickUpper ); { ( , uint256 total0Range, uint256 total1Range, uint256 tokensOwed0Range, uint256 tokensOwed1Range ) = calculatePositionInfo( tick, sqrtRatioX96, rangePosition.tickLower, rangePosition.tickUpper ); total0 = total0.add(total0Range).add(token0.balanceOf(address(this))); total1 = total1.add(total1Range).add(token1.balanceOf(address(this))); tokensOwed0 = tokensOwed0.add(tokensOwed0Range); tokensOwed1 = tokensOwed1.add(tokensOwed1Range); } uint256 _totalSupply = totalSupply(); uint256 price = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, FixedPoint96.Q96); total1 = total1.add(FullMath.mulDiv(total0, price, FixedPoint96.Q96)); if (total1 > 0) { tokensOwed1 = tokensOwed1.add( FullMath.mulDiv(tokensOwed0, price, FixedPoint96.Q96) ); uint256 shares = FullMath.mulDiv( FullMath.mulDiv(tokensOwed1, _totalSupply, total1), performanceFee, PERFORMANCE_FEE_PRECISION ); if (shares > 0) { _mintPoolTokens(_feeTo, shares); } } } } /** @notice burns everyting (main and range positions) and collects any fees accrued in the pool. @dev this is called fairly frequently since compounding is not automatic: in UniV3, all fees must be manually withdrawn. */ function burnCollectPositions() internal { uint128 mL = positionLiquidity(mainPosition); uint128 rL = positionLiquidity(rangePosition); if (0 < mL) { activePool.burn(mainPosition.tickLower, mainPosition.tickUpper, mL); activePool.collect( address(this), mainPosition.tickLower, mainPosition.tickUpper, type(uint128).max, type(uint128).max ); } if (0 < rL) { activePool.burn(rangePosition.tickLower, rangePosition.tickUpper, rL); activePool.collect( address(this), rangePosition.tickLower, rangePosition.tickUpper, type(uint128).max, type(uint128).max ); } } /** @notice in contrast to `burnCollectPositions`, this only burns a portion of liqudity, used for when a user withdraws tokens from the vault. @param position Storage pointer to position @param tick Current tick @param shares User shares to burn @param _totalSupply totalSupply of Lixir vault tokens */ function burnAndCollect( Position storage position, int24 tick, uint256 shares, uint256 _totalSupply ) internal returns (uint256 amount0Out, uint256 amount1Out) { int24 tickLower = position.tickLower; int24 tickUpper = position.tickUpper; /* * N.B. that tokensOwed{0,1} here are calculated prior to burning, * and so should only contain tokensOwed from fees and never tokensOwed from a burn */ (uint128 liquidity, uint256 tokensOwed0, uint256 tokensOwed1) = liquidityAndTokensOwed(tick, tickLower, tickUpper); uint128 LDelta = FullMath.mulDiv(shares, liquidity, _totalSupply).toUint128(); amount0Out = FullMath.mulDiv(tokensOwed0, shares, _totalSupply); amount1Out = FullMath.mulDiv(tokensOwed1, shares, _totalSupply); if (0 < LDelta) { (uint256 burnt0Out, uint256 burnt1Out) = activePool.burn(tickLower, tickUpper, LDelta); amount0Out = amount0Out.add(burnt0Out); amount1Out = amount1Out.add(burnt1Out); } if (0 < amount0Out || 0 < amount1Out) { activePool.collect( address(this), tickLower, tickUpper, amount0Out.toUint128(), amount1Out.toUint128() ); } } /// @dev internal readonly getters and pure helper functions /** * @dev Calculates shares and amounts to deposit from amounts desired, TVL of vault, and totalSupply of vault tokens * @param amount0Desired Amount of token 0 desired by user * @param amount1Desired Amount of token 1 desired by user * @param total0 Total amount of token 0 available to activePool * @param total1 Total amount of token 1 available to activePool * @param _totalSupply Total supply of vault tokens * @return shares Shares of activePool to mint to user * @return amount0In Actual amount of token0 user should deposit into activePool * @return amount1In Actual amount of token1 user should deposit into activePool */ function calcSharesAndAmounts( uint256 amount0Desired, uint256 amount1Desired, uint256 total0, uint256 total1, uint256 _totalSupply ) internal pure returns ( uint256 shares, uint256 amount0In, uint256 amount1In ) { (bool roundedSharesFrom0, uint256 sharesFrom0) = 0 < total0 ? mulDivRoundingUp(amount0Desired, _totalSupply, total0) : (false, 0); (bool roundedSharesFrom1, uint256 sharesFrom1) = 0 < total1 ? mulDivRoundingUp(amount1Desired, _totalSupply, total1) : (false, 0); uint8 realSharesOffsetFor0 = roundedSharesFrom0 ? 1 : 2; uint8 realSharesOffsetFor1 = roundedSharesFrom1 ? 1 : 2; if ( realSharesOffsetFor0 < sharesFrom0 && (total1 == 0 || sharesFrom0 < sharesFrom1) ) { shares = sharesFrom0 - 1 - realSharesOffsetFor0; amount0In = amount0Desired; amount1In = FullMath.mulDivRoundingUp(sharesFrom0, total1, _totalSupply); LixirErrors.require_INSUFFICIENT_OUTPUT_AMOUNT( amount1In <= amount1Desired ); } else { LixirErrors.require_INSUFFICIENT_INPUT_AMOUNT( realSharesOffsetFor1 < sharesFrom1 ); shares = sharesFrom1 - 1 - realSharesOffsetFor1; amount0In = FullMath.mulDivRoundingUp(sharesFrom1, total0, _totalSupply); LixirErrors.require_INSUFFICIENT_OUTPUT_AMOUNT( amount0In <= amount0Desired ); amount1In = amount1Desired; } } function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (bool rounded, uint256 result) { result = FullMath.mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; rounded = true; } } /** * @dev Calculates shares, liquidity deltas, and amounts in for initial deposit * @param amount0Desired Amount of token 0 desired by user * @param amount1Desired Amount of token 1 desired by user * @return shares Initial shares to mint * @return mLDelta Liquidity delta for main position * @return amount0In Amount of token 0 to transfer from user * @return amount1In Amount of token 1 to transfer from user */ function calculateInitialDeposit( uint256 amount0Desired, uint256 amount1Desired ) internal view returns ( uint256 shares, uint128 mLDelta, uint256 amount0In, uint256 amount1In ) { (uint160 sqrtRatioX96, int24 tick) = getSqrtRatioX96AndTick(); uint160 sqrtRatioLowerX96 = TickMath.getSqrtRatioAtTick(mainPosition.tickLower); uint160 sqrtRatioUpperX96 = TickMath.getSqrtRatioAtTick(mainPosition.tickUpper); mLDelta = LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, sqrtRatioLowerX96, sqrtRatioUpperX96, amount0Desired, amount1Desired ); LixirErrors.require_INSUFFICIENT_INPUT_AMOUNT(0 < mLDelta); (amount0In, amount1In) = getAmountsForLiquidity( sqrtRatioX96, sqrtRatioLowerX96, sqrtRatioUpperX96, mLDelta.toInt128() ); shares = mLDelta; } /** * @dev Queries activePool for current square root price and current tick * @return _sqrtRatioX96 Current square root price * @return _tick Current tick */ function getSqrtRatioX96AndTick() internal view returns (uint160 _sqrtRatioX96, int24 _tick) { (_sqrtRatioX96, _tick, , , , , ) = activePool.slot0(); } /** * @dev Calculates tokens owed for a position * @param realTick Current tick * @param tickLower Lower tick of position * @param tickUpper Upper tick of position * @param feeGrowthInside0LastX128 Last fee growth of token0 between tickLower and tickUpper * @param feeGrowthInside1LastX128 Last fee growth of token0 between tickLower and tickUpper * @param liquidity Liquidity of position for which tokens owed is being calculated * @param tokensOwed0Last Last tokens owed to position * @param tokensOwed1Last Last tokens owed to position * @return tokensOwed0 Amount of token0 owed to position * @return tokensOwed1 Amount of token1 owed to position */ function calculateTokensOwed( int24 realTick, int24 tickLower, int24 tickUpper, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 liquidity, uint128 tokensOwed0Last, uint128 tokensOwed1Last ) internal view returns (uint128 tokensOwed0, uint128 tokensOwed1) { /* * V3 doesn't use SafeMath here, so we don't either * This could of course result in a dramatic forfeiture of fees. The reality though is * we rebalance far frequently enough for this to never happen in any realistic scenario. * This has no difference from the v3 implementation, and was copied from contracts/libraries/Position.sol */ (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInsideTicks(realTick, tickLower, tickUpper); tokensOwed0 = uint128( tokensOwed0Last + FullMath.mulDiv( feeGrowthInside0X128 - feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128 ) ); tokensOwed1 = uint128( tokensOwed1Last + FullMath.mulDiv( feeGrowthInside1X128 - feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128 ) ); } function _positionDataHelper( int24 realTick, int24 tickLower, int24 tickUpper ) internal view returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { ( liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1 ) = activePool.positions( PositionKey.compute(address(this), tickLower, tickUpper) ); if (liquidity == 0) { return ( 0, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1 ); } (tokensOwed0, tokensOwed1) = calculateTokensOwed( realTick, tickLower, tickUpper, feeGrowthInside0LastX128, feeGrowthInside1LastX128, liquidity, tokensOwed0, tokensOwed1 ); } /** * @dev Queries and calculates liquidity and tokens owed * @param tick Current tick * @param tickLower Lower tick of position * @param tickUpper Upper tick of position * @return liquidity Liquidity of position for which tokens owed is being calculated * @return tokensOwed0 Amount of token0 owed to position * @return tokensOwed1 Amount of token1 owed to position */ function liquidityAndTokensOwed( int24 tick, int24 tickLower, int24 tickUpper ) internal view returns ( uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, , , tokensOwed0, tokensOwed1) = _positionDataHelper( tick, tickLower, tickUpper ); } function calculateTotals() external view returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ) { (uint160 sqrtRatioX96, int24 tick) = getSqrtRatioX96AndTick(); return _calculateTotals( sqrtRatioX96, tick, DepositPositionData(0, mainPosition.tickLower, mainPosition.tickUpper), DepositPositionData(0, rangePosition.tickLower, rangePosition.tickUpper) ); } /** * @notice This variant is so that tick TWAP's may be used by other protocols to calculate * totals, allowing them to safeguard themselves from manipulation. This would be useful if * Lixir vault tokens were used as collateral in a lending protocol. * @param virtualTick Tick at which to calculate amounts from liquidity */ function calculateTotalsFromTick(int24 virtualTick) external view override returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(virtualTick); (, int24 realTick) = getSqrtRatioX96AndTick(); return _calculateTotalsFromTick( sqrtRatioX96, realTick, DepositPositionData(0, mainPosition.tickLower, mainPosition.tickUpper), DepositPositionData(0, rangePosition.tickLower, rangePosition.tickUpper) ); } /** * @dev Helper function for calculating totals * @param sqrtRatioX96 *Current or virtual* sqrtPriceX96 * @param realTick Current tick, for calculating tokensOwed correctly * @param mainData Main position data * @param rangeData Range position data * N.B realTick must be provided because tokensOwed calculation needs * the current correct tick because the ticks are only updated upon the * crossing of ticks * sqrtRatioX96 can be a current sqrtPriceX96 *or* a sqrtPriceX96 calculated * from a virtual tick, for external consumption */ function _calculateTotalsFromTick( uint160 sqrtRatioX96, int24 realTick, DepositPositionData memory mainData, DepositPositionData memory rangeData ) internal view returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ) { (mL, total0, total1) = calculatePositionTotals( realTick, sqrtRatioX96, mainData.tickLower, mainData.tickUpper ); { uint256 rt0; uint256 rt1; (rL, rt0, rt1) = calculatePositionTotals( realTick, sqrtRatioX96, rangeData.tickLower, rangeData.tickUpper ); total0 = total0.add(rt0); total1 = total1.add(rt1); } total0 = total0.add(token0.balanceOf(address(this))); total1 = total1.add(token1.balanceOf(address(this))); } function _calculateTotals( uint160 sqrtRatioX96, int24 tick, DepositPositionData memory mainData, DepositPositionData memory rangeData ) internal view returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ) { return _calculateTotalsFromTick(sqrtRatioX96, tick, mainData, rangeData); } /** * @dev Calculates total tokens obtainable and liquidity of a given position (fees + amounts in position) * total{0,1} is sum of tokensOwed{0,1} from each position plus sum of liquidityForAmount{0,1} for each position plus vault balance of token{0,1} * @param realTick Current tick (for calculating tokensOwed) * @param sqrtRatioX96 Current (or virtual) square root price * @param tickLower Lower tick of position * @param tickLower Upper tick of position * @return liquidity Liquidity of position * @return total0 Total amount of token0 obtainable from position * @return total1 Total amount of token1 obtainable from position */ function calculatePositionTotals( int24 realTick, uint160 sqrtRatioX96, int24 tickLower, int24 tickUpper ) internal view returns ( uint128 liquidity, uint256 total0, uint256 total1 ) { uint256 tokensOwed0; uint256 tokensOwed1; ( liquidity, total0, total1, tokensOwed0, tokensOwed1 ) = calculatePositionInfo(realTick, sqrtRatioX96, tickLower, tickUpper); total0 = total0.add(tokensOwed0); total1 = total1.add(tokensOwed1); } function calculatePositionInfo( int24 realTick, uint160 sqrtRatioX96, int24 tickLower, int24 tickUpper ) internal view returns ( uint128 liquidity, uint256 total0, uint256 total1, uint256 tokensOwed0, uint256 tokensOwed1 ) { uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; ( liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1 ) = _positionDataHelper(realTick, tickLower, tickUpper); uint160 sqrtPriceLower = TickMath.getSqrtRatioAtTick(tickLower); uint160 sqrtPriceUpper = TickMath.getSqrtRatioAtTick(tickUpper); (uint256 amount0, uint256 amount1) = getAmountsForLiquidity( sqrtRatioX96, sqrtPriceLower, sqrtPriceUpper, liquidity.toInt128() ); } /** * @dev Calculates fee growth between a tick range * @param tick Current tick * @param tickLower Lower tick of range * @param tickUpper Upper tick of range * @return feeGrowthInside0X128 Fee growth of token 0 inside ticks * @return feeGrowthInside1X128 Fee growth of token 1 inside ticks */ function getFeeGrowthInsideTicks( int24 tick, int24 tickLower, int24 tickUpper ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { /* * Underflow is Good here, actually. * Uniswap V3 doesn't use SafeMath here, and the cases where it does underflow, * it should help us get back to the rightful fee growth value of our position. * It would underflow only when feeGrowthGlobal{0,1}X128 has overflowed already in the V3 contract. * It should never underflow if feeGrowthGlobal{0,1}X128 hasn't yet overflowed. * Of course, if feeGrowthGlobal{0,1}X128 has overflowed twice over or more, we cannot possibly recover * fees from the overflow before last via underflow here, and it is possible our feeGrowthOutside values are * insufficently large to underflow enough to recover fees from the most recent overflow. * But, we rebalance frequently, so this should never be an issue. * This math is no different than in the v3 activePool contract and was copied from contracts/libraries/Tick.sol */ uint256 feeGrowthGlobal0X128 = activePool.feeGrowthGlobal0X128(); uint256 feeGrowthGlobal1X128 = activePool.feeGrowthGlobal1X128(); ( , , uint256 feeGrowthOutside0X128Lower, uint256 feeGrowthOutside1X128Lower, , , , ) = activePool.ticks(tickLower); ( , , uint256 feeGrowthOutside0X128Upper, uint256 feeGrowthOutside1X128Upper, , , , ) = activePool.ticks(tickUpper); // calculate fee growth below uint256 feeGrowthBelow0X128; uint256 feeGrowthBelow1X128; if (tick >= tickLower) { feeGrowthBelow0X128 = feeGrowthOutside0X128Lower; feeGrowthBelow1X128 = feeGrowthOutside1X128Lower; } else { feeGrowthBelow0X128 = feeGrowthGlobal0X128 - feeGrowthOutside0X128Lower; feeGrowthBelow1X128 = feeGrowthGlobal1X128 - feeGrowthOutside1X128Lower; } // calculate fee growth above uint256 feeGrowthAbove0X128; uint256 feeGrowthAbove1X128; if (tick < tickUpper) { feeGrowthAbove0X128 = feeGrowthOutside0X128Upper; feeGrowthAbove1X128 = feeGrowthOutside1X128Upper; } else { feeGrowthAbove0X128 = feeGrowthGlobal0X128 - feeGrowthOutside0X128Upper; feeGrowthAbove1X128 = feeGrowthGlobal1X128 - feeGrowthOutside1X128Upper; } feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128; } /** * @dev Queries position liquidity * @param position Storage pointer to position we want to query */ function positionLiquidity(Position storage position) internal view returns (uint128 _liquidity) { (_liquidity, , , , ) = activePool.positions( PositionKey.compute(address(this), position.tickLower, position.tickUpper) ); } function getAmountsForLiquidity( uint160 sqrtPriceX96, uint160 sqrtPriceX96Lower, uint160 sqrtPriceX96Upper, int128 liquidityDelta ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtPriceX96 <= sqrtPriceX96Lower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it amount0 = SqrtPriceMath .getAmount0Delta(sqrtPriceX96Lower, sqrtPriceX96Upper, liquidityDelta) .abs(); } else if (sqrtPriceX96 < sqrtPriceX96Upper) { amount0 = SqrtPriceMath .getAmount0Delta(sqrtPriceX96, sqrtPriceX96Upper, liquidityDelta) .abs(); amount1 = SqrtPriceMath .getAmount1Delta(sqrtPriceX96Lower, sqrtPriceX96, liquidityDelta) .abs(); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it amount1 = SqrtPriceMath .getAmount1Delta(sqrtPriceX96Lower, sqrtPriceX96Upper, liquidityDelta) .abs(); } } /// @inheritdoc IUniswapV3MintCallback function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata ) external virtual override { require(msg.sender == address(activePool)); if (amount0Owed > 0) { TransferHelper.safeTransfer(address(token0), msg.sender, amount0Owed); } if (amount1Owed > 0) { TransferHelper.safeTransfer(address(token1), msg.sender, amount1Owed); } } } // File: LixirVaultETH.sol contract LixirVaultETH is LixirVault, ILixirVaultETH { using SafeMath for uint256; using SafeCast for uint256; IWETH9 public immutable weth9; TOKEN public override WETH_TOKEN; constructor(address _registry) LixirVault(_registry) { weth9 = LixirRegistry(_registry).weth9(); } function initialize( string memory name, string memory symbol, address _token0, address _token1, address _strategist, address _keeper, address _strategy ) public override(LixirVault, ILixirVault) initializer { LixirVault.initialize( name, symbol, _token0, _token1, _strategist, _keeper, _strategy ); TOKEN _WETH_TOKEN; if (_token0 == address(weth9)) { _WETH_TOKEN = TOKEN.ZERO; } else { require(_token1 == address(weth9)); _WETH_TOKEN = TOKEN.ONE; } WETH_TOKEN = _WETH_TOKEN; } /** @notice equivalent to `deposit` except logic is configured for ETH instead of ERC20 payments. @param amountDesired amount of ERC20 token desired by caller @param amountEthMin minimum amount of ETH desired by caller @param amountMin minimum amount of ERC20 token desired by caller @param recipient The address for which the liquidity will be created @param deadline Blocktimestamp that this must execute before @return shares @return amountEthIn how much ETH was actually deposited @return amountIn how much the ERC20 token was actually deposited */ function depositETH( uint256 amountDesired, uint256 amountEthMin, uint256 amountMin, address recipient, uint256 deadline ) external payable override whenNotPaused notExpired(deadline) returns ( uint256 shares, uint256 amountEthIn, uint256 amountIn ) { TOKEN _WETH_TOKEN = WETH_TOKEN; if (_WETH_TOKEN == TOKEN.ZERO) { (shares, amountEthIn, amountIn) = _depositETH( _WETH_TOKEN, msg.value, amountDesired, amountEthMin, amountMin, recipient, deadline ); } else { (shares, amountIn, amountEthIn) = _depositETH( _WETH_TOKEN, amountDesired, msg.value, amountMin, amountEthMin, recipient, deadline ); } } function _depositETH( TOKEN _WETH_TOKEN, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) internal returns ( uint256 shares, uint256 amount0In, uint256 amount1In ) { uint256 amountEthDesired = msg.value; DepositPositionData memory mainData; DepositPositionData memory rangeData; uint256 total0; uint256 total1; ( mainData, rangeData, shares, amount0In, amount1In, total0, total1 ) = _depositStepOne( amount0Desired, amount1Desired, amount0Min, amount1Min, recipient ); if (_WETH_TOKEN == TOKEN.ZERO) { if (0 < amount0In) { weth9.deposit{value: amount0In}(); } if (0 < amount1In) { TransferHelper.safeTransferFrom( address(token1), msg.sender, address(this), amount1In ); } } else { if (0 < amount0In) { TransferHelper.safeTransferFrom( address(token0), msg.sender, address(this), amount0In ); } if (0 < amount1In) { weth9.deposit{value: amount1In}(); } } _depositStepTwo( mainData, rangeData, recipient, shares, amount0In, amount1In, total0, total1 ); Address.sendValue(msg.sender, address(this).balance); } /** @notice withdraws the desired shares from the vault @dev same as `withdraw` except this can be called from an `approve`d address @param withdrawer the address to withdraw from @param shares number of shares to withdraw @param amountEthMin amount of ETH desired by user @param amountMin Minimum amount of ERC20 token desired by user @param recipient address to recieve ETH and ERC20 withdrawals @param deadline blocktimestamp that this must execute by @return amountEthOut how much ETH was actually withdrawn @return amountOut how much ERC20 token was actually withdrawn */ function withdrawETHFrom( address withdrawer, uint256 shares, uint256 amountEthMin, uint256 amountMin, address payable recipient, uint256 deadline ) external override canSpend(withdrawer, shares) returns (uint256 amountEthOut, uint256 amountOut) { TOKEN _WETH_TOKEN = WETH_TOKEN; uint256 amount0Min; uint256 amount1Min; if (_WETH_TOKEN == TOKEN.ZERO) { amount0Min = amountEthMin; amount1Min = amountMin; (amountEthOut, amountOut) = _withdrawETH( _WETH_TOKEN, withdrawer, shares, amount0Min, amount1Min, recipient, deadline ); } else { amount0Min = amountMin; amount1Min = amountEthMin; (amountOut, amountEthOut) = _withdrawETH( _WETH_TOKEN, withdrawer, shares, amount0Min, amount1Min, recipient, deadline ); } } /** @notice withdraws the desired shares from the vault @param shares number of shares to withdraw @param amountEthMin amount of ETH desired by user @param amountMin Minimum amount of ERC20 token desired by user @param recipient address to recieve ETH and ERC20 withdrawals @param deadline blocktimestamp that this must execute by @return amountEthOut how much ETH was actually withdrawn @return amountOut how much ERC20 token was actually withdrawn */ function withdrawETH( uint256 shares, uint256 amountEthMin, uint256 amountMin, address payable recipient, uint256 deadline ) external override returns (uint256 amountEthOut, uint256 amountOut) { TOKEN _WETH_TOKEN = WETH_TOKEN; uint256 amount0Min; uint256 amount1Min; if (_WETH_TOKEN == TOKEN.ZERO) { amount0Min = amountEthMin; amount1Min = amountMin; (amountEthOut, amountOut) = _withdrawETH( _WETH_TOKEN, msg.sender, shares, amount0Min, amount1Min, recipient, deadline ); } else { amount0Min = amountMin; amount1Min = amountEthMin; (amountOut, amountEthOut) = _withdrawETH( _WETH_TOKEN, msg.sender, shares, amount0Min, amount1Min, recipient, deadline ); } } function _withdrawETH( TOKEN _WETH_TOKEN, address withdrawer, uint256 shares, uint256 amount0Min, uint256 amount1Min, address payable recipient, uint256 deadline ) internal notExpired(deadline) returns (uint256 amount0Out, uint256 amount1Out) { (amount0Out, amount1Out) = _withdrawStep( withdrawer, shares, amount0Min, amount1Min, recipient ); if (_WETH_TOKEN == TOKEN.ZERO) { if (0 < amount0Out) { weth9.withdraw(amount0Out); Address.sendValue(recipient, amount0Out); } if (0 < amount1Out) { TransferHelper.safeTransfer(address(token1), recipient, amount1Out); } } else { if (0 < amount1Out) { TransferHelper.safeTransfer(address(token0), recipient, amount0Out); } if (0 < amount1Out) { weth9.withdraw(amount1Out); Address.sendValue(recipient, amount1Out); } } } receive() external payable override { require(msg.sender == address(weth9)); } }
Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't need to send a transaction, and thus is not required to hold Ether at all./ solhint-disable-next-line func-name-mixedcase
interface IERC20Permit { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256); function DOMAIN_SEPARATOR() external view returns (bytes32); }
7,863,861
./partial_match/1/0xc39b13960D0B1BBD09FAB90969960f7a56e89E92/sources/Exchange.sol
Getter to determine if pairs are whitelisted. _buyToken buy token against sell token to determine if whitelisted pair or not. _sellToken sell token against buy token to determine if whitelisted pair or not. return bool is whitelisted pair./
function isPaired(address _buyToken, address _sellToken) public view returns (bool) { return pair[pairIdentifier[_buyToken][_sellToken]].paired; }
3,714,671
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./token/BambooToken.sol"; // // // Raindrop is the contract in charge of the lottery system. // Every 10 days the contract will choose a winner. // Randomness used here is based on future block hash, requiring two calls to determine the winner. (Commit + Draw). // We are aware of the security vulnerabilities for this PRNG approach, still is for now the choice for finding the winner, because it is easier for end users. // The PRNG method here is based on the Breeding Contract from the CriptoKitties DAPP. // Which was written by Axiom Zen, Dieter Shirley <dete@axiomzen.co> (https://github.com/dete), Fabiano P. Soriani <fabianosoriani@gmail.com> (https://github.com/flockonus), Jordan Schalm contract Raindrop is Ownable{ using SafeMath for uint256; using SafeERC20 for IERC20; // Info used in case of an emergency refund. struct UserInfo{ uint256 validLimit; // Timestamp until these tickets are valid uint256 tickets; // Number of tickets bought by the user uint256 amountSpent; // Amount spent on tickets } // Simple flag to check if contract has been started. // Owner could stop the contract if there are security issues. In that case all participants will be refunded. bool public isCloudy; // The address that will receive a percentage of the lottery. address public feeTo; // The BAMBOO TOKEN, currency used to buy tickets and give the price. BambooToken public bamboo; // The timestamp of the next lottery draw. uint256 public nextRain; // The price of a ticket entry. uint256 public price; // Number of winners (and minimum participants). uint public constant nwinners = 9; // The winners of the last lottery. address[] private lastWinners; // List of participants for current raindrop. address[] private participants; // Tracking of amount of tickets per user. Needed in case of an emergency refund. mapping(address => UserInfo) private ticketHolders; // Current prize pool amount. uint256 public prizePool; // Variables used for randomness. uint256 internal constant maskLast8Bits = uint256(0xff); uint256 internal constant maskFirst248Bits = uint256(~0xff); uint256 private _targetBlock; bool public commited; bool public refundPeriod; event TicketsPurchased(address indexed user, uint256 ntickets); event NewRain(uint256 nextRain); event TicketPriceSet(uint256 price); event Commit(uint256 targetBlock); constructor(BambooToken _bamboo) { bamboo = _bamboo; isCloudy = false; refundPeriod = false; } // Purchase tickets for the lottery. The bamboo should be approved beforehand. function buyTickets(uint _ntickets) public { require(msg.sender != owner(), "buyTickets: owner cannot participate"); require(isCloudy, "buyTickets: lottery has not started yet"); require(block.timestamp<=nextRain, "buyTickets: period of buying tickets ended"); require(_ntickets >0, "buyTickets: invalid number of tickets!"); uint256 balance = bamboo.balanceOf(msg.sender); require(balance >=price.mul(_ntickets), "buyTickets: not enough bamboo!"); uint256 cost = price.mul(_ntickets); IERC20(bamboo).safeTransferFrom(address(msg.sender), address(this), cost); prizePool = prizePool.add(cost); registerTicket(msg.sender, _ntickets); for(uint i=0; i<_ntickets; i++) { participants.push(msg.sender); } emit TicketsPurchased(msg.sender, _ntickets); } // Register ticket of current lottery in case of a refund. function registerTicket(address _addr, uint _ntickets) internal { UserInfo storage user = ticketHolders[_addr]; if(user.validLimit != nextRain) { user.validLimit = nextRain; user.tickets = _ntickets; } else{ user.tickets += _ntickets; } user.amountSpent += price.mul(_ntickets); } // Stop the ticket sell and prepare the variables. function commit() public { require(isCloudy, "commit: lottery has not started yet"); require(block.timestamp>nextRain , "commit: period of buying tickets still up!"); require(!commited, "commit: this raindrop has already been commited"); // If there are not enough participants, add 1 week. if(participants.length < nwinners){ nextRain = block.timestamp.add(7 days); emit NewRain(nextRain); updateTickets(); } else{ _targetBlock = block.number + 1; commited = true; emit Commit(_targetBlock); } } // Choose the winner. This call could be expensive, so the Bamboo team will be calling it every endRain day. function drawWinners() public { require(isCloudy, "drawWinners: lottery has not started yet"); require(block.timestamp>nextRain , "drawWinners: period of buying tickets still up!"); require(commited, "drawWinners: this raindrop has not been commited yet"); // We will use the blockhash of the next n blocks to choose the n winners. require(block.number > _targetBlock + nwinners, "drawWinners: please wait for some more blocks to pass"); uint256 prize = prizePool.div(10); uint256[] memory randomNums = new uint256[](nwinners); for(uint i=0; i<nwinners; ++i) { uint256 targetBlock = _targetBlock + i; // Try to grab the hash of the "target block". This should be available the vast // majority of the time (it will only fail if no-one calls drawWinner() within 256 // blocks of the target block, which is about 40 minutes. uint256 randomN = uint256(blockhash(targetBlock)); if (randomN == 0) { // We don't want to completely bail if the target block is no-longer available, // nor do we want to just use the current block's hash (since it could allow a // caller to game the random result). Compute the most recent block that has the // the same value modulo 256 as the target block. The hash for this block will // still be available, and – while it can still change as time passes – it will // only change every 40 minutes. Again, someone is very likely to jump in with // the giveBirth() call before it can cycle too many times. _targetBlock = (block.number & maskFirst248Bits) + (targetBlock & maskLast8Bits); // The computation above could result in a block LARGER than the current block, // if so, subtract 256. if (_targetBlock >= block.number) _targetBlock = _targetBlock.sub(256); targetBlock = _targetBlock + i; randomN = uint256(blockhash(targetBlock)); } randomN = uint256(keccak256(abi.encode(randomN, targetBlock))); randomNums[i] = randomN; } // Reset variables for next lottery. Deleting variables returns a bit of gas. delete(prizePool); delete(commited); delete(_targetBlock); // Select winners. delete(lastWinners); for (uint i=0; i<nwinners; i++) { uint256 rindex = randomNums[i].mod(participants.length); lastWinners.push(participants[rindex]); // Remove that ticket from contention. participants[rindex] = participants[participants.length -1]; participants.pop(); } delete(participants); // Declare the winners and reset the lottery! for(uint i=0; i<nwinners; i++){ IERC20(bamboo).safeTransfer(lastWinners[i], prize); } IERC20(bamboo).safeTransfer(feeTo, prize); nextRain = block.timestamp.add(10 days); emit NewRain(nextRain); } // Get the winners of the last lottery. function getLastWinners() public view returns(address[] memory) { return lastWinners; } // Stops the contract and allows users to call for refunds function emergencyStop() public onlyOwner { delete(isCloudy); delete(commited); delete(_targetBlock); delete(nextRain); delete(prizePool); delete(participants); refundPeriod = true; } // In emergencies, allows users to refund tickets. function refund() public { require(refundPeriod, 'refund: can only refund on emergency stop'); UserInfo storage user = ticketHolders[msg.sender]; require(user.amountSpent > 0, 'refund: nothing to refund'); uint256 amount = user.amountSpent; IERC20(bamboo).safeTransfer(msg.sender, amount); delete(ticketHolders[msg.sender]); } // This function is called when there is less than minimum participants. No require needed function updateTickets() internal { address last; for(uint i=0; i<participants.length; i++) { address current = participants[i]; if (current != last){ ticketHolders[current].validLimit = nextRain; } last = current; } } // A simple function that returns the number of tickets from a user. function getTickets(address _user) external view returns (uint256) { if(ticketHolders[_user].validLimit == nextRain){ return ticketHolders[_user].tickets; } else{ return 0; } } // Allows the owner to start the contract. After this call, the contract doesn't need the owner anymore to work. function startRain() public onlyOwner { require(!isCloudy, "startRain: contract already started"); require(price>0, "startRain: please set ticket price first"); nextRain = block.timestamp.add(10 days); isCloudy = true; refundPeriod = false; emit NewRain(nextRain); } // Sets the address that will receive the commission from the lottery. function setFeeTo(address _feeTo) external onlyOwner { feeTo = _feeTo; } // Sets the ticket price. function setTicketPrice(uint256 _amount) external onlyOwner { require(_amount > 0, "setTicketPrice: invalid amount"); require(!isCloudy, "setTicketPrice: raindrop already started"); price = _amount; emit TicketPriceSet(price); } }
Sets the ticket price.
function setTicketPrice(uint256 _amount) external onlyOwner { require(_amount > 0, "setTicketPrice: invalid amount"); require(!isCloudy, "setTicketPrice: raindrop already started"); price = _amount; emit TicketPriceSet(price); }
12,536,635
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "./ChainlinkOracle.sol"; import "./UniswapV3TWAPOracle.sol"; import "./UniswapV3TWAPOracle2.sol"; /** * We make MedianOracle *inherit* its median-component oracles (eg, ChainlinkOracle), rather than hold them as state variables * like any sane person would, because this significantly reduces the number of (gas-pricey) external contract calls. * Eg, this contract calling ChainlinkOracle.latestPrice() on itself is significantly cheaper than calling * chainlinkOracle.latestPrice() on a chainlinkOracle var (contract). */ contract MedianOracle is ChainlinkOracle, UniswapV3TWAPOracle, UniswapV3TWAPOracle2 { constructor( AggregatorV3Interface chainlinkAggregator, IUniswapV3Pool uniswapPool1, uint uniswapTokenToPrice1, int uniswapDecimals1, IUniswapV3Pool uniswapPool2, uint uniswapTokenToPrice2, int uniswapDecimals2 ) ChainlinkOracle(chainlinkAggregator) UniswapV3TWAPOracle(uniswapPool1, uniswapTokenToPrice1, uniswapDecimals1) UniswapV3TWAPOracle2(uniswapPool2, uniswapTokenToPrice2, uniswapDecimals2) {} function latestPrice() public virtual override(ChainlinkOracle, UniswapV3TWAPOracle, UniswapV3TWAPOracle2) view returns (uint price, uint updateTime) { (uint chainlinkPrice, uint chainlinkUpdateTime) = ChainlinkOracle.latestPrice(); (uint uniswapPrice1, uint uniswapUpdateTime1) = UniswapV3TWAPOracle.latestPrice(); (uint uniswapPrice2, uint uniswapUpdateTime2) = UniswapV3TWAPOracle2.latestPrice(); (price, updateTime) = medianPriceAndUpdateTime(chainlinkPrice, chainlinkUpdateTime, uniswapPrice1, uniswapUpdateTime1, uniswapPrice2, uniswapUpdateTime2); } function latestChainlinkPrice() public view returns (uint price, uint updateTime) { (price, updateTime) = ChainlinkOracle.latestPrice(); } function latestUniswapV3TWAPPrice1() public view returns (uint price, uint updateTime) { (price, updateTime) = UniswapV3TWAPOracle.latestPrice(); } function latestUniswapV3TWAPPrice2() public view returns (uint price, uint updateTime) { (price, updateTime) = UniswapV3TWAPOracle2.latestPrice(); } /** * @notice Currently only supports three inputs * @return price the median price of the three passed in * @return updateTime the updateTime corresponding to the median price. Not the median of the three updateTimes! */ function medianPriceAndUpdateTime(uint p1, uint t1, uint p2, uint t2, uint p3, uint t3) public pure returns (uint price, uint updateTime) { bool p1gtp2 = p1 > p2; bool p2gtp3 = p2 > p3; bool p3gtp1 = p3 > p1; (price, updateTime) = (p3gtp1 == p1gtp2 ? (p1, t1) : (p1gtp2 == p2gtp3 ? (p2, t2) : (p3, t3))); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "./Oracle.sol"; /** * @title ChainlinkOracle */ contract ChainlinkOracle is Oracle { uint public constant CHAINLINK_SCALE_FACTOR = 1e10; // Since Chainlink has 8 dec places, and latestPrice() needs 18 AggregatorV3Interface public immutable chainlinkAggregator; constructor(AggregatorV3Interface aggregator_) { chainlinkAggregator = aggregator_; } /** * @notice Retrieve the latest price of the price oracle. * @return price */ function latestPrice() public virtual override view returns (uint price, uint updateTime) { int rawPrice; (, rawPrice,, updateTime,) = chainlinkAggregator.latestRoundData(); require(rawPrice > 0, "Chainlink price <= 0"); price = uint(rawPrice) * CHAINLINK_SCALE_FACTOR; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; //import "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol"; import "./uniswap/v3-periphery/OracleLibrary.sol"; import "./Oracle.sol"; contract UniswapV3TWAPOracle is Oracle { uint32 public constant UNISWAP_TWAP_PERIOD = 10 minutes; uint private constant WAD = 1e18; IUniswapV3Pool public immutable uniswapV3Pool; uint public immutable uniswapTokenToPrice; // See constructor comment below. uint128 public immutable uniswapScaleFactor; /** * @notice Example pools to pass in: * USDC/ETH (0.05%): 0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640, 1, -12 * ETH/USDT (0.05%): 0x11b815efb8f581194ae79006d24e0d814b7697f6, 0, -12 * @param tokenToPrice Which token we're pricing (0 or 1) relative to the other. Eg, for the USDC/ETH pool (token0 = USDC, * token1 = ETH), we want the price of ETH in terms of USDC, not vice versa: so we should pass in `tokenToPrice == 1'. * @param decimalPlaces How many decimal places are already included in the numbers Uniswap returns. So, * `decimalPlaces = 3` means when Uniswap returns 12345, it actually represents 12.345 (ie, the last three digits were the * decimal part). `decimalPlaces = -3` means when Uniswap returns 12345, it actually represents 12,345,000. */ constructor(IUniswapV3Pool pool, uint tokenToPrice, int decimalPlaces) { uniswapV3Pool = pool; require(tokenToPrice == 0 || tokenToPrice == 1, "tokenToPrice not 0 or 1"); uniswapTokenToPrice = tokenToPrice; // We want latestPrice() to return WAD-fixed-point (18-decimal-place) numbers. So, eg, if Uniswap's output numbers // include 3 decimal places (ie, are already scaled by 10**3), we need to scale them by another 10**15: uniswapScaleFactor = uint128(decimalPlaces >= 0 ? WAD / 10 ** uint(decimalPlaces) : WAD * 10 ** uint(-decimalPlaces)); } function latestPrice() public virtual override view returns (uint price, uint updateTime) { int24 twapTick = OracleLibrary.consult(address(uniswapV3Pool), UNISWAP_TWAP_PERIOD); price = uniswapTokenToPrice == 1 ? OracleLibrary.getQuoteAtTick(twapTick, uniswapScaleFactor, uniswapV3Pool.token1(), uniswapV3Pool.token0()) : OracleLibrary.getQuoteAtTick(twapTick, uniswapScaleFactor, uniswapV3Pool.token0(), uniswapV3Pool.token1()); (,, uint16 observationIndex,,,,) = uniswapV3Pool.slot0(); (updateTime,,,) = uniswapV3Pool.observations(observationIndex); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; //import "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol"; import "./uniswap/v3-periphery/OracleLibrary.sol"; import "./Oracle.sol"; /** * This is all just a copy of UniswapV3TWAPOracle, so that MedianOracle can inherit both of them without conflicts. It would * of course be cleaner to make MedianOracle hold them as member variables, but that would cost more gas due to external calls. */ contract UniswapV3TWAPOracle2 is Oracle { uint32 public constant UNISWAP_TWAP_PERIOD_2 = 10 minutes; uint private constant WAD = 1e18; IUniswapV3Pool public immutable uniswapV3Pool2; uint public immutable uniswapTokenToPrice2; uint128 public immutable uniswapScaleFactor2; constructor(IUniswapV3Pool pool, uint tokenToPrice, int decimalPlaces) { uniswapV3Pool2 = pool; require(tokenToPrice == 0 || tokenToPrice == 1, "tokenToPrice not 0 or 1"); uniswapTokenToPrice2 = tokenToPrice; uniswapScaleFactor2 = uint128(decimalPlaces >= 0 ? WAD / 10 ** uint(decimalPlaces) : WAD * 10 ** uint(-decimalPlaces)); } function latestPrice() public virtual override view returns (uint price, uint updateTime) { int24 twapTick = OracleLibrary.consult(address(uniswapV3Pool2), UNISWAP_TWAP_PERIOD_2); price = uniswapTokenToPrice2 == 1 ? OracleLibrary.getQuoteAtTick(twapTick, uniswapScaleFactor2, uniswapV3Pool2.token1(), uniswapV3Pool2.token0()) : OracleLibrary.getQuoteAtTick(twapTick, uniswapScaleFactor2, uniswapV3Pool2.token0(), uniswapV3Pool2.token1()); (,, uint16 observationIndex,,,,) = uniswapV3Pool2.slot0(); (updateTime,,,) = uniswapV3Pool2.observations(observationIndex); } } pragma solidity >=0.6.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: GPL-3.0-or-later pragma solidity ^0.8.0; abstract contract Oracle { /** * @return price WAD-scaled - 18 dec places * @return updateTime The last time the price was updated. This is a bit subtle: `price` can change without `updateTime` * changing. Suppose, eg, the current Uniswap v3 TWAP price over the last 10 minutes is $3,000, and then Uniswap records a * new trade observation at a price of $2,980. This will nudge the 10-minute TWAP slightly below $3,000, and reset * `updateTime` to the new trade's time. However, over the subsequent 10 minutes, the 10-minute TWAP will continue to * decrease, as more and more of "the last 10 minutes" is at $2,980 rather than $3,000: but because this gradual price * change is only driven by the passage of time, not by any new price observations, it will *not* change `updateTime`, * which will remain at the time of the $2,980 trade until another trade occurs. */ function latestPrice() public virtual view returns (uint price, uint updateTime); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; //import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '../v3-core/FullMath.sol'; //import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '../v3-core/TickMath.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; //import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol'; import './PoolAddress.sol'; /// @title Oracle library /// @notice Provides functions to integrate with V3 pool oracle library OracleLibrary { /// @notice Fetches time-weighted average tick using Uniswap V3 oracle /// @param pool Address of Uniswap V3 pool that we want to observe /// @param period Number of seconds in the past to start calculating time-weighted average /// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) { require(period != 0, 'BP'); uint32[] memory secondAgos = new uint32[](2); secondAgos[0] = period; secondAgos[1] = 0; (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; timeWeightedAverageTick = int24(tickCumulativesDelta / int56(uint56(period))); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(period)) != 0)) timeWeightedAverageTick--; } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param tick Tick value used to calculate the quote /// @param baseAmount Amount of token to be converted /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a�b�denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (~denominator + 1) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a�b�denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int256 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 uint256 internal constant MAX_TICK = uint256(-MIN_TICK); /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= MAX_TICK, 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint160( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ) ); } }
Retrieve the latest price of the price oracle. return price/
function latestPrice() public virtual override view returns (uint price, uint updateTime) { int rawPrice; (, rawPrice,, updateTime,) = chainlinkAggregator.latestRoundData(); require(rawPrice > 0, "Chainlink price <= 0"); price = uint(rawPrice) * CHAINLINK_SCALE_FACTOR; }
9,957,878
/** *Submitted for verification at Etherscan.io on 2022-04-08 */ // File: @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: bsc-library/contracts/IBEP20.sol pragma solidity >=0.4.0; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @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.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: bsc-library/contracts/SafeBEP20.sol pragma solidity ^0.6.0; /** * @title SafeBEP20 * @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer( IBEP20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IBEP20 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 * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IBEP20 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), "SafeBEP20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IBEP20 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( IBEP20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeBEP20: 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(IBEP20 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, "SafeBEP20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeBEP20: BEP20 operation did not succeed"); } } } // File: contracts/SmartChefInitializable.sol pragma solidity 0.6.12; contract StakingContract2 is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Whether it is initialized bool public isInitialized; // Accrued token per share uint256 public accTokenPerShare; // The block number when KISHI reward ends. uint256 public bonusEndBlock; // The block number when KISHI reward starts. uint256 public startBlock; // The block number of the last pool update uint256 public lastRewardBlock; // KATSUMI tokens reward per block. uint256 public rewardPerBlock; // The precision factor uint256 public PRECISION_FACTOR; // The reward token IBEP20 public rewardToken; // The staked token IBEP20 public stakedToken; // locking period uint256 public lockingPeriod; // total staked tokens uint256 public totalDeposit; // Info of each user that stakes tokens (stakedToken) mapping(address => UserInfo) public userInfo; struct UserInfo { uint256 amount; // How many staked tokens the user has provided uint256 rewardDebt; // Reward debt } struct LockedBalance { uint256 amount; uint256 unlockTime; } mapping(address => LockedBalance[]) public userLocks; event AdminTokenRecovery(address tokenRecovered, uint256 amount); event Deposit(address indexed user, uint256 amount); event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock); event NewRewardPerBlock(uint256 rewardPerBlock); event RewardsStop(uint256 blockNumber); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); constructor() public {} /* * @notice Initialize the contract * @param _stakedToken: staked token address * @param _rewardToken: reward token address * @param _rewardPerBlock: reward per block (in rewardToken) * @param _startBlock: start block * @param _bonusEndBlock: end block * @param _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0) * @param _admin: admin address with ownership */ function initialize( IBEP20 _stakedToken, IBEP20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _lockingPeriod ) external onlyOwner { require(!isInitialized, "Already initialized"); // Make this contract initialized isInitialized = true; stakedToken = _stakedToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; lockingPeriod = _lockingPeriod; uint256 decimalsRewardToken = uint256(rewardToken.decimals()); require(decimalsRewardToken < 30, "Must be inferior to 30"); PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken))); // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; } function modifyTimes(uint256 _startTime, uint256 _endTime, uint256 _reward) public onlyOwner { startBlock = _startTime; bonusEndBlock = _endTime; rewardPerBlock = _reward; lastRewardBlock = startBlock; } /* * @notice Deposit staked tokens and collect reward tokens (if any) * @param _amount: amount to withdraw (in rewardToken) */ function deposit(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; _updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } } if (_amount > 0) { stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } uint256 unlockTime = block.timestamp.add(lockingPeriod); user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); userLocks[msg.sender].push(LockedBalance({amount: _amount, unlockTime: unlockTime})); totalDeposit = totalDeposit.add(_amount); emit Deposit(msg.sender, _amount); } function harvest() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; require(user.amount > 0, "No staked amount"); _updatePool(); uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); require(pending > 0, "No reward to harvest"); rewardToken.safeTransfer(address(msg.sender), pending); user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); } // Final balance received and penalty balance paid by user upon calling exit function withdrawableBalance(address account) view public returns (uint256 unlockedAmount) { UserInfo storage user = userInfo[account]; if (user.amount > 0) { uint256 length = userLocks[account].length; for (uint i = 0; i < length; i++) { uint256 lockedAmount = userLocks[account][i].amount; if (lockedAmount == 0) continue; if (userLocks[account][i].unlockTime > block.timestamp) { break; } unlockedAmount = unlockedAmount.add(lockedAmount); } } return (unlockedAmount); } // Withdraw all currently locked tokens where the unlock time has passed function withdrawExpiredLocks() external { UserInfo storage user = userInfo[msg.sender]; _updatePool(); uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); LockedBalance[] storage locks = userLocks[msg.sender]; uint256 amount; uint256 length = locks.length; if (locks[length-1].unlockTime <= block.timestamp) { amount = user.amount; delete userLocks[msg.sender]; } else { for (uint i = 0; i < length; i++) { if (locks[i].unlockTime > block.timestamp) break; amount = amount.add(locks[i].amount); delete locks[i]; } } user.amount = user.amount.sub(amount); stakedToken.safeTransfer(msg.sender, amount); if (pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); totalDeposit = totalDeposit.sub(amount); emit Withdraw(msg.sender, amount); } /* * @notice Withdraw unlocked tokens without caring about rewards * @dev Needs to be for emergency. */ function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; _updatePool(); LockedBalance[] storage locks = userLocks[msg.sender]; uint256 amount; uint256 length = locks.length; if (locks[length-1].unlockTime <= block.timestamp) { amount = user.amount; delete userLocks[msg.sender]; } else { for (uint i = 0; i < length; i++) { if (locks[i].unlockTime > block.timestamp) break; amount = amount.add(locks[i].amount); delete locks[i]; } } user.amount = user.amount.sub(amount); stakedToken.safeTransfer(msg.sender, amount); user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); totalDeposit = totalDeposit.sub(amount); emit EmergencyWithdraw(msg.sender, amount); } /* * @notice Stop rewards * @dev Only callable by owner. Needs to be for emergency. */ function emergencyRewardWithdraw(uint256 _amount) external onlyOwner { uint256 tokenBalance = rewardToken.balanceOf(address(this)); require(_amount <= tokenBalance.sub(totalDeposit), "Withdrawing more than reward left"); rewardToken.safeTransfer(address(msg.sender), _amount); } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of tokens to withdraw * @dev This function is only callable by admin. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require(_tokenAddress != address(stakedToken), "Cannot be staked token"); require(_tokenAddress != address(rewardToken), "Cannot be reward token"); IBEP20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /* * @notice Stop rewards * @dev Only callable by owner */ function stopReward() external onlyOwner { bonusEndBlock = block.number; } /* * @notice Update reward per block * @dev Only callable by owner. * @param _rewardPerBlock: the reward per block */ function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { rewardPerBlock = _rewardPerBlock; emit NewRewardPerBlock(_rewardPerBlock); } /** * @notice It allows the admin to update start and end blocks * @dev This function is only callable by owner. * @param _startBlock: the new start block * @param _bonusEndBlock: the new end block */ function updateStartAndEndBlocks(uint256 _startBlock, uint256 _bonusEndBlock) external onlyOwner { require(block.number < startBlock, "Pool has started"); require(_startBlock < _bonusEndBlock, "New startBlock must be lower than new endBlock"); require(block.number < _startBlock, "New startBlock must be higher than current block"); startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; emit NewStartAndEndBlocks(_startBlock, _bonusEndBlock); } /* * @notice View function to see pending reward on frontend. * @param _user: user address * @return Pending reward for a given user */ function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 stakedTokenSupply = totalDeposit; if (block.number > lastRewardBlock && stakedTokenSupply != 0) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 kishiReward = multiplier.mul(rewardPerBlock); uint256 adjustedTokenPerShare = accTokenPerShare.add(kishiReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)); return user.amount.mul(adjustedTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); } else { return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); } } /* * @notice Update reward variables of the given pool to be up-to-date. */ function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } uint256 stakedTokenSupply = totalDeposit; if (stakedTokenSupply == 0) { lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 kishiReward = multiplier.mul(rewardPerBlock); accTokenPerShare = accTokenPerShare.add(kishiReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)); lastRewardBlock = block.number; } /* * @notice Return reward multiplier over the given _from to _to block. * @param _from: block to start * @param _to: block to finish */ function _getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from); } else if (_from >= bonusEndBlock) { return 0; } else { return bonusEndBlock.sub(_from); } } }
Withdraw all currently locked tokens where the unlock time has passed
function withdrawExpiredLocks() external { UserInfo storage user = userInfo[msg.sender]; _updatePool(); uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); LockedBalance[] storage locks = userLocks[msg.sender]; uint256 amount; uint256 length = locks.length; if (locks[length-1].unlockTime <= block.timestamp) { amount = user.amount; delete userLocks[msg.sender]; for (uint i = 0; i < length; i++) { if (locks[i].unlockTime > block.timestamp) break; amount = amount.add(locks[i].amount); delete locks[i]; } } user.amount = user.amount.sub(amount); stakedToken.safeTransfer(msg.sender, amount); if (pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); totalDeposit = totalDeposit.sub(amount); emit Withdraw(msg.sender, amount); }
7,759,169
// SPDX-License-Identifier: MIT pragma solidity >=0.6.8; 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); } 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; } 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; } 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; } // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas 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 (r < r1 ? r : r1); } } /** * @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; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // library containing some math for dealing with the liquidity shares of a pair, e.g. computing their exact value // in terms of the underlying tokens library UniswapV2LiquidityMathLibrary { using SafeMath for uint256; // computes the direction and magnitude of the profit-maximizing trade function computeProfitMaximizingTrade( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) pure internal returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant.mul(1000), aToB ? truePriceTokenA : truePriceTokenB, (aToB ? truePriceTokenB : truePriceTokenA).mul(997) ) ); uint256 rightSide = (aToB ? reserveA.mul(1000) : reserveB.mul(1000)) / 997; if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price to the profit-maximizing price amountIn = leftSide.sub(rightSide); } // gets the reserves after an arbitrage moves the price to the profit-maximizing ratio given an externally observed true price function getReservesAfterArbitrage( address factory, address tokenA, address tokenB, uint256 truePriceTokenA, uint256 truePriceTokenB ) view internal returns (uint256 reserveA, uint256 reserveB) { // first get reserves before the swap (reserveA, reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); require(reserveA > 0 && reserveB > 0, 'UniswapV2ArbitrageLibrary: ZERO_PAIR_RESERVES'); // then compute how much to swap to arb to the true price (bool aToB, uint256 amountIn) = computeProfitMaximizingTrade(truePriceTokenA, truePriceTokenB, reserveA, reserveB); if (amountIn == 0) { return (reserveA, reserveB); } // now affect the trade to the reserves if (aToB) { uint amountOut = UniswapV2Library.getAmountOut(amountIn, reserveA, reserveB); reserveA += amountIn; reserveB -= amountOut; } else { uint amountOut = UniswapV2Library.getAmountOut(amountIn, reserveB, reserveA); reserveB += amountIn; reserveA -= amountOut; } } // computes liquidity value given all the parameters of the pair function computeLiquidityValue( uint256 reservesA, uint256 reservesB, uint256 totalSupply, uint256 liquidityAmount, bool feeOn, uint kLast ) internal pure returns (uint256 tokenAAmount, uint256 tokenBAmount) { if (feeOn && kLast > 0) { uint rootK = Babylonian.sqrt(reservesA.mul(reservesB)); uint rootKLast = Babylonian.sqrt(kLast); if (rootK > rootKLast) { uint numerator1 = totalSupply; uint numerator2 = rootK.sub(rootKLast); uint denominator = rootK.mul(5).add(rootKLast); uint feeLiquidity = FullMath.mulDiv(numerator1, numerator2, denominator); totalSupply = totalSupply.add(feeLiquidity); } } return (reservesA.mul(liquidityAmount) / totalSupply, reservesB.mul(liquidityAmount) / totalSupply); } // get all current parameters from the pair and compute value of a liquidity amount // **note this is subject to manipulation, e.g. sandwich attacks**. prefer passing a manipulation resistant price to // #getLiquidityValueAfterArbitrageToPrice function getLiquidityValue( address factory, address tokenA, address tokenB, uint256 liquidityAmount ) internal view returns (uint256 tokenAAmount, uint256 tokenBAmount) { (uint256 reservesA, uint256 reservesB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); bool feeOn = IUniswapV2Factory(factory).feeTo() != address(0); uint kLast = feeOn ? pair.kLast() : 0; uint totalSupply = pair.totalSupply(); return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast); } // given two tokens, tokenA and tokenB, and their "true price", i.e. the observed ratio of value of token A to token B, // and a liquidity amount, returns the value of the liquidity in terms of tokenA and tokenB function getLiquidityValueAfterArbitrageToPrice( address factory, address tokenA, address tokenB, uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 liquidityAmount ) internal view returns ( uint256 tokenAAmount, uint256 tokenBAmount ) { bool feeOn = IUniswapV2Factory(factory).feeTo() != address(0); IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); uint kLast = feeOn ? pair.kLast() : 0; uint totalSupply = pair.totalSupply(); // this also checks that totalSupply > 0 require(totalSupply >= liquidityAmount && liquidityAmount > 0, 'ComputeLiquidityValue: LIQUIDITY_AMOUNT'); (uint reservesA, uint reservesB) = getReservesAfterArbitrage(factory, tokenA, tokenB, truePriceTokenA, truePriceTokenB); return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast); } } // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function decimals() external view returns (uint256); function symbol() external view returns (string memory); /** * @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"); } } /** * @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 _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"); } } }
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function decimals() external view returns (uint256); function symbol() external view returns (string memory); 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); }
1,785,458
./full_match/1/0x70996FeE3bc1BA38e36Ea356aee5d855161e6e52/sources/contracts/CrossChainPortal.sol
inheritdoc IGuardable
function setGuardians(address[] calldata guardians, bool[] calldata enableds) external override onlySelf { _setGuardians(guardians, enableds); }
16,577,462
// File: contracts/components/Proxy.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.24; /** * Math operations with safety checks */ contract Proxy { event Upgraded(address indexed implementation); address internal _implementation; function implementation() public view returns (address) { return _implementation; } function () external payable { address _impl = _implementation; require(_impl != address(0), "implementation contract not set"); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: contracts/components/Owned.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.24; /// @dev `Owned` is a base level contract that assigns an `owner` that can be /// later changed contract Owned { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _; } address public owner; /// @notice The Constructor assigns the message sender to be `owner` constructor() public { owner = msg.sender; } address public newOwner; function transferOwner(address _newOwner) public onlyOwner { require(_newOwner != address(0), "New owner is the zero address"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner. 0x0 can be used to create /// an unowned neutral vault, however that cannot be undone function changeOwner(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; } } function renounceOwnership() public onlyOwner { owner = address(0); } } // File: contracts/components/Halt.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.24; contract Halt is Owned { bool public halted = false; modifier notHalted() { require(!halted, "Smart contract is halted"); _; } modifier isHalted() { require(halted, "Smart contract is not halted"); _; } /// @notice function Emergency situation that requires /// @notice contribution period to stop or not. function setHalt(bool halt) public onlyOwner { halted = halt; } } // File: contracts/components/ReentrancyGuard.sol pragma solidity 0.4.26; /** * @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 { bool private _notEntered; constructor () internal { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: contracts/lib/BasicStorageLib.sol pragma solidity ^0.4.24; library BasicStorageLib { struct UintData { mapping(bytes => mapping(bytes => uint)) _storage; } struct BoolData { mapping(bytes => mapping(bytes => bool)) _storage; } struct AddressData { mapping(bytes => mapping(bytes => address)) _storage; } struct BytesData { mapping(bytes => mapping(bytes => bytes)) _storage; } struct StringData { mapping(bytes => mapping(bytes => string)) _storage; } /* uintStorage */ function setStorage(UintData storage self, bytes memory key, bytes memory innerKey, uint value) internal { self._storage[key][innerKey] = value; } function getStorage(UintData storage self, bytes memory key, bytes memory innerKey) internal view returns (uint) { return self._storage[key][innerKey]; } function delStorage(UintData storage self, bytes memory key, bytes memory innerKey) internal { delete self._storage[key][innerKey]; } /* boolStorage */ function setStorage(BoolData storage self, bytes memory key, bytes memory innerKey, bool value) internal { self._storage[key][innerKey] = value; } function getStorage(BoolData storage self, bytes memory key, bytes memory innerKey) internal view returns (bool) { return self._storage[key][innerKey]; } function delStorage(BoolData storage self, bytes memory key, bytes memory innerKey) internal { delete self._storage[key][innerKey]; } /* addressStorage */ function setStorage(AddressData storage self, bytes memory key, bytes memory innerKey, address value) internal { self._storage[key][innerKey] = value; } function getStorage(AddressData storage self, bytes memory key, bytes memory innerKey) internal view returns (address) { return self._storage[key][innerKey]; } function delStorage(AddressData storage self, bytes memory key, bytes memory innerKey) internal { delete self._storage[key][innerKey]; } /* bytesStorage */ function setStorage(BytesData storage self, bytes memory key, bytes memory innerKey, bytes memory value) internal { self._storage[key][innerKey] = value; } function getStorage(BytesData storage self, bytes memory key, bytes memory innerKey) internal view returns (bytes memory) { return self._storage[key][innerKey]; } function delStorage(BytesData storage self, bytes memory key, bytes memory innerKey) internal { delete self._storage[key][innerKey]; } /* stringStorage */ function setStorage(StringData storage self, bytes memory key, bytes memory innerKey, string memory value) internal { self._storage[key][innerKey] = value; } function getStorage(StringData storage self, bytes memory key, bytes memory innerKey) internal view returns (string memory) { return self._storage[key][innerKey]; } function delStorage(StringData storage self, bytes memory key, bytes memory innerKey) internal { delete self._storage[key][innerKey]; } } // File: contracts/components/BasicStorage.sol pragma solidity ^0.4.24; contract BasicStorage { /************************************************************ ** ** VARIABLES ** ************************************************************/ //// basic variables using BasicStorageLib for BasicStorageLib.UintData; using BasicStorageLib for BasicStorageLib.BoolData; using BasicStorageLib for BasicStorageLib.AddressData; using BasicStorageLib for BasicStorageLib.BytesData; using BasicStorageLib for BasicStorageLib.StringData; BasicStorageLib.UintData internal uintData; BasicStorageLib.BoolData internal boolData; BasicStorageLib.AddressData internal addressData; BasicStorageLib.BytesData internal bytesData; BasicStorageLib.StringData internal stringData; } // File: contracts/interfaces/IRC20Protocol.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.26; interface IRC20Protocol { function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); function balanceOf(address _owner) external view returns (uint); } // File: contracts/interfaces/IQuota.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity 0.4.26; interface IQuota { function userMintLock(uint tokenId, bytes32 storemanGroupId, uint value) external; function userMintRevoke(uint tokenId, bytes32 storemanGroupId, uint value) external; function userMintRedeem(uint tokenId, bytes32 storemanGroupId, uint value) external; function smgMintLock(uint tokenId, bytes32 storemanGroupId, uint value) external; function smgMintRevoke(uint tokenId, bytes32 storemanGroupId, uint value) external; function smgMintRedeem(uint tokenId, bytes32 storemanGroupId, uint value) external; function userBurnLock(uint tokenId, bytes32 storemanGroupId, uint value) external; function userBurnRevoke(uint tokenId, bytes32 storemanGroupId, uint value) external; function userBurnRedeem(uint tokenId, bytes32 storemanGroupId, uint value) external; function smgBurnLock(uint tokenId, bytes32 storemanGroupId, uint value) external; function smgBurnRevoke(uint tokenId, bytes32 storemanGroupId, uint value) external; function smgBurnRedeem(uint tokenId, bytes32 storemanGroupId, uint value) external; function userFastMint(uint tokenId, bytes32 storemanGroupId, uint value) external; function userFastBurn(uint tokenId, bytes32 storemanGroupId, uint value) external; function smgFastMint(uint tokenId, bytes32 storemanGroupId, uint value) external; function smgFastBurn(uint tokenId, bytes32 storemanGroupId, uint value) external; function assetLock(bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId) external; function assetRedeem(bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId) external; function assetRevoke(bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId) external; function debtLock(bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId) external; function debtRedeem(bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId) external; function debtRevoke(bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId) external; function getUserMintQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint); function getSmgMintQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint); function getUserBurnQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint); function getSmgBurnQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint); function getAsset(uint tokenId, bytes32 storemanGroupId) external view returns (uint asset, uint asset_receivable, uint asset_payable); function getDebt(uint tokenId, bytes32 storemanGroupId) external view returns (uint debt, uint debt_receivable, uint debt_payable); function isDebtClean(bytes32 storemanGroupId) external view returns (bool); } // File: contracts/interfaces/IStoremanGroup.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.24; interface IStoremanGroup { function getSelectedSmNumber(bytes32 groupId) external view returns(uint number); function getStoremanGroupConfig(bytes32 id) external view returns(bytes32 groupId, uint8 status, uint deposit, uint chain1, uint chain2, uint curve1, uint curve2, bytes gpk1, bytes gpk2, uint startTime, uint endTime); function getDeposit(bytes32 id) external view returns(uint); function getStoremanGroupStatus(bytes32 id) external view returns(uint8 status, uint startTime, uint endTime); function setGpk(bytes32 groupId, bytes gpk1, bytes gpk2) external; function setInvalidSm(bytes32 groupId, uint[] indexs, uint8[] slashTypes) external returns(bool isContinue); function getThresholdByGrpId(bytes32 groupId) external view returns (uint); function getSelectedSmInfo(bytes32 groupId, uint index) external view returns(address wkAddr, bytes PK, bytes enodeId); function recordSmSlash(address wk) public; } // File: contracts/interfaces/ITokenManager.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity 0.4.26; interface ITokenManager { function getTokenPairInfo(uint id) external view returns (uint origChainID, bytes tokenOrigAccount, uint shadowChainID, bytes tokenShadowAccount); function getTokenPairInfoSlim(uint id) external view returns (uint origChainID, bytes tokenOrigAccount, uint shadowChainID); function mintToken(uint id, address to,uint value) external; function burnToken(uint id, uint value) external; } // File: contracts/interfaces/ISignatureVerifier.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity 0.4.26; interface ISignatureVerifier { function verify( uint curveId, bytes32 signature, bytes32 groupKeyX, bytes32 groupKeyY, bytes32 randomPointX, bytes32 randomPointY, bytes32 message ) external returns (bool); } // File: contracts/lib/SafeMath.sol pragma solidity ^0.4.24; /** * Math operations with safety checks */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath mul overflow"); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath div 0"); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub b > a"); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath add overflow"); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath mod 0"); return a % b; } } // File: contracts/crossApproach/lib/HTLCTxLib.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.26; pragma experimental ABIEncoderV2; library HTLCTxLib { using SafeMath for uint; /** * * ENUMS * */ /// @notice tx info status /// @notice uninitialized,locked,redeemed,revoked enum TxStatus {None, Locked, Redeemed, Revoked} /** * * STRUCTURES * */ /// @notice struct of HTLC user mint lock parameters struct HTLCUserParams { bytes32 xHash; /// hash of HTLC random number bytes32 smgID; /// ID of storeman group which user has selected uint tokenPairID; /// token pair id on cross chain uint value; /// exchange token value uint lockFee; /// exchange token value uint lockedTime; /// HTLC lock time } /// @notice HTLC(Hashed TimeLock Contract) tx info struct BaseTx { bytes32 smgID; /// HTLC transaction storeman ID uint lockedTime; /// HTLC transaction locked time uint beginLockedTime; /// HTLC transaction begin locked time TxStatus status; /// HTLC transaction status } /// @notice user tx info struct UserTx { BaseTx baseTx; uint tokenPairID; uint value; uint fee; address userAccount; /// HTLC transaction sender address for the security check while user's revoke } /// @notice storeman tx info struct SmgTx { BaseTx baseTx; uint tokenPairID; uint value; address userAccount; /// HTLC transaction user address for the security check while user's redeem } /// @notice storeman debt tx info struct DebtTx { BaseTx baseTx; bytes32 srcSmgID; /// HTLC transaction sender(source storeman) ID } struct Data { /// @notice mapping of hash(x) to UserTx -- xHash->htlcUserTxData mapping(bytes32 => UserTx) mapHashXUserTxs; /// @notice mapping of hash(x) to SmgTx -- xHash->htlcSmgTxData mapping(bytes32 => SmgTx) mapHashXSmgTxs; /// @notice mapping of hash(x) to DebtTx -- xHash->htlcDebtTxData mapping(bytes32 => DebtTx) mapHashXDebtTxs; } /** * * MANIPULATIONS * */ /// @notice add user transaction info /// @param params parameters for user tx function addUserTx(Data storage self, HTLCUserParams memory params) public { UserTx memory userTx = self.mapHashXUserTxs[params.xHash]; // UserTx storage userTx = self.mapHashXUserTxs[params.xHash]; // require(params.value != 0, "Value is invalid"); require(userTx.baseTx.status == TxStatus.None, "User tx exists"); userTx.baseTx.smgID = params.smgID; userTx.baseTx.lockedTime = params.lockedTime; userTx.baseTx.beginLockedTime = now; userTx.baseTx.status = TxStatus.Locked; userTx.tokenPairID = params.tokenPairID; userTx.value = params.value; userTx.fee = params.lockFee; userTx.userAccount = msg.sender; self.mapHashXUserTxs[params.xHash] = userTx; } /// @notice refund coins from HTLC transaction, which is used for storeman redeem(outbound) /// @param x HTLC random number function redeemUserTx(Data storage self, bytes32 x) external returns(bytes32 xHash) { xHash = sha256(abi.encodePacked(x)); UserTx storage userTx = self.mapHashXUserTxs[xHash]; require(userTx.baseTx.status == TxStatus.Locked, "Status is not locked"); require(now < userTx.baseTx.beginLockedTime.add(userTx.baseTx.lockedTime), "Redeem timeout"); userTx.baseTx.status = TxStatus.Redeemed; return xHash; } /// @notice revoke user transaction /// @param xHash hash of HTLC random number function revokeUserTx(Data storage self, bytes32 xHash) external { UserTx storage userTx = self.mapHashXUserTxs[xHash]; require(userTx.baseTx.status == TxStatus.Locked, "Status is not locked"); require(now >= userTx.baseTx.beginLockedTime.add(userTx.baseTx.lockedTime), "Revoke is not permitted"); userTx.baseTx.status = TxStatus.Revoked; } /// @notice function for get user info /// @param xHash hash of HTLC random number /// @return smgID ID of storeman which user has selected /// @return tokenPairID token pair ID of cross chain /// @return value exchange value /// @return fee exchange fee /// @return userAccount HTLC transaction sender address for the security check while user's revoke function getUserTx(Data storage self, bytes32 xHash) external view returns (bytes32, uint, uint, uint, address) { UserTx storage userTx = self.mapHashXUserTxs[xHash]; return (userTx.baseTx.smgID, userTx.tokenPairID, userTx.value, userTx.fee, userTx.userAccount); } /// @notice add storeman transaction info /// @param xHash hash of HTLC random number /// @param smgID ID of the storeman which user has selected /// @param tokenPairID token pair ID of cross chain /// @param value HTLC transfer value of token /// @param userAccount user account address on the destination chain, which is used to redeem token function addSmgTx(Data storage self, bytes32 xHash, bytes32 smgID, uint tokenPairID, uint value, address userAccount, uint lockedTime) external { SmgTx memory smgTx = self.mapHashXSmgTxs[xHash]; // SmgTx storage smgTx = self.mapHashXSmgTxs[xHash]; require(value != 0, "Value is invalid"); require(smgTx.baseTx.status == TxStatus.None, "Smg tx exists"); smgTx.baseTx.smgID = smgID; smgTx.baseTx.status = TxStatus.Locked; smgTx.baseTx.lockedTime = lockedTime; smgTx.baseTx.beginLockedTime = now; smgTx.tokenPairID = tokenPairID; smgTx.value = value; smgTx.userAccount = userAccount; self.mapHashXSmgTxs[xHash] = smgTx; } /// @notice refund coins from HTLC transaction, which is used for users redeem(inbound) /// @param x HTLC random number function redeemSmgTx(Data storage self, bytes32 x) external returns(bytes32 xHash) { xHash = sha256(abi.encodePacked(x)); SmgTx storage smgTx = self.mapHashXSmgTxs[xHash]; require(smgTx.baseTx.status == TxStatus.Locked, "Status is not locked"); require(now < smgTx.baseTx.beginLockedTime.add(smgTx.baseTx.lockedTime), "Redeem timeout"); smgTx.baseTx.status = TxStatus.Redeemed; return xHash; } /// @notice revoke storeman transaction /// @param xHash hash of HTLC random number function revokeSmgTx(Data storage self, bytes32 xHash) external { SmgTx storage smgTx = self.mapHashXSmgTxs[xHash]; require(smgTx.baseTx.status == TxStatus.Locked, "Status is not locked"); require(now >= smgTx.baseTx.beginLockedTime.add(smgTx.baseTx.lockedTime), "Revoke is not permitted"); smgTx.baseTx.status = TxStatus.Revoked; } /// @notice function for get smg info /// @param xHash hash of HTLC random number /// @return smgID ID of storeman which user has selected /// @return tokenPairID token pair ID of cross chain /// @return value exchange value /// @return userAccount user account address for redeem function getSmgTx(Data storage self, bytes32 xHash) external view returns (bytes32, uint, uint, address) { SmgTx storage smgTx = self.mapHashXSmgTxs[xHash]; return (smgTx.baseTx.smgID, smgTx.tokenPairID, smgTx.value, smgTx.userAccount); } /// @notice add storeman transaction info /// @param xHash hash of HTLC random number /// @param srcSmgID ID of source storeman group /// @param destSmgID ID of the storeman which will take over of the debt of source storeman group /// @param lockedTime HTLC lock time function addDebtTx(Data storage self, bytes32 xHash, bytes32 srcSmgID, bytes32 destSmgID, uint lockedTime) external { DebtTx memory debtTx = self.mapHashXDebtTxs[xHash]; // DebtTx storage debtTx = self.mapHashXDebtTxs[xHash]; require(debtTx.baseTx.status == TxStatus.None, "Debt tx exists"); debtTx.baseTx.smgID = destSmgID; debtTx.baseTx.status = TxStatus.Locked; debtTx.baseTx.lockedTime = lockedTime; debtTx.baseTx.beginLockedTime = now; debtTx.srcSmgID = srcSmgID; self.mapHashXDebtTxs[xHash] = debtTx; } /// @notice refund coins from HTLC transaction /// @param x HTLC random number function redeemDebtTx(Data storage self, bytes32 x) external returns(bytes32 xHash) { xHash = sha256(abi.encodePacked(x)); DebtTx storage debtTx = self.mapHashXDebtTxs[xHash]; require(debtTx.baseTx.status == TxStatus.Locked, "Status is not locked"); require(now < debtTx.baseTx.beginLockedTime.add(debtTx.baseTx.lockedTime), "Redeem timeout"); debtTx.baseTx.status = TxStatus.Redeemed; return xHash; } /// @notice revoke debt transaction, which is used for source storeman group /// @param xHash hash of HTLC random number function revokeDebtTx(Data storage self, bytes32 xHash) external { DebtTx storage debtTx = self.mapHashXDebtTxs[xHash]; require(debtTx.baseTx.status == TxStatus.Locked, "Status is not locked"); require(now >= debtTx.baseTx.beginLockedTime.add(debtTx.baseTx.lockedTime), "Revoke is not permitted"); debtTx.baseTx.status = TxStatus.Revoked; } /// @notice function for get debt info /// @param xHash hash of HTLC random number /// @return srcSmgID ID of source storeman /// @return destSmgID ID of destination storeman function getDebtTx(Data storage self, bytes32 xHash) external view returns (bytes32, bytes32) { DebtTx storage debtTx = self.mapHashXDebtTxs[xHash]; return (debtTx.srcSmgID, debtTx.baseTx.smgID); } function getLeftTime(uint endTime) private view returns (uint) { if (now < endTime) { return endTime.sub(now); } return 0; } /// @notice function for get debt info /// @param xHash hash of HTLC random number /// @return leftTime the left lock time function getLeftLockedTime(Data storage self, bytes32 xHash) external view returns (uint) { UserTx storage userTx = self.mapHashXUserTxs[xHash]; if (userTx.baseTx.status != TxStatus.None) { return getLeftTime(userTx.baseTx.beginLockedTime.add(userTx.baseTx.lockedTime)); } SmgTx storage smgTx = self.mapHashXSmgTxs[xHash]; if (smgTx.baseTx.status != TxStatus.None) { return getLeftTime(smgTx.baseTx.beginLockedTime.add(smgTx.baseTx.lockedTime)); } DebtTx storage debtTx = self.mapHashXDebtTxs[xHash]; if (debtTx.baseTx.status != TxStatus.None) { return getLeftTime(debtTx.baseTx.beginLockedTime.add(debtTx.baseTx.lockedTime)); } require(false, 'invalid xHash'); } } // File: contracts/crossApproach/lib/RapidityTxLib.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.26; library RapidityTxLib { /** * * ENUMS * */ /// @notice tx info status /// @notice uninitialized,Redeemed enum TxStatus {None, Redeemed} /** * * STRUCTURES * */ struct Data { /// @notice mapping of uniqueID to TxStatus -- uniqueID->TxStatus mapping(bytes32 => TxStatus) mapTxStatus; } /** * * MANIPULATIONS * */ /// @notice add user transaction info /// @param uniqueID Rapidity random number function addRapidityTx(Data storage self, bytes32 uniqueID) internal { TxStatus status = self.mapTxStatus[uniqueID]; require(status == TxStatus.None, "Rapidity tx exists"); self.mapTxStatus[uniqueID] = TxStatus.Redeemed; } } // File: contracts/crossApproach/lib/CrossTypes.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.26; library CrossTypes { using SafeMath for uint; /** * * STRUCTURES * */ struct Data { /// map of the htlc transaction info HTLCTxLib.Data htlcTxData; /// map of the rapidity transaction info RapidityTxLib.Data rapidityTxData; /// quota data of storeman group IQuota quota; /// token manager instance interface ITokenManager tokenManager; /// storemanGroup admin instance interface IStoremanGroup smgAdminProxy; /// storemanGroup fee admin instance address address smgFeeProxy; ISignatureVerifier sigVerifier; /// @notice transaction fee, smgID => fee mapping(bytes32 => uint) mapStoremanFee; /// @notice transaction fee, origChainID => shadowChainID => fee mapping(uint => mapping(uint =>uint)) mapLockFee; /// @notice transaction fee, origChainID => shadowChainID => fee mapping(uint => mapping(uint =>uint)) mapRevokeFee; } /** * * MANIPULATIONS * */ // /// @notice convert bytes32 to address // /// @param b bytes32 // function bytes32ToAddress(bytes32 b) internal pure returns (address) { // return address(uint160(bytes20(b))); // high // // return address(uint160(uint256(b))); // low // } /// @notice convert bytes to address /// @param b bytes function bytesToAddress(bytes b) internal pure returns (address addr) { assembly { addr := mload(add(b,20)) } } function transfer(address tokenScAddr, address to, uint value) internal returns(bool) { uint beforeBalance; uint afterBalance; beforeBalance = IRC20Protocol(tokenScAddr).balanceOf(to); // IRC20Protocol(tokenScAddr).transfer(to, value); tokenScAddr.call(bytes4(keccak256("transfer(address,uint256)")), to, value); afterBalance = IRC20Protocol(tokenScAddr).balanceOf(to); return afterBalance == beforeBalance.add(value); } function transferFrom(address tokenScAddr, address from, address to, uint value) internal returns(bool) { uint beforeBalance; uint afterBalance; beforeBalance = IRC20Protocol(tokenScAddr).balanceOf(to); // IRC20Protocol(tokenScAddr).transferFrom(from, to, value); tokenScAddr.call(bytes4(keccak256("transferFrom(address,address,uint256)")), from, to, value); afterBalance = IRC20Protocol(tokenScAddr).balanceOf(to); return afterBalance == beforeBalance.add(value); } } // File: contracts/crossApproach/CrossStorage.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.26; contract CrossStorage is BasicStorage { using HTLCTxLib for HTLCTxLib.Data; using RapidityTxLib for RapidityTxLib.Data; /************************************************************ ** ** VARIABLES ** ************************************************************/ CrossTypes.Data internal storageData; /// @notice locked time(in seconds) uint public lockedTime = uint(3600*36); /// @notice Since storeman group admin receiver address may be changed, system should make sure the new address /// @notice can be used, and the old address can not be used. The solution is add timestamp. /// @notice unit: second uint public smgFeeReceiverTimeout = uint(10*60); enum GroupStatus { none, initial, curveSeted, failed, selected, ready, unregistered, dismissed } } // File: contracts/crossApproach/CrossProxy.sol /* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.26; /** * Math operations with safety checks */ contract CrossProxy is CrossStorage, ReentrancyGuard, Halt, Proxy { ///@dev update the address of CrossDelegate contract ///@param impl the address of the new CrossDelegate contract function upgradeTo(address impl) public onlyOwner { require(impl != address(0), "Cannot upgrade to invalid address"); require(impl != _implementation, "Cannot upgrade to the same implementation"); _implementation = impl; emit Upgraded(impl); } }
Divides two numbers and returns the remainder (unsigned integer modulo), reverts when dividing by zero./
function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath mod 0"); return a % b; }
882,880
// Permit pattern copied from BAL https://etherscan.io/address/0xba100000625a3754423978a60c9317c58a424e3d#code pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC20Permit is ERC20 { string public constant version = "1"; bytes32 public immutable DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public immutable PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public permitNonces; constructor(string memory name, string memory symbol) public ERC20(name, symbol) { uint256 chainId = getChainId(); DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } function getChainId() internal pure returns (uint256) { uint256 chainID; assembly { chainID := chainid() } return chainID; } function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(block.timestamp <= deadline, "ERR_EXPIRED_SIG"); bytes32 digest = keccak256( abi.encodePacked( uint16(0x1901), DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, permitNonces[owner]++, deadline)) ) ); require(owner == _recover(digest, v, r, s), "ERR_INVALID_SIG"); _approve(owner, spender, value); } function _recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) private pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } } pragma solidity 0.6.12; import "./ERC20Permit.sol"; contract Idle is ERC20Permit { constructor() public ERC20Permit("Idle", "IDLE") { _mint(msg.sender, 13000000 * 10**18); // 13M } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); 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), "IDLE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "IDLE::delegateBySig: invalid nonce"); require(now <= expiry, "IDLE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * ERC20 modified transferFrom that also update the avgPrice paid for the recipient and * updates user gov idx * * @param sender : sender account * @param recipient : recipient account * @param amount : value to transfer * @return : flag whether transfer was successful or not */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, allowance(sender, msg.sender).sub(amount, "ERC20: transfer amount exceeds allowance")); _moveDelegates(_delegates[sender], _delegates[recipient], amount); return true; } /** * ERC20 modified transfer that also update the delegates * * @param recipient : recipient account * @param amount : value to transfer * @return : flag whether transfer was successful or not */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, recipient, amount); _moveDelegates(_delegates[msg.sender], _delegates[recipient], amount); return true; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "IDLE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying IDLEs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "IDLE::_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); } } pragma solidity 0.6.12; import "./VesterFactory.sol"; import "./Vester.sol"; import "./Idle.sol"; contract LockedIDLE { address public constant IDLE = address(0x875773784Af8135eA0ef43b5a374AaD105c5D39e); address public constant vestingFactory = address(0xbF875f2C6e4Cc1688dfe4ECf79583193B6089972); Idle public idle; VesterFactory public factory; constructor() public { idle = Idle(IDLE); factory = VesterFactory(vestingFactory); } function balanceOf(address _user) public view returns (uint256) { address vestingContract = factory.vestingContracts(_user); if (vestingContract == address(0)) { return 0; } if (_user == address(0x4191dbEe094bDFD087f14791E7D7084f5e92447e)) { return idle.balanceOf(0x6405127E97C3c9D0FB49a48a3332F82581a1EE03); } uint256 balance = idle.balanceOf(vestingContract); // team members have 1/10th of the voting power if (_user == address(0x3675D2A334f17bCD4689533b7Af263D48D96eC72) || _user == address(0x4F314638B730Bc46Df5e600E524267d0641C98B4) || _user == address(0xd889Acb680D5eDbFeE593d2b7355a666248bAB9b) || _user == address(0xaDa343Cb6820F4f5001749892f6CAA9920129F2A) ) { return balance / 10; } return balance; } } pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Vester { using SafeMath for uint; address public idle; address public recipient; uint public vestingAmount; uint public vestingBegin; uint public vestingCliff; uint public vestingEnd; uint public lastUpdate; constructor( address idle_, address recipient_, uint vestingAmount_, uint vestingBegin_, uint vestingCliff_, uint vestingEnd_ ) public { require(vestingBegin_ >= block.timestamp, 'TreasuryVester::constructor: vesting begin too early'); require(vestingCliff_ >= vestingBegin_, 'TreasuryVester::constructor: cliff is too early'); require(vestingEnd_ > vestingCliff_, 'TreasuryVester::constructor: end is too early'); idle = idle_; recipient = recipient_; vestingAmount = vestingAmount_; vestingBegin = vestingBegin_; vestingCliff = vestingCliff_; vestingEnd = vestingEnd_; lastUpdate = vestingBegin; } function setRecipient(address recipient_) public { require(msg.sender == recipient, 'TreasuryVester::setRecipient: unauthorized'); recipient = recipient_; } function claim() public { require(block.timestamp >= vestingCliff, 'TreasuryVester::claim: not time yet'); uint amount; if (block.timestamp >= vestingEnd) { amount = IIdle(idle).balanceOf(address(this)); } else { amount = vestingAmount.mul(block.timestamp - lastUpdate).div(vestingEnd - vestingBegin); lastUpdate = block.timestamp; } IIdle(idle).transfer(recipient, amount); } // Add ability to delegate vote in governance function setDelegate(address delegatee) public { require(msg.sender == recipient, 'TreasuryVester::setDelegate: unauthorized'); IIdle(idle).delegate(delegatee); } } interface IIdle { function balanceOf(address account) external view returns (uint); function transfer(address dst, uint rawAmount) external returns (bool); function delegate(address delegatee) external; } pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./Vester.sol"; contract VesterFactory is Ownable { using SafeMath for uint256; address public IDLE; mapping (address => address) public vestingContracts; constructor(address idle) public { require(idle != address(0), "IS_0"); IDLE = idle; } function deployVestingContracts( uint256 vestingStart, address[] memory founders, address[] memory investors, uint256[] memory founderAmounts, uint256[] memory investorAmounts, uint256[] memory foundersVestingParams, uint256[] memory investorsVestingParams ) public onlyOwner { require(founders.length == founderAmounts.length, "FOUNDERS_LEN"); require(investors.length == investorAmounts.length, "INVESTORS_LEN"); for (uint256 i = 0; i < founders.length; i++) { _deployVesting(founders[i], founderAmounts[i], vestingStart, foundersVestingParams[0], foundersVestingParams[1]); } for (uint256 j = 0; j < investors.length; j++) { _deployVesting(investors[j], investorAmounts[j], vestingStart, investorsVestingParams[0], investorsVestingParams[1]); } } function _deployVesting( address recipient, uint256 amount, uint256 beginVesting, uint256 cliff, uint256 endVesting ) internal returns (address vester) { require(recipient != address(0), 'IS_0'); require(amount != 0, 'IS_0'); uint256 timestamp = block.timestamp; require(cliff >= timestamp, 'TIMESTAMP'); require(endVesting >= timestamp, 'TIMESTAMP'); vester = address(new Vester(IDLE, recipient, amount, beginVesting, cliff, endVesting)); vestingContracts[recipient] = vester; // Idle tokens should already be in this contract IERC20(IDLE).transfer(vester, amount); } function emergencyWithdrawal(address token, address to, uint256 amount) external onlyOwner { ERC20(token).transfer(to, amount); } } // 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; 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: 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.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; /** * @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); }
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/ EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature unique. Appendix F in the Ethereum Yellow paper (https:ethereum.github.io/yellowpaper/paper.pdf), defines the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most signatures from current libraries generate a unique signature with an s-value in the lower half order. If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept these malleable signatures as well.
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); 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), "IDLE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "IDLE::delegateBySig: invalid nonce"); require(now <= expiry, "IDLE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
491,671
pragma solidity ^0.8.4; // // 卄闩长ㄩ-尺丫ㄩ // // 📱 Telegram: https://t.me/HakuRYUofficial // 🌎 Website: https://haku-ryu.me/ // 🌐 Twitter: https://twitter.com/HAKU_RYU_TOKEN // 📸 Instagram: https://www.instagram.com/haku7978/ // /** * Stores constant shared between the token and presale contracts * Prevents accidental mismatches between contracts * Uniswap v2 router 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D * testnet PCS router 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3 */ contract Shared { address constant public ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; } // File: SwapInterfaces.sol pragma solidity ^0.8.4; interface ISwapFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface ISwapPair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface ISwapRouter01 { 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); } interface ISwapRouter02 is ISwapRouter01 { 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; } // File: ReentrancyGuard.sol pragma solidity ^0.8.4; /** * @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; } } // File: Context.sol pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(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: Ownable.sol pragma solidity ^0.8.4; /** * @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; 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; } /** * @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: IERC20.sol pragma solidity ^0.8.4; 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); } // File: IERC20Metadata.sol pragma solidity ^0.8.4; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: ERC20.sol pragma solidity ^0.8.4; /** * @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 {} } // File: Address.sol pragma solidity ^0.8.4; /** * @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: BlackOwned.sol pragma solidity ^0.8.4; contract HAKURYU is ERC20, Ownable, Shared { using Address for address; using Address for address payable; ISwapRouter02 public uniswapV2Router; address public uniswapV2Pair; bool private swapping; address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; uint256 public swapTokensAtAmount = 200_000 * (10**18); uint256 public blacklistTimeout = 30 minutes; mapping(address => uint256) public isBlacklistedUntil; uint256 public liquidityFee = 3; uint256 public marketingFee = 8; uint256 public devFee = 1; uint256 public feeDenominator = 100; uint256 public maxTxAmount; uint256 private launchedAt; bool public tradingOpened; uint256 private antibotEndTime; address public marketingWalletAddress = 0x227625d6857cD1266Ad4c4cb826C6A096e845EbC; address public devWalletAddress = 0xCE458F823a700595f76dB54990203B2dbcE8170E; // exlcude from fees and max transaction amount mapping (address => bool) private isExcludedFromFees; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event AccidentallySentTokenWithdrawn (address indexed token, address indexed account, uint256 amount); event AccidentallySentBNBWithdrawn (address indexed account, uint256 amount); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); constructor() ERC20("HAKURYU", "$RYU") { ISwapRouter02 _uniswapV2Router = ISwapRouter02(ROUTER); // Create a uniswap pair for this new token address _uniswapV2Pair = ISwapFactory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(marketingWalletAddress, true); excludeFromFees(devWalletAddress, true); excludeFromFees(BURN_ADDRESS, true); excludeFromFees(address(this), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), 1_000_000_000 * 10**18); maxTxAmount = totalSupply() / 500; // 0.2% } receive() external payable {} function airdropDifferentNumberOfTokens (address airdropWallet, address[] calldata airdropRecipients, uint256[] calldata airdropAmounts) external onlyOwner { if (!isExcludedFromFees[airdropWallet]) excludeFromFees(airdropWallet, true); require (airdropRecipients.length == airdropAmounts.length, "Length of recipient and amount arrays must be the same"); // airdropWallet needs to have approved the contract address to spend at least the sum of airdropAmounts for (uint256 i = 0; i < airdropRecipients.length; i++) _transfer (airdropWallet, airdropRecipients[i], airdropAmounts[i]); } function airdropSameNumberOfTokens (address airdropWallet, address[] calldata airdropRecipients, uint256 airdropAmount) external onlyOwner { if (!isExcludedFromFees[airdropWallet]) excludeFromFees(airdropWallet, true); // airdropWallet needs to have approved the contract address to spend at least airdropAmount * number of recipients for (uint256 i = 0; i < airdropRecipients.length; i++) _transfer (airdropWallet, airdropRecipients[i], airdropAmount); } function updateUniswapV2Router(address newAddress) public onlyOwner { require(newAddress != address(uniswapV2Router), "HAKURYU: The router already has that address"); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = ISwapRouter02(newAddress); address _uniswapV2Pair = ISwapFactory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); uniswapV2Pair = _uniswapV2Pair; } function excludeFromFees(address account, bool excluded) public onlyOwner { isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setMarketingWallet(address payable wallet) external onlyOwner{ require(marketingWalletAddress != address(0), "HAKURYU: Can't set marketing wallet to the zero address"); marketingWalletAddress = wallet; } function setDevWallet(address payable wallet) external onlyOwner{ require(devWalletAddress != address(0), "HAKURYU: Can't set marketing wallet to the zero address"); devWalletAddress = wallet; } function setLiquidityFee(uint256 value) external onlyOwner { liquidityFee = value; } function setMarketingFee(uint256 value) external onlyOwner { marketingFee = value; } function setDevFee(uint256 value) external onlyOwner { devFee = value; } function setBlacklistTimeout(uint256 value) external onlyOwner{ blacklistTimeout = value; } function setMaxTxPermille(uint256 maxTxPermille) external onlyOwner { require (maxTxPermille > 0, "HAKURYU: Can't set max Tx to 0"); maxTxAmount = totalSupply() * maxTxPermille / 1000; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "HAKURYU: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function blacklistAddress(address account, bool value) external onlyOwner { isBlacklistedUntil[account] = block.timestamp + (value ? blacklistTimeout : 0); } function launch() external onlyOwner { launchedAt = block.timestamp; tradingOpened = true; } function toggleTrading (bool _tradingOpened) external onlyOwner { tradingOpened = _tradingOpened; } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "HAKURYU: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function excludedFromFees (address account) public view onlyOwner returns (bool) { return isExcludedFromFees[account]; } // Help users who accidentally send tokens to the contract address function withdrawOtherTokens (address _token, address _account) external onlyOwner { IERC20 token = IERC20(_token); uint tokenBalance = token.balanceOf (address(this)); token.transfer (_account, tokenBalance); emit AccidentallySentTokenWithdrawn (_token, _account, tokenBalance); } // Help users who accidentally send BNB to the contract address - this only removes BNB that has been manually transferred to the contract address // BNB that is created as part of the liquidity provision process will be sent to the PCS pair address immediately and so cannot be affected by this action function withdrawExcessBNB (address _account) external onlyOwner { uint256 contractBNBBalance = address(this).balance; if (contractBNBBalance > 0) payable(_account).sendValue(contractBNBBalance); emit AccidentallySentBNBWithdrawn (_account, contractBNBBalance); } function _transfer( address from, address to, uint256 amount ) internal override { require (tradingOpened || isExcludedFromFees[from], "HAKURYU: Trading paused"); require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(isBlacklistedUntil[from] < block.timestamp && isBlacklistedUntil[to] < block.timestamp, "HAKURYU: Blacklisted address"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); uint256 totalFees = liquidityFee + marketingFee + devFee; bool canSwap = contractTokenBalance >= swapTokensAtAmount && launchedAt + 10 < block.timestamp && tradingOpened; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 swapTokens = contractTokenBalance * liquidityFee / totalFees; swapAndLiquify(swapTokens); uint256 marketingTokens = contractTokenBalance * marketingFee / totalFees; swapAndSendToFee(marketingTokens, marketingWalletAddress); uint256 devTokens = contractTokenBalance * devFee / totalFees; swapAndSendToFee(devTokens, devWalletAddress); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (isExcludedFromFees[from] || isExcludedFromFees[to]) takeFee = false; if (takeFee) { uint256 fees = amount * (launchedAt + 10 < block.timestamp ? totalFees : (feeDenominator - 1))/ feeDenominator; if (automatedMarketMakerPairs[to]) fees += amount / 100; amount = amount - fees; super._transfer (from, address(this), fees); } super._transfer (from, to, amount); } function swapAndSendToFee(uint256 tokens, address feeAddress) private { uint256 newBalance = swapTokensForEth(tokens); payable(feeAddress).sendValue (newBalance); } function swapAndLiquify(uint256 tokens) private { // split the contract balance into halves uint256 half = tokens / 2; uint256 otherHalf = tokens - half; // swap tokens for ETH uint256 newBalance = swapTokensForEth(half); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity (,uint256 ethFromLiquidity,) = uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(0), block.timestamp ); if (ethAmount - ethFromLiquidity > 0) payable(marketingWalletAddress).sendValue(ethAmount - ethFromLiquidity); } function swapTokensForEth(uint256 tokenAmount) private returns (uint256) { uint256 initialBalance = address(this).balance; // 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 ); return (address(this).balance - initialBalance); } }
Help users who accidentally send tokens to the contract address
function withdrawOtherTokens (address _token, address _account) external onlyOwner { IERC20 token = IERC20(_token); uint tokenBalance = token.balanceOf (address(this)); token.transfer (_account, tokenBalance); emit AccidentallySentTokenWithdrawn (_token, _account, tokenBalance); }
1,130,581
/** *Submitted for verification at Etherscan.io on 2022-01-04 */ // File: Bees/beeFlat.sol // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: Bees/WithSuperOperators.sol //SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; contract WithSuperOperators is Ownable { mapping(address => bool) internal _superOperators; event SuperOperator(address superOperator, bool enabled); /// @notice Enable or disable the ability of `superOperator` to transfer tokens of all (superOperator rights). /// @param superOperator address that will be given/removed superOperator right. /// @param enabled set whether the superOperator is enabled or disabled. function setSuperOperator(address superOperator, bool enabled) external onlyOwner { _superOperators[superOperator] = enabled; emit SuperOperator(superOperator, enabled); } /// @notice check whether address `who` is given superOperator rights. /// @param who The address to query. /// @return whether the address has superOperator rights. function isSuperOperator(address who) public view returns (bool) { return _superOperators[who]; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: Bees/ERC721C_2.sol pragma solidity ^0.8.0; abstract contract ERC721C is Context, ERC165, IERC721, IERC721Metadata, WithSuperOperators { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; //uint256 internal _supply; uint256[] internal _tokenIds; // Mapping from token ID to owner address mapping(uint256 => address) internal _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 = ERC721C.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || _superOperators[_msgSender()] || 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 = ERC721C.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) || _superOperators[_msgSender()]); } /** * @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; //_supply += 1; _tokenIds.push(tokenId); _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 = ERC721C.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); 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(ERC721C.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(ERC721C.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 {} } // File: Bees/ERC721EnumLiteC.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableLiteC is ERC721C, IERC721Enumerable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721C) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256 tokenId) { require(index < ERC721C.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); uint count; for( uint i; i < _tokenIds.length; ++i ){ if( owner == _owners[_tokenIds[i]] ){ if( count == index ) return _tokenIds[i]; else ++count; } } require(false, "ERC721Enumerable: owner index out of bounds"); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _tokenIds.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableLiteC.totalSupply(), "ERC721Enumerable: global index out of bounds"); return index; } } // File: Bees/BeeNFT.sol pragma solidity >=0.7.0 <0.9.0; contract BeeNFT is Ownable, ERC721EnumerableLiteC { using Strings for uint256; string private baseTokenURI = "https:///"; mapping(address => bool) public enabledMinter; uint256 public maxSupply = 13838; bool public paused = false; mapping(uint256 => uint256) public QueenRegistry; //ID to Int Status mapping(uint256 => uint256) public miscSetting; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721C(_name, _symbol){ setBaseURI(_initBaseURI); } // public function mint(address _to, uint256 _mintNumber) public { require(enabledMinter[msg.sender] , "!minter"); uint256 supply = totalSupply(); require(!paused, "paused" ); require(supply + 1 <= maxSupply, "OverMaxSupply" ); _safeMint(_to, _mintNumber, ""); } // function gift(uint[] calldata quantity, address[] calldata recipient) external onlyOwner{ // require(quantity.length == recipient.length, "Must provide equal quantities and recipients" ); // uint totalQuantity = 0; // uint256 supply = totalSupply(); // for(uint i = 0; i < quantity.length; ++i){ // totalQuantity += quantity[i]; // } // require( supply + totalQuantity <= maxSupply, "Mint/order exceeds supply" ); // delete totalQuantity; // for(uint i = 0; i < recipient.length; ++i){ // for(uint j = 0; j < quantity[i]; ++j){ // _safeMint( recipient[i], supply++, "" ); // } // } // } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory _value) public onlyOwner{ baseTokenURI = _value; } function setMaxSupply(uint256 _maxSupply) public onlyOwner { maxSupply = _maxSupply; } function setMinter(address _minter, bool _option) public onlyOwner { enabledMinter[_minter] = _option; } function setMisc(uint256[] calldata _ids, uint256[] calldata _values) public onlyOwner { require(_ids.length == _values.length, "Must provide equal ids and values" ); for(uint256 i = 0; i < _ids.length; i++){ miscSetting[_ids[i]] = _values[i]; } } function setQueenRegistry(uint256[] calldata _ids, uint256[] calldata _values) public onlyOwner { require(_ids.length == _values.length, "Must provide equal ids and values" ); for(uint256 i = 0; i < _ids.length; i++){ QueenRegistry[_ids[i]] = _values[i]; } } function pause(bool _state) public onlyOwner { paused = _state; } }
Enable or disable the ability of `superOperator` to transfer tokens of all (superOperator rights). superOperator address that will be given/removed superOperator right. enabled set whether the superOperator is enabled or disabled.
function setSuperOperator(address superOperator, bool enabled) external onlyOwner { _superOperators[superOperator] = enabled; emit SuperOperator(superOperator, enabled); }
10,819,085
./full_match/80001/0xf44654944Bc27F0bdC3D49B8d336148828453c55/sources/contracts/cafe.sol
Function to buy points with Ether
function buyPoints() public payable { wallet = payable(0xaBF9d65AE288ec97d1DB998A5EaD6582475fbA41); uint pointsToAdd = uint((msg.value * 10**18) / 2000); points[msg.sender] += pointsToAdd; }
5,692,337
pragma solidity 0.5.16; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../hardworkInterface/IStrategy.sol"; import "../Controllable.sol"; import "../hardworkInterface/IMigrator.sol"; import "../hardworkInterface/IVault.sol"; contract SplitterStrategy is IStrategy, Controllable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public underlying; address public vault; mapping(address => bool) public unsalvagableTokens; mapping(address => bool) public isStrategyWhitelisted; address[] public whitelistedStrategies; address[] public activeStrategies; uint256[] public caps; uint256[] public investmentRatioNumerators; address[] public withdrawalOrder; address public futureStrategy; uint256 public strategyWhitelistTime; uint256 public investmentRatioDenominator = 10000; uint256 public whitelistStrategyTimeLock = 12 hours; bool public isInitialized = false; event StrategyWhitelisted( address strategy ); event StrategyWhitelistAnnounced( address strategy, uint256 when ); event StrategyUnwhitelisted( address strategy ); modifier restricted() { require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()), "The sender has to be the controller or vault or governance"); _; } constructor(address _storage) public Controllable(_storage) { } function initSplitter( address _underlying, address _vault, address[] memory _strategies, uint256[] memory _investmentRatioNumerators, uint256[] memory _caps, address[] memory _withdrawalOrder ) public onlyGovernance { require(!isInitialized, "splitter is already initialized"); isInitialized = true; require(_underlying != address(0), "_underlying cannot be empty"); require(_vault != address(0), "_vault cannot be empty"); require(IVault(_vault).underlying() == _underlying, "underlying must match"); unsalvagableTokens[_underlying] = true; underlying = IERC20(_underlying); vault = _vault; for (uint256 i = 0; i < _strategies.length; i++) { whitelistedStrategies.push(_strategies[i]); isStrategyWhitelisted[_strategies[i]] = true; } _configureStrategies(_strategies, _investmentRatioNumerators, _caps, _withdrawalOrder); } /* * Instant configuration of the active strategies, caps, investment ratios, * and withdrawal orders */ function configureStrategies( address[] memory _activeStrategies, uint256[] memory _investmentRatioNumerators, uint256[] memory _caps, address[] memory _withdrawalOrder ) public onlyGovernance { _configureStrategies( _activeStrategies, _investmentRatioNumerators, _caps, _withdrawalOrder ); } function _configureStrategies( address[] memory _activeStrategies, uint256[] memory _investmentRatioNumerators, uint256[] memory _caps, address[] memory _withdrawalOrder ) internal { require(_activeStrategies.length == _investmentRatioNumerators.length, "investment ratios length invalid"); require(_activeStrategies.length == _caps.length, "caps length invalid"); require(whitelistedStrategies.length == _withdrawalOrder.length, "withdrawalOrder length invalid"); activeStrategies.length = 0; investmentRatioNumerators.length = 0; caps.length = 0; for (uint256 i = 0; i < _activeStrategies.length; i++) { require(isStrategyWhitelisted[_activeStrategies[i]], "strategy not whitelisted"); activeStrategies.push(_activeStrategies[i]); investmentRatioNumerators.push(_investmentRatioNumerators[i]); caps.push(_caps[i]); } withdrawalOrder.length = 0; for (uint256 i = 0; i < _withdrawalOrder.length; i++) { require(isStrategyWhitelisted[_withdrawalOrder[i]], "withdrawal strategy not whitelisted"); withdrawalOrder.push(_withdrawalOrder[i]); } } function depositArbCheck() public view returns(bool) { for (uint256 i = 0; i < activeStrategies.length; i++) { if (!IStrategy(activeStrategies[i]).depositArbCheck()) { return false; } } return true; } /* * Returns the total amount. * Iterates over all whitelisted strateges, not just active */ function investedUnderlyingBalance() public view returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < whitelistedStrategies.length; i++) { result = result.add(IStrategy(whitelistedStrategies[i]).investedUnderlyingBalance()); } return result.add(IERC20(underlying).balanceOf(address(this))); } /* * Invests all tokens that were accumulated so far */ function investAllUnderlying() internal { uint256 splitterInitialBalance = IERC20(underlying).balanceOf(address(this)); for (uint256 i = 0; i < activeStrategies.length; i++) { uint256 computedRatio = splitterInitialBalance.mul(investmentRatioNumerators[i]).div(investmentRatioDenominator); uint256 toInvest = Math.min(computedRatio, IERC20(underlying).balanceOf(address(this))); if (toInvest > 0) { if (caps[i] > 0) { // there is a cap uint256 strategyBalance = IStrategy(activeStrategies[i]).investedUnderlyingBalance(); if (strategyBalance < caps[i]) { uint256 maxRemaining = caps[i] - strategyBalance; IERC20(underlying).safeTransfer(activeStrategies[i], Math.min(maxRemaining, toInvest)); } } else { // no cap IERC20(underlying).safeTransfer(activeStrategies[i], toInvest); } } } // the rest of the funds would stay in the strategy } /** * Withdraws everything from a specific strategy */ function withdrawFromStrategy(address strategy, uint256 amount) external restricted { require(isStrategyWhitelisted[strategy], "strategy not whitelisted"); IStrategy(strategy).withdrawToVault(amount); } /** * Invests into a specific strategy */ function investIntoStrategy(address strategy, uint256 amount) external restricted { require(isStrategyWhitelisted[strategy], "strategy not whitelisted"); IERC20(underlying).safeTransfer(strategy, amount); } /** * Withdraws everything from all the vaults */ function withdrawAllToVault() external restricted { for (uint256 i = 0; i < withdrawalOrder.length; i++) { if (IStrategy(withdrawalOrder[i]).investedUnderlyingBalance() > 0) { IStrategy(withdrawalOrder[i]).withdrawAllToVault(); } } uint256 actualBalance = IERC20(underlying).balanceOf(address(this)); if (actualBalance > 0) { IERC20(underlying).safeTransfer(vault, actualBalance); } } /* * Cashes some amount out and withdraws to the vault */ function withdrawToVault(uint256 amount) external restricted { require(amount > 0, "amount must be greater than 0"); for (uint256 i = 0; i < withdrawalOrder.length; i++) { uint256 splitterBalance = IERC20(underlying).balanceOf(address(this)); if (splitterBalance >= amount) { break; } uint256 strategyBalance = IStrategy(withdrawalOrder[i]).investedUnderlyingBalance(); if (strategyBalance > 0) { IStrategy(withdrawalOrder[i]).withdrawToVault( Math.min(amount.sub(splitterBalance), strategyBalance) ); } } // we intend to fail if we don't have enough balance require(IERC20(underlying).balanceOf(address(this)) >= amount, "splitter does not have sufficient balance"); IERC20(underlying).safeTransfer(vault, amount); // investing back the rest if anything left investAllUnderlying(); } /** * Calls doHardWork on all strategies */ function doHardWork() public restricted { investAllUnderlying(); for (uint256 i = 0; i < activeStrategies.length; i++) { IStrategy(activeStrategies[i]).doHardWork(); } } /** * Calls doHardWork on a specific strategy */ function doHardWork(address _strategy) public restricted { IStrategy(_strategy).doHardWork(); } function _setStrategyWhitelistTime(uint256 _strategyWhitelistTime) internal { strategyWhitelistTime = _strategyWhitelistTime; } function _setFutureStrategy(address _futureStrategy) internal { futureStrategy = _futureStrategy; } function whitelistedStrategyCount() public view returns (uint256) { return whitelistedStrategies.length; } function canWhitelistStrategy(address _strategy) public view returns (bool) { return (_strategy == futureStrategy && block.timestamp > strategyWhitelistTime && strategyWhitelistTime > 0); // or the timelock has passed } /** * Indicates that a strategy would be added to the splitter */ function announceStrategyWhitelist(address _strategy) public onlyGovernance { require(_strategy != address(0), "_strategy cannot be 0x0"); require(IStrategy(_strategy).underlying() == address(underlying), "Underlying of splitter must match Strategy underlying"); require(IStrategy(_strategy).vault() == address(this), "The strategy does not belong to this splitter"); // records a new timestamp uint256 when = block.timestamp.add(whitelistStrategyTimeLock); _setStrategyWhitelistTime(when); _setFutureStrategy(_strategy); emit StrategyWhitelistAnnounced(_strategy, when); } /** * Finalizes (or cancels) the strategy update by resetting the data */ function finalizeStrategyWhitelist() public onlyGovernance { _setStrategyWhitelistTime(0); _setFutureStrategy(address(0)); } /** * Removes a given strategy from the whitelist * It is only allowed in case its underlying balance is 0 */ function unwhitelistStrategy(address _strategy) public onlyGovernance { require(_strategy != address(0), "_strategy cannot be 0x0"); require(isStrategyWhitelisted[_strategy], "_strategy is not whitelisted"); IStrategy strategy = IStrategy(_strategy); require(strategy.investedUnderlyingBalance() == 0, "can only unwhitelist an empty strategy"); emit StrategyUnwhitelisted(_strategy); isStrategyWhitelisted[_strategy] = false; for (uint256 i = 0; i < whitelistedStrategies.length; i++) { if (whitelistedStrategies[i] == _strategy) { if (i < whitelistedStrategies.length - 1) { whitelistedStrategies[i] = whitelistedStrategies[whitelistedStrategies.length - 1]; } whitelistedStrategies.length--; return; } } } /** * Adds a given strategy into the whitelist * Possible only after the timelock expired */ function whitelistStrategy(address _strategy) public onlyGovernance { require(canWhitelistStrategy(_strategy), "The strategy exists and switch timelock did not elapse yet"); require(_strategy != address(0), "_strategy cannot be 0x0"); require(IStrategy(_strategy).underlying() == address(underlying), "Underlying of splitter must match Strategy underlying"); require(IStrategy(_strategy).vault() == address(this), "The strategy does not belong to this splitter"); whitelistedStrategies.push(_strategy); isStrategyWhitelisted[_strategy] = true; emit StrategyWhitelisted(_strategy); IERC20(underlying).safeApprove(_strategy, 0); IERC20(underlying).safeApprove(_strategy, uint256(~0)); finalizeStrategyWhitelist(); } // should only be called by controller function salvage(address destination, address token, uint256 amount) external restricted { require(!unsalvagableTokens[token], "token is defined as not salvageable"); IERC20(token).safeTransfer(destination, amount); } }
Calls doHardWork on all strategies/
function doHardWork() public restricted { investAllUnderlying(); for (uint256 i = 0; i < activeStrategies.length; i++) { IStrategy(activeStrategies[i]).doHardWork(); } }
5,399,008
./partial_match/1/0x01300F58c6Bb3A756640705464797882aeEC62fD/sources/SKSMedallion.sol
Prevent malicious actions
function burn(uint256 _tokenId) external onlyOwner { delete tokenCoinTypes[_tokenId]; address owner = ownerOf(_tokenId); _burn(_tokenId); emit Burned(owner, _tokenId); }
16,166,840
pragma solidity 0.8.4; // SPDX-License-Identifier: MIT /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut 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"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, block.chainid, address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping (address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") { } /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } /** * @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()); } } /** * @dev ERC20 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 ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev 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; } } /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } contract IDO is ERC20Permit, ERC20Pausable, AccessControl { // Contract owner address address public owner; // Proposed new contract owner address address public newOwner; bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); uint256 public constant cap = 100 * 1000 * 1000 * 1 ether; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() ERC20("Idexo Token", "IDO") ERC20Permit("Idexo Token") { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); _mint(_msgSender(), cap); owner = _msgSender(); emit OwnershipTransferred(address(0), _msgSender()); } /****************************| | Ownership | |___________________________*/ /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == _msgSender(), "IDO: CALLER_NO_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. * `owner` should first call {removeOperator} for himself. */ function renounceOwnership() external onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } /** * @dev Transfer the contract ownership. * The new owner still needs to accept the transfer. * can only be called by the contract owner. * * @param _newOwner new contract owner. */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0), "IDO: INVALID_ADDRESS"); require(_newOwner != owner, "IDO: OWNERSHIP_SELF_TRANSFER"); newOwner = _newOwner; } /** * @dev The new owner accept an ownership transfer. * The new owner should remove `operator` role from previous owner and add for himself. */ function acceptOwnership() external { require(_msgSender() == newOwner, "IDO: CALLER_NO_NEW_OWNER"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } /***********************| | Role | |______________________*/ /** * @dev Restricted to members of the operator role. */ modifier onlyOperator() { require(hasRole(OPERATOR_ROLE, _msgSender()), "IDO: CALLER_NO_OPERATOR_ROLE"); _; } /** * @dev Add an account to the operator role. * @param account address */ function addOperator(address account) public onlyOwner { require(!hasRole(OPERATOR_ROLE, account), "IDO: ALREADY_OERATOR_ROLE"); grantRole(OPERATOR_ROLE, account); } /** * @dev Remove an account from the operator role. * @param account address */ function removeOperator(address account) public onlyOwner { require(hasRole(OPERATOR_ROLE, account), "IDO: NO_OPERATOR_ROLE"); revokeRole(OPERATOR_ROLE, account); } /** * @dev Check if an account is operator. * @param account address */ function checkOperator(address account) public view returns (bool) { return hasRole(OPERATOR_ROLE, account); } /************************| | Token | |_______________________*/ /** * @dev `_beforeTokenTransfer` hook override. * @param from address * @param to address * @param amount uint256 * `Owner` can only transfer when paused */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20, ERC20Pausable) { if (from == owner) { return; } ERC20Pausable._beforeTokenTransfer(from, to, amount); } /** * @dev Get chain id. */ function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /******************************| | Pausability | |_____________________________*/ /** * @dev Pause. */ function pause() public onlyOperator { super._pause(); } /** * @dev Unpause. */ function unpause() public onlyOperator { super._unpause(); } }
Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current owner. `owner` should first call {removeOperator} for himself./
function renounceOwnership() external onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); }
1,519,068
pragma solidity 0.4.25; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : dave@akomba.com // released under Apache 2.0 licence library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } } contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract DecoBaseProjectsMarketplace is Ownable { using SafeMath for uint256; // `DecoRelay` contract address. address public relayContractAddress; /** * @dev Payble fallback for reverting transactions of any incoming ETH. */ function () public payable { require(msg.value == 0, "Blocking any incoming ETH."); } /** * @dev Set the new address of the `DecoRelay` contract. * @param _newAddress An address of the new contract. */ function setRelayContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Relay address must not be 0x0."); relayContractAddress = _newAddress; } /** * @dev Allows to trasnfer any ERC20 tokens from the contract balance to owner's address. * @param _tokenAddress An `address` of an ERC20 token. * @param _tokens An `uint` tokens amount. * @return A `bool` operation result state. */ function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { IERC20 token = IERC20(_tokenAddress); return token.transfer(owner(), _tokens); } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /// @title Contract to store other contracts newest versions addresses and service information. contract DecoRelay is DecoBaseProjectsMarketplace { address public projectsContractAddress; address public milestonesContractAddress; address public escrowFactoryContractAddress; address public arbitrationContractAddress; address public feesWithdrawalAddress; uint8 public shareFee; function setProjectsContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); projectsContractAddress = _newAddress; } function setMilestonesContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); milestonesContractAddress = _newAddress; } function setEscrowFactoryContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); escrowFactoryContractAddress = _newAddress; } function setArbitrationContractAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); arbitrationContractAddress = _newAddress; } function setFeesWithdrawalAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0x0), "Address should not be 0x0."); feesWithdrawalAddress = _newAddress; } function setShareFee(uint8 _shareFee) external onlyOwner { require(_shareFee <= 100, "Deconet share fee must be less than 100%."); shareFee = _shareFee; } } /** * @title Escrow contract, every project deploys a clone and transfer ownership to the project client, so all * funds not reserved to pay for a milestone can be safely moved in/out. */ contract DecoEscrow is DecoBaseProjectsMarketplace { using SafeMath for uint256; // Indicates if the current clone has been initialized. bool internal isInitialized; // Stores share fee that should apply on any successful distribution. uint8 public shareFee; // Authorized party for executing funds distribution operations. address public authorizedAddress; // State variable to track available ETH Escrow owner balance. // Anything that is not blocked or distributed in favor of any party can be withdrawn by the owner. uint public balance; // Mapping of available for withdrawal funds by the address. // Accounted amounts are excluded from the `balance`. mapping (address => uint) public withdrawalAllowanceForAddress; // Maps information about the amount of deposited ERC20 token to the token address. mapping(address => uint) public tokensBalance; /** * Mapping of ERC20 tokens amounts to token addresses that are available for withdrawal for a given address. * Accounted here amounts are excluded from the `tokensBalance`. */ mapping(address => mapping(address => uint)) public tokensWithdrawalAllowanceForAddress; // ETH amount blocked in Escrow. // `balance` excludes this amount. uint public blockedBalance; // Mapping of the amount of ERC20 tokens to the the token address that are blocked in Escrow. // A token value in `tokensBalance` excludes stored here amount. mapping(address => uint) public blockedTokensBalance; // Logged when an operation with funds occurred. event FundsOperation ( address indexed sender, address indexed target, address tokenAddress, uint amount, PaymentType paymentType, OperationType indexed operationType ); // Logged when the given address authorization to distribute Escrow funds changed. event FundsDistributionAuthorization ( address targetAddress, bool isAuthorized ); // Accepted types of payments. enum PaymentType { Ether, Erc20 } // Possible operations with funds. enum OperationType { Receive, Send, Block, Unblock, Distribute } // Restrict function call to be originated from an address that was authorized to distribute funds. modifier onlyAuthorized() { require(authorizedAddress == msg.sender, "Only authorized addresses allowed."); _; } /** * @dev Default `payable` fallback to accept incoming ETH from any address. */ function () public payable { deposit(); } /** * @dev Initialize the Escrow clone with default values. * @param _newOwner An address of a new escrow owner. * @param _authorizedAddress An address that will be stored as authorized. */ function initialize( address _newOwner, address _authorizedAddress, uint8 _shareFee, address _relayContractAddress ) external { require(!isInitialized, "Only uninitialized contracts allowed."); isInitialized = true; authorizedAddress = _authorizedAddress; emit FundsDistributionAuthorization(_authorizedAddress, true); _transferOwnership(_newOwner); shareFee = _shareFee; relayContractAddress = _relayContractAddress; } /** * @dev Start transfering the given amount of the ERC20 tokens available by provided address. * @param _tokenAddress ERC20 token contract address. * @param _amount Amount to transfer from sender`s address. */ function depositErc20(address _tokenAddress, uint _amount) external { require(_tokenAddress != address(0x0), "Token Address shouldn't be 0x0."); IERC20 token = IERC20(_tokenAddress); require( token.transferFrom(msg.sender, address(this), _amount), "Transfer operation should be successful." ); tokensBalance[_tokenAddress] = tokensBalance[_tokenAddress].add(_amount); emit FundsOperation ( msg.sender, address(this), _tokenAddress, _amount, PaymentType.Erc20, OperationType.Receive ); } /** * @dev Withdraw the given amount of ETH to sender`s address if allowance or contract balance is sufficient. * @param _amount Amount to withdraw. */ function withdraw(uint _amount) external { withdrawForAddress(msg.sender, _amount); } /** * @dev Withdraw the given amount of ERC20 token to sender`s address if allowance or contract balance is sufficient. * @param _tokenAddress ERC20 token address. * @param _amount Amount to withdraw. */ function withdrawErc20(address _tokenAddress, uint _amount) external { withdrawErc20ForAddress(msg.sender, _tokenAddress, _amount); } /** * @dev Block funds for future use by authorized party stored in `authorizedAddress`. * @param _amount An uint of Wei to be blocked. */ function blockFunds(uint _amount) external onlyAuthorized { require(_amount <= balance, "Amount to block should be less or equal than balance."); balance = balance.sub(_amount); blockedBalance = blockedBalance.add(_amount); emit FundsOperation ( address(this), msg.sender, address(0x0), _amount, PaymentType.Ether, OperationType.Block ); } /** * @dev Blocks ERC20 tokens funds for future use by authorized party listed in `authorizedAddress`. * @param _tokenAddress An address of ERC20 token. * @param _amount An uint of tokens to be blocked. */ function blockTokenFunds(address _tokenAddress, uint _amount) external onlyAuthorized { uint accountedTokensBalance = tokensBalance[_tokenAddress]; require( _amount <= accountedTokensBalance, "Tokens mount to block should be less or equal than balance." ); tokensBalance[_tokenAddress] = accountedTokensBalance.sub(_amount); blockedTokensBalance[_tokenAddress] = blockedTokensBalance[_tokenAddress].add(_amount); emit FundsOperation ( address(this), msg.sender, _tokenAddress, _amount, PaymentType.Erc20, OperationType.Block ); } /** * @dev Distribute funds between contract`s balance and allowance for some address. * Deposit may be returned back to the contract address, i.e. to the escrow owner. * Or deposit may flow to the allowance for an address as a result of an evidence * given by an authorized party about fullfilled obligations. * **IMPORTANT** This operation includes fees deduction. * @param _destination Destination address for funds distribution. * @param _amount Amount to distribute in favor of a destination address. */ function distributeFunds( address _destination, uint _amount ) external onlyAuthorized { require( _amount <= blockedBalance, "Amount to distribute should be less or equal than blocked balance." ); uint amount = _amount; if (shareFee > 0 && relayContractAddress != address(0x0)) { DecoRelay relayContract = DecoRelay(relayContractAddress); address feeDestination = relayContract.feesWithdrawalAddress(); uint fee = amount.mul(shareFee).div(100); amount = amount.sub(fee); blockedBalance = blockedBalance.sub(fee); withdrawalAllowanceForAddress[feeDestination] = withdrawalAllowanceForAddress[feeDestination].add(fee); emit FundsOperation( msg.sender, feeDestination, address(0x0), fee, PaymentType.Ether, OperationType.Distribute ); } if (_destination == owner()) { unblockFunds(amount); return; } blockedBalance = blockedBalance.sub(amount); withdrawalAllowanceForAddress[_destination] = withdrawalAllowanceForAddress[_destination].add(amount); emit FundsOperation( msg.sender, _destination, address(0x0), amount, PaymentType.Ether, OperationType.Distribute ); } /** * @dev Distribute ERC20 token funds between contract`s balance and allowanc for some address. * Deposit may be returned back to the contract address, i.e. to the escrow owner. * Or deposit may flow to the allowance for an address as a result of an evidence * given by authorized party about fullfilled obligations. * **IMPORTANT** This operation includes fees deduction. * @param _destination Destination address for funds distribution. * @param _tokenAddress ERC20 Token address. * @param _amount Amount to distribute in favor of a destination address. */ function distributeTokenFunds( address _destination, address _tokenAddress, uint _amount ) external onlyAuthorized { require( _amount <= blockedTokensBalance[_tokenAddress], "Amount to distribute should be less or equal than blocked balance." ); uint amount = _amount; if (shareFee > 0 && relayContractAddress != address(0x0)) { DecoRelay relayContract = DecoRelay(relayContractAddress); address feeDestination = relayContract.feesWithdrawalAddress(); uint fee = amount.mul(shareFee).div(100); amount = amount.sub(fee); blockedTokensBalance[_tokenAddress] = blockedTokensBalance[_tokenAddress].sub(fee); uint allowance = tokensWithdrawalAllowanceForAddress[feeDestination][_tokenAddress]; tokensWithdrawalAllowanceForAddress[feeDestination][_tokenAddress] = allowance.add(fee); emit FundsOperation( msg.sender, feeDestination, _tokenAddress, fee, PaymentType.Erc20, OperationType.Distribute ); } if (_destination == owner()) { unblockTokenFunds(_tokenAddress, amount); return; } blockedTokensBalance[_tokenAddress] = blockedTokensBalance[_tokenAddress].sub(amount); uint allowanceForSender = tokensWithdrawalAllowanceForAddress[_destination][_tokenAddress]; tokensWithdrawalAllowanceForAddress[_destination][_tokenAddress] = allowanceForSender.add(amount); emit FundsOperation( msg.sender, _destination, _tokenAddress, amount, PaymentType.Erc20, OperationType.Distribute ); } /** * @dev Withdraws ETH amount from the contract's balance to the provided address. * @param _targetAddress An `address` for transfer ETH to. * @param _amount An `uint` amount to be transfered. */ function withdrawForAddress(address _targetAddress, uint _amount) public { require( _amount <= address(this).balance, "Amount to withdraw should be less or equal than balance." ); if (_targetAddress == owner()) { balance = balance.sub(_amount); } else { uint withdrawalAllowance = withdrawalAllowanceForAddress[_targetAddress]; withdrawalAllowanceForAddress[_targetAddress] = withdrawalAllowance.sub(_amount); } _targetAddress.transfer(_amount); emit FundsOperation ( address(this), _targetAddress, address(0x0), _amount, PaymentType.Ether, OperationType.Send ); } /** * @dev Withdraws ERC20 token amount from the contract's balance to the provided address. * @param _targetAddress An `address` for transfer tokens to. * @param _tokenAddress An `address` of ERC20 token. * @param _amount An `uint` amount of ERC20 tokens to be transfered. */ function withdrawErc20ForAddress(address _targetAddress, address _tokenAddress, uint _amount) public { IERC20 token = IERC20(_tokenAddress); require( _amount <= token.balanceOf(this), "Token amount to withdraw should be less or equal than balance." ); if (_targetAddress == owner()) { tokensBalance[_tokenAddress] = tokensBalance[_tokenAddress].sub(_amount); } else { uint tokenWithdrawalAllowance = getTokenWithdrawalAllowance(_targetAddress, _tokenAddress); tokensWithdrawalAllowanceForAddress[_targetAddress][_tokenAddress] = tokenWithdrawalAllowance.sub( _amount ); } token.transfer(_targetAddress, _amount); emit FundsOperation ( address(this), _targetAddress, _tokenAddress, _amount, PaymentType.Erc20, OperationType.Send ); } /** * @dev Returns allowance for withdrawing the given token for sender address. * @param _tokenAddress An address of ERC20 token. * @return An uint value of allowance. */ function getTokenWithdrawalAllowance(address _account, address _tokenAddress) public view returns(uint) { return tokensWithdrawalAllowanceForAddress[_account][_tokenAddress]; } /** * @dev Accept and account incoming deposit in contract state. */ function deposit() public payable { require(msg.value > 0, "Deposited amount should be greater than 0."); balance = balance.add(msg.value); emit FundsOperation ( msg.sender, address(this), address(0x0), msg.value, PaymentType.Ether, OperationType.Receive ); } /** * @dev Unblock blocked funds and make them available to the contract owner. * @param _amount An uint of Wei to be unblocked. */ function unblockFunds(uint _amount) public onlyAuthorized { require( _amount <= blockedBalance, "Amount to unblock should be less or equal than balance" ); blockedBalance = blockedBalance.sub(_amount); balance = balance.add(_amount); emit FundsOperation ( msg.sender, address(this), address(0x0), _amount, PaymentType.Ether, OperationType.Unblock ); } /** * @dev Unblock blocked token funds and make them available to the contract owner. * @param _amount An uint of Wei to be unblocked. */ function unblockTokenFunds(address _tokenAddress, uint _amount) public onlyAuthorized { uint accountedBlockedTokensAmount = blockedTokensBalance[_tokenAddress]; require( _amount <= accountedBlockedTokensAmount, "Tokens amount to unblock should be less or equal than balance" ); blockedTokensBalance[_tokenAddress] = accountedBlockedTokensAmount.sub(_amount); tokensBalance[_tokenAddress] = tokensBalance[_tokenAddress].add(_amount); emit FundsOperation ( msg.sender, address(this), _tokenAddress, _amount, PaymentType.Erc20, OperationType.Unblock ); } /** * @dev Override base contract logic to block this operation for Escrow contract. * @param _tokenAddress An `address` of an ERC20 token. * @param _tokens An `uint` tokens amount. * @return A `bool` operation result state. */ function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { return false; } } contract CloneFactory { event CloneCreated(address indexed target, address clone); function createClone(address target) internal returns (address result) { bytes memory clone = hex"600034603b57603080600f833981f36000368180378080368173bebebebebebebebebebebebebebebebebebebebe5af43d82803e15602c573d90f35b3d90fd"; bytes20 targetBytes = bytes20(target); for (uint i = 0; i < 20; i++) { clone[26 + i] = targetBytes[i]; } assembly { let len := mload(clone) let data := add(clone, 0x20) result := create(0, data, len) } } } /** * @title Utility contract that provides a way to execute cheap clone deployment of the DecoEscrow contract * on chain. */ contract DecoEscrowFactory is DecoBaseProjectsMarketplace, CloneFactory { // Escrow master-contract address. address public libraryAddress; // Logged when a new Escrow clone is deployed to the chain. event EscrowCreated(address newEscrowAddress); /** * @dev Constructor for the contract. * @param _libraryAddress Escrow master-contract address. */ constructor(address _libraryAddress) public { libraryAddress = _libraryAddress; } /** * @dev Updates library address with the given value. * @param _libraryAddress Address of a new base contract. */ function setLibraryAddress(address _libraryAddress) external onlyOwner { require(libraryAddress != _libraryAddress); require(_libraryAddress != address(0x0)); libraryAddress = _libraryAddress; } /** * @dev Create Escrow clone. * @param _ownerAddress An address of the Escrow contract owner. * @param _authorizedAddress An addresses that is going to be authorized in Escrow contract. */ function createEscrow( address _ownerAddress, address _authorizedAddress ) external returns(address) { address clone = createClone(libraryAddress); DecoRelay relay = DecoRelay(relayContractAddress); DecoEscrow(clone).initialize( _ownerAddress, _authorizedAddress, relay.shareFee(), relayContractAddress ); emit EscrowCreated(clone); return clone; } } contract IDecoArbitrationTarget { /** * @dev Prepare arbitration target for a started dispute. * @param _idHash A `bytes32` hash of id. */ function disputeStartedFreeze(bytes32 _idHash) public; /** * @dev React to an active dispute settlement with given parameters. * @param _idHash A `bytes32` hash of id. * @param _respondent An `address` of a respondent. * @param _respondentShare An `uint8` share for the respondent. * @param _initiator An `address` of a dispute initiator. * @param _initiatorShare An `uint8` share for the initiator. * @param _isInternal A `bool` indicating if dispute was settled by participants without an arbiter. * @param _arbiterWithdrawalAddress An `address` for sending out arbiter compensation. */ function disputeSettledTerminate( bytes32 _idHash, address _respondent, uint8 _respondentShare, address _initiator, uint8 _initiatorShare, bool _isInternal, address _arbiterWithdrawalAddress ) public; /** * @dev Check eligibility of a given address to perform operations. * @param _idHash A `bytes32` hash of id. * @param _addressToCheck An `address` to check. * @return A `bool` check status. */ function checkEligibility(bytes32 _idHash, address _addressToCheck) public view returns(bool); /** * @dev Check if target is ready for a dispute. * @param _idHash A `bytes32` hash of id. * @return A `bool` check status. */ function canStartDispute(bytes32 _idHash) public view returns(bool); } library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } interface IDecoArbitration { /** * @dev Should be logged upon dispute start. */ event LogStartedDispute( address indexed sender, bytes32 indexed idHash, uint timestamp, int respondentShareProposal ); /** * @dev Should be logged upon proposal rejection. */ event LogRejectedProposal( address indexed sender, bytes32 indexed idHash, uint timestamp, uint8 rejectedProposal ); /** * @dev Should be logged upon dispute settlement. */ event LogSettledDispute( address indexed sender, bytes32 indexed idHash, uint timestamp, uint8 respondentShare, uint8 initiatorShare ); /** * @dev Should be logged when contract owner updates fees. */ event LogFeesUpdated( uint timestamp, uint fixedFee, uint8 shareFee ); /** * @dev Should be logged when time limit to accept/reject proposal for respondent is updated. */ event LogProposalTimeLimitUpdated( uint timestamp, uint proposalActionTimeLimit ); /** * @dev Should be logged when the withdrawal address for the contract owner changed. */ event LogWithdrawalAddressChanged( uint timestamp, address newWithdrawalAddress ); /** * @notice Start dispute for the given project. * @dev This call should log event and save dispute information and notify `IDecoArbitrationTarget` object * about started dispute. Dipsute can be started only if target instance call of * `canStartDispute` method confirms that state is valid. Also, txn sender and respondent addresses * eligibility must be confirmed by arbitation target `checkEligibility` method call. * @param _idHash A `bytes32` hash of a project id. * @param _respondent An `address` of the second paty involved in the dispute. * @param _respondentShareProposal An `int` value indicating percentage of disputed funds * proposed to the respondent. Valid values range is 0-100, different values are considered as 'No Proposal'. * When provided percentage is 100 then this dispute is processed automatically, * and all funds are distributed in favor of the respondent. */ function startDispute(bytes32 _idHash, address _respondent, int _respondentShareProposal) external; /** * @notice Accept active dispute proposal, sender should be the respondent. * @dev Respondent of a dispute can accept existing proposal and if proposal exists then `settleDispute` * method should be called with proposal value. Time limit for respondent to accept/reject proposal * must not be exceeded. * @param _idHash A `bytes32` hash of a project id. */ function acceptProposal(bytes32 _idHash) external; /** * @notice Reject active dispute proposal and escalate dispute. * @dev Txn sender should be dispute's respondent. Dispute automatically gets escalated to this contract * owner aka arbiter. Proposal must exist, otherwise this method should do nothing. When respondent * rejects proposal then it should get removed and corresponding event should be logged. * There should be a time limit for a respondent to reject a given proposal, and if it is overdue * then arbiter should take on a dispute to settle it. * @param _idHash A `bytes32` hash of a project id. */ function rejectProposal(bytes32 _idHash) external; /** * @notice Settle active dispute. * @dev Sender should be the current contract or its owner(arbiter). Action is possible only when there is no active * proposal or time to accept the proposal is over. Sum of shares should be 100%. Should notify target * instance about a dispute settlement via `disputeSettledTerminate` method call. Also corresponding * event must be emitted. * @param _idHash A `bytes32` hash of a project id. * @param _respondentShare An `uint` percents of respondent share. * @param _initiatorShare An `uint` percents of initiator share. */ function settleDispute(bytes32 _idHash, uint _respondentShare, uint _initiatorShare) external; /** * @return Retuns this arbitration contract withdrawal `address`. */ function getWithdrawalAddress() external view returns(address); /** * @return The arbitration contract fixed `uint` fee and `uint8` share of all disputed funds fee. */ function getFixedAndShareFees() external view returns(uint, uint8); /** * @return An `uint` time limit for accepting/rejecting a proposal by respondent. */ function getTimeLimitForReplyOnProposal() external view returns(uint); } pragma solidity 0.4.25; /// @title Contract for Project events and actions handling. contract DecoProjects is DecoBaseProjectsMarketplace { using SafeMath for uint256; using ECDSA for bytes32; // struct for project details struct Project { string agreementId; address client; address maker; address arbiter; address escrowContractAddress; uint startDate; uint endDate; uint8 milestoneStartWindow; uint8 feedbackWindow; uint8 milestonesCount; uint8 customerSatisfaction; uint8 makerSatisfaction; bool agreementsEncrypted; } struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } struct Proposal { string agreementId; address arbiter; } bytes32 constant private EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); bytes32 constant private PROPOSAL_TYPEHASH = keccak256( "Proposal(string agreementId,address arbiter)" ); bytes32 private DOMAIN_SEPARATOR; // enumeration to describe possible project states for easier state changes reporting. enum ProjectState { Active, Completed, Terminated } // enumeration to describe possible satisfaction score types. enum ScoreType { CustomerSatisfaction, MakerSatisfaction } // Logged when a project state changes. event LogProjectStateUpdate ( bytes32 indexed agreementHash, address updatedBy, uint timestamp, ProjectState state ); // Logged when either party sets satisfaction score after the completion of a project. event LogProjectRated ( bytes32 indexed agreementHash, address indexed ratedBy, address indexed ratingTarget, uint8 rating, uint timestamp ); // maps the agreement`s unique hash to the project details. mapping (bytes32 => Project) public projects; // maps hashes of all maker's projects to the maker's address. mapping (address => bytes32[]) public makerProjects; // maps hashes of all client's projects to the client's address. mapping (address => bytes32[]) public clientProjects; // maps arbiter's fixed fee to a project. mapping (bytes32 => uint) public projectArbiterFixedFee; // maps arbiter's share fee to a project. mapping (bytes32 => uint8) public projectArbiterShareFee; // Modifier to restrict method to be called either by project`s owner or maker modifier eitherClientOrMaker(bytes32 _agreementHash) { Project memory project = projects[_agreementHash]; require( project.client == msg.sender || project.maker == msg.sender, "Only project owner or maker can perform this operation." ); _; } // Modifier to restrict method to be called either by project`s owner or maker modifier eitherClientOrMakerOrMilestoneContract(bytes32 _agreementHash) { Project memory project = projects[_agreementHash]; DecoRelay relay = DecoRelay(relayContractAddress); require( project.client == msg.sender || project.maker == msg.sender || relay.milestonesContractAddress() == msg.sender, "Only project owner or maker can perform this operation." ); _; } // Modifier to restrict method to be called by the milestones contract. modifier onlyMilestonesContract(bytes32 _agreementHash) { DecoRelay relay = DecoRelay(relayContractAddress); require( msg.sender == relay.milestonesContractAddress(), "Only milestones contract can perform this operation." ); Project memory project = projects[_agreementHash]; _; } constructor (uint256 _chainId) public { require(_chainId != 0, "You must specify a nonzero chainId"); DOMAIN_SEPARATOR = hash(EIP712Domain({ name: "Deco.Network", version: "1", chainId: _chainId, verifyingContract: address(this) })); } /** * @dev Creates a new milestone-based project with pre-selected maker and owner. All parameters are required. * @param _agreementId A `string` unique id of the agreement document for that project. * @param _client An `address` of the project owner. * @param _arbiter An `address` of the referee to settle all escalated disputes between parties. * @param _maker An `address` of the project`s maker. * @param _makersSignature A `bytes` digital signature of the maker to proof the agreement acceptance. * @param _milestonesCount An `uint8` count of planned milestones for the project. * @param _milestoneStartWindow An `uint8` count of days project`s owner has to start the next milestone. * If this time is exceeded then the maker can terminate the project. * @param _feedbackWindow An `uint8` time in days project`s owner has to provide feedback for the last milestone. * If that time is exceeded then maker can terminate the project and get paid for awaited * milestone. * @param _agreementEncrypted A `bool` flag indicating whether or not the agreement is encrypted. */ function startProject( string _agreementId, address _client, address _arbiter, address _maker, bytes _makersSignature, uint8 _milestonesCount, uint8 _milestoneStartWindow, uint8 _feedbackWindow, bool _agreementEncrypted ) external { require(msg.sender == _client, "Only the client can kick off the project."); require(_client != _maker, "Client can`t be a maker on her own project."); require(_arbiter != _maker && _arbiter != _client, "Arbiter must not be a client nor a maker."); require( isMakersSignatureValid(_maker, _makersSignature, _agreementId, _arbiter), "Maker should sign the hash of immutable agreement doc." ); require(_milestonesCount >= 1 && _milestonesCount <= 24, "Milestones count is not in the allowed 1-24 range."); bytes32 hash = keccak256(_agreementId); require(projects[hash].client == address(0x0), "Project shouldn't exist yet."); saveCurrentArbitrationFees(_arbiter, hash); address newEscrowCloneAddress = deployEscrowClone(msg.sender); projects[hash] = Project( _agreementId, msg.sender, _maker, _arbiter, newEscrowCloneAddress, now, 0, // end date is unknown yet _milestoneStartWindow, _feedbackWindow, _milestonesCount, 0, // CSAT is 0 to indicate that it isn't set by maker yet 0, // MSAT is 0 to indicate that it isn't set by client yet _agreementEncrypted ); makerProjects[_maker].push(hash); clientProjects[_client].push(hash); emit LogProjectStateUpdate(hash, msg.sender, now, ProjectState.Active); } /** * @dev Terminate the project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. */ function terminateProject(bytes32 _agreementHash) external eitherClientOrMakerOrMilestoneContract(_agreementHash) { Project storage project = projects[_agreementHash]; require(project.client != address(0x0), "Only allowed for existing projects."); require(project.endDate == 0, "Only allowed for active projects."); address milestoneContractAddress = DecoRelay(relayContractAddress).milestonesContractAddress(); if (msg.sender != milestoneContractAddress) { DecoMilestones milestonesContract = DecoMilestones(milestoneContractAddress); milestonesContract.terminateLastMilestone(_agreementHash, msg.sender); } project.endDate = now; emit LogProjectStateUpdate(_agreementHash, msg.sender, now, ProjectState.Terminated); } /** * @dev Complete the project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. */ function completeProject( bytes32 _agreementHash ) external onlyMilestonesContract(_agreementHash) { Project storage project = projects[_agreementHash]; require(project.client != address(0x0), "Only allowed for existing projects."); require(project.endDate == 0, "Only allowed for active projects."); projects[_agreementHash].endDate = now; DecoMilestones milestonesContract = DecoMilestones( DecoRelay(relayContractAddress).milestonesContractAddress() ); bool isLastMilestoneAccepted; uint8 milestoneNumber; (isLastMilestoneAccepted, milestoneNumber) = milestonesContract.isLastMilestoneAccepted( _agreementHash ); require( milestoneNumber == projects[_agreementHash].milestonesCount, "The last milestone should be the last for that project." ); require(isLastMilestoneAccepted, "Only allowed when all milestones are completed."); emit LogProjectStateUpdate(_agreementHash, msg.sender, now, ProjectState.Completed); } /** * @dev Rate the second party on the project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @param _rating An `uint8` satisfaction score of either client or maker. Min value is 1, max is 10. */ function rateProjectSecondParty( bytes32 _agreementHash, uint8 _rating ) external eitherClientOrMaker(_agreementHash) { require(_rating >= 1 && _rating <= 10, "Project rating should be in the range 1-10."); Project storage project = projects[_agreementHash]; require(project.endDate != 0, "Only allowed for active projects."); address ratingTarget; if (msg.sender == project.client) { require(project.customerSatisfaction == 0, "CSAT is allowed to provide only once."); project.customerSatisfaction = _rating; ratingTarget = project.maker; } else { require(project.makerSatisfaction == 0, "MSAT is allowed to provide only once."); project.makerSatisfaction = _rating; ratingTarget = project.client; } emit LogProjectRated(_agreementHash, msg.sender, ratingTarget, _rating, now); } /** * @dev Query for getting the address of Escrow contract clone deployed for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of a clone. */ function getProjectEscrowAddress(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].escrowContractAddress; } /** * @dev Query for getting the address of a client for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of a client. */ function getProjectClient(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].client; } /** * @dev Query for getting the address of a maker for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of a maker. */ function getProjectMaker(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].maker; } /** * @dev Query for getting the address of an arbiter for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `address` of an arbiter. */ function getProjectArbiter(bytes32 _agreementHash) public view returns(address) { return projects[_agreementHash].arbiter; } /** * @dev Query for getting the feedback window for a client for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint8` feedback window in days. */ function getProjectFeedbackWindow(bytes32 _agreementHash) public view returns(uint8) { return projects[_agreementHash].feedbackWindow; } /** * @dev Query for getting the milestone start window for a client for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint8` milestone start window in days. */ function getProjectMilestoneStartWindow(bytes32 _agreementHash) public view returns(uint8) { return projects[_agreementHash].milestoneStartWindow; } /** * @dev Query for getting the start date for the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint` start date. */ function getProjectStartDate(bytes32 _agreementHash) public view returns(uint) { return projects[_agreementHash].startDate; } /** * @dev Calculates sum and number of CSAT scores of ended & rated projects for the given maker`s address. * @param _maker An `address` of the maker to look up. * @return An `uint` sum of all scores and an `uint` number of projects counted in sum. */ function makersAverageRating(address _maker) public view returns(uint, uint) { return calculateScore(_maker, ScoreType.CustomerSatisfaction); } /** * @dev Calculates sum and number of MSAT scores of ended & rated projects for the given client`s address. * @param _client An `address` of the client to look up. * @return An `uint` sum of all scores and an `uint` number of projects counted in sum. */ function clientsAverageRating(address _client) public view returns(uint, uint) { return calculateScore(_client, ScoreType.MakerSatisfaction); } /** * @dev Returns hashes of all client`s projects * @param _client An `address` to look up. * @return `bytes32[]` of projects hashes. */ function getClientProjects(address _client) public view returns(bytes32[]) { return clientProjects[_client]; } /** @dev Returns hashes of all maker`s projects * @param _maker An `address` to look up. * @return `bytes32[]` of projects hashes. */ function getMakerProjects(address _maker) public view returns(bytes32[]) { return makerProjects[_maker]; } /** * @dev Checks if a project with the given hash exists. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return A `bool` stating for the project`s existence. */ function checkIfProjectExists(bytes32 _agreementHash) public view returns(bool) { return projects[_agreementHash].client != address(0x0); } /** * @dev Query for getting end date of the given project. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint` end time of the project */ function getProjectEndDate(bytes32 _agreementHash) public view returns(uint) { return projects[_agreementHash].endDate; } /** * @dev Returns preconfigured count of milestones for a project with the given hash. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint8` count of milestones set upon the project creation. */ function getProjectMilestonesCount(bytes32 _agreementHash) public view returns(uint8) { return projects[_agreementHash].milestonesCount; } /** * @dev Returns configured for the given project arbiter fees. * @param _agreementHash A `bytes32` hash of the project`s agreement id. * @return An `uint` fixed fee and an `uint8` share fee of the project's arbiter. */ function getProjectArbitrationFees(bytes32 _agreementHash) public view returns(uint, uint8) { return ( projectArbiterFixedFee[_agreementHash], projectArbiterShareFee[_agreementHash] ); } function getInfoForDisputeAndValidate( bytes32 _agreementHash, address _respondent, address _initiator, address _arbiter ) public view returns(uint, uint8, address) { require(checkIfProjectExists(_agreementHash), "Project must exist."); Project memory project = projects[_agreementHash]; address client = project.client; address maker = project.maker; require(project.arbiter == _arbiter, "Arbiter should be same as saved in project."); require( (_initiator == client && _respondent == maker) || (_initiator == maker && _respondent == client), "Initiator and respondent must be different and equal to maker/client addresses." ); (uint fixedFee, uint8 shareFee) = getProjectArbitrationFees(_agreementHash); return (fixedFee, shareFee, project.escrowContractAddress); } /** * @dev Pulls the current arbitration contract fixed & share fees and save them for a project. * @param _arbiter An `address` of arbitration contract. * @param _agreementHash A `bytes32` hash of agreement id. */ function saveCurrentArbitrationFees(address _arbiter, bytes32 _agreementHash) internal { IDecoArbitration arbitration = IDecoArbitration(_arbiter); uint fixedFee; uint8 shareFee; (fixedFee, shareFee) = arbitration.getFixedAndShareFees(); projectArbiterFixedFee[_agreementHash] = fixedFee; projectArbiterShareFee[_agreementHash] = shareFee; } /** * @dev Calculates the sum of scores and the number of ended and rated projects for the given client`s or * maker`s address. * @param _address An `address` to look up. * @param _scoreType A `ScoreType` indicating what score should be calculated. * `CustomerSatisfaction` type means that CSAT score for the given address as a maker should be calculated. * `MakerSatisfaction` type means that MSAT score for the given address as a client should be calculated. * @return An `uint` sum of all scores and an `uint` number of projects counted in sum. */ function calculateScore( address _address, ScoreType _scoreType ) internal view returns(uint, uint) { bytes32[] memory allProjectsHashes = getProjectsByScoreType(_address, _scoreType); uint rating = 0; uint endedProjectsCount = 0; for (uint index = 0; index < allProjectsHashes.length; index++) { bytes32 agreementHash = allProjectsHashes[index]; if (projects[agreementHash].endDate == 0) { continue; } uint8 score = getProjectScoreByType(agreementHash, _scoreType); if (score == 0) { continue; } endedProjectsCount++; rating = rating.add(score); } return (rating, endedProjectsCount); } /** * @dev Returns all projects for the given address depending on the provided score type. * @param _address An `address` to look up. * @param _scoreType A `ScoreType` to identify projects source. * @return `bytes32[]` of projects hashes either from `clientProjects` or `makerProjects` storage arrays. */ function getProjectsByScoreType(address _address, ScoreType _scoreType) internal view returns(bytes32[]) { if (_scoreType == ScoreType.CustomerSatisfaction) { return makerProjects[_address]; } else { return clientProjects[_address]; } } /** * @dev Returns project score by the given type. * @param _agreementHash A `bytes32` hash of a project`s agreement id. * @param _scoreType A `ScoreType` to identify what score is requested. * @return An `uint8` score of the given project and of the given type. */ function getProjectScoreByType(bytes32 _agreementHash, ScoreType _scoreType) internal view returns(uint8) { if (_scoreType == ScoreType.CustomerSatisfaction) { return projects[_agreementHash].customerSatisfaction; } else { return projects[_agreementHash].makerSatisfaction; } } /** * @dev Deploy DecoEscrow contract clone for the newly created project. * @param _newContractOwner An `address` of a new contract owner. * @return An `address` of a new deployed escrow contract. */ function deployEscrowClone(address _newContractOwner) internal returns(address) { DecoRelay relay = DecoRelay(relayContractAddress); DecoEscrowFactory factory = DecoEscrowFactory(relay.escrowFactoryContractAddress()); return factory.createEscrow(_newContractOwner, relay.milestonesContractAddress()); } /** * @dev Check validness of maker's signature on project creation. * @param _maker An `address` of a maker. * @param _signature A `bytes` digital signature generated by a maker. * @param _agreementId A unique id of the agreement document for a project * @param _arbiter An `address` of a referee to settle all escalated disputes between parties. * @return A `bool` indicating validity of the signature. */ function isMakersSignatureValid(address _maker, bytes _signature, string _agreementId, address _arbiter) internal view returns (bool) { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(Proposal(_agreementId, _arbiter)) )); address signatureAddress = digest.recover(_signature); return signatureAddress == _maker; } function hash(EIP712Domain eip712Domain) internal view returns (bytes32) { return keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract )); } function hash(Proposal proposal) internal view returns (bytes32) { return keccak256(abi.encode( PROPOSAL_TYPEHASH, keccak256(bytes(proposal.agreementId)), proposal.arbiter )); } } /// @title Contract for Milesotone events and actions handling. contract DecoMilestones is IDecoArbitrationTarget, DecoBaseProjectsMarketplace { address public constant ETH_TOKEN_ADDRESS = address(0x0); // struct to describe Milestone struct Milestone { uint8 milestoneNumber; // original duration of a milestone. uint32 duration; // track all adjustments caused by state changes Active <-> Delivered <-> Rejected // `adjustedDuration` time gets increased by the time that is spent by client // to provide a feedback when agreed milestone time is not exceeded yet. // Initial value is the same as duration. uint32 adjustedDuration; uint depositAmount; address tokenAddress; uint startedTime; uint deliveredTime; uint acceptedTime; // indicates that a milestone progress was paused. bool isOnHold; } // enumeration to describe possible milestone states. enum MilestoneState { Active, Delivered, Accepted, Rejected, Terminated, Paused } // map agreement id hash to milestones list. mapping (bytes32 => Milestone[]) public projectMilestones; // Logged when milestone state changes. event LogMilestoneStateUpdated ( bytes32 indexed agreementHash, address indexed sender, uint timestamp, uint8 milestoneNumber, MilestoneState indexed state ); event LogMilestoneDurationAdjusted ( bytes32 indexed agreementHash, address indexed sender, uint32 amountAdded, uint8 milestoneNumber ); /** * @dev Starts a new milestone for the project and deposit ETH in smart contract`s escrow. * @param _agreementHash A `bytes32` hash of the agreement id. * @param _depositAmount An `uint` of wei that are going to be deposited for a new milestone. * @param _duration An `uint` seconds of a milestone duration. */ function startMilestone( bytes32 _agreementHash, uint _depositAmount, address _tokenAddress, uint32 _duration ) external { uint8 completedMilestonesCount = uint8(projectMilestones[_agreementHash].length); if (completedMilestonesCount > 0) { Milestone memory lastMilestone = projectMilestones[_agreementHash][completedMilestonesCount - 1]; require(lastMilestone.acceptedTime > 0, "All milestones must be accepted prior starting a new one."); } DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require( projectsContract.getProjectClient(_agreementHash) == msg.sender, "Only project's client starts a miestone" ); require( projectsContract.getProjectMilestonesCount(_agreementHash) > completedMilestonesCount, "Milestones count should not exceed the number configured in the project." ); require( projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active." ); blockFundsInEscrow( projectsContract.getProjectEscrowAddress(_agreementHash), _depositAmount, _tokenAddress ); uint nowTimestamp = now; projectMilestones[_agreementHash].push( Milestone( completedMilestonesCount + 1, _duration, _duration, _depositAmount, _tokenAddress, nowTimestamp, 0, 0, false ) ); emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, completedMilestonesCount + 1, MilestoneState.Active ); } /** * @dev Maker delivers the current active milestone. * @param _agreementHash Project`s unique hash. */ function deliverLastMilestone(bytes32 _agreementHash) external { DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require(projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active."); require(projectsContract.getProjectMaker(_agreementHash) == msg.sender, "Sender must be a maker."); uint nowTimestamp = now; uint8 milestonesCount = uint8(projectMilestones[_agreementHash].length); require(milestonesCount > 0, "There must be milestones to make a delivery."); Milestone storage milestone = projectMilestones[_agreementHash][milestonesCount - 1]; require( milestone.startedTime > 0 && milestone.deliveredTime == 0 && milestone.acceptedTime == 0, "Milestone must be active, not delivered and not accepted." ); require(!milestone.isOnHold, "Milestone must not be paused."); milestone.deliveredTime = nowTimestamp; emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, milestonesCount, MilestoneState.Delivered ); } /** * @dev Project owner accepts the current delivered milestone. * @param _agreementHash Project`s unique hash. */ function acceptLastMilestone(bytes32 _agreementHash) external { DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require(projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active."); require(projectsContract.getProjectClient(_agreementHash) == msg.sender, "Sender must be a client."); uint8 milestonesCount = uint8(projectMilestones[_agreementHash].length); require(milestonesCount > 0, "There must be milestones to accept a delivery."); Milestone storage milestone = projectMilestones[_agreementHash][milestonesCount - 1]; require( milestone.startedTime > 0 && milestone.acceptedTime == 0 && milestone.deliveredTime > 0 && milestone.isOnHold == false, "Milestone should be active and delivered, but not rejected, or already accepted, or put on hold." ); uint nowTimestamp = now; milestone.acceptedTime = nowTimestamp; if (projectsContract.getProjectMilestonesCount(_agreementHash) == milestonesCount) { projectsContract.completeProject(_agreementHash); } distributeFundsInEscrow( projectsContract.getProjectEscrowAddress(_agreementHash), projectsContract.getProjectMaker(_agreementHash), milestone.depositAmount, milestone.tokenAddress ); emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, milestonesCount, MilestoneState.Accepted ); } /** * @dev Project owner rejects the current active milestone. * @param _agreementHash Project`s unique hash. */ function rejectLastDeliverable(bytes32 _agreementHash) external { DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); require(projectsContract.getProjectEndDate(_agreementHash) == 0, "Project should be active."); require(projectsContract.getProjectClient(_agreementHash) == msg.sender, "Sender must be a client."); uint8 milestonesCount = uint8(projectMilestones[_agreementHash].length); require(milestonesCount > 0, "There must be milestones to reject a delivery."); Milestone storage milestone = projectMilestones[_agreementHash][milestonesCount - 1]; require( milestone.startedTime > 0 && milestone.acceptedTime == 0 && milestone.deliveredTime > 0 && milestone.isOnHold == false, "Milestone should be active and delivered, but not rejected, or already accepted, or on hold." ); uint nowTimestamp = now; if (milestone.startedTime.add(milestone.adjustedDuration) > milestone.deliveredTime) { uint32 timeToAdd = uint32(nowTimestamp.sub(milestone.deliveredTime)); milestone.adjustedDuration += timeToAdd; emit LogMilestoneDurationAdjusted ( _agreementHash, msg.sender, timeToAdd, milestonesCount ); } milestone.deliveredTime = 0; emit LogMilestoneStateUpdated( _agreementHash, msg.sender, nowTimestamp, milestonesCount, MilestoneState.Rejected ); } /** * @dev Prepare arbitration target for a started dispute. * @param _idHash A `bytes32` hash of id. */ function disputeStartedFreeze(bytes32 _idHash) public { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); require( projectsContract.getProjectArbiter(_idHash) == msg.sender, "Freezing upon dispute start can be sent only by arbiter." ); uint milestonesCount = projectMilestones[_idHash].length; require(milestonesCount > 0, "There must be active milestone."); Milestone storage lastMilestone = projectMilestones[_idHash][milestonesCount - 1]; lastMilestone.isOnHold = true; emit LogMilestoneStateUpdated( _idHash, msg.sender, now, uint8(milestonesCount), MilestoneState.Paused ); } /** * @dev React to an active dispute settlement with given parameters. * @param _idHash A `bytes32` hash of id. * @param _respondent An `address` of a respondent. * @param _respondentShare An `uint8` share for the respondent. * @param _initiator An `address` of a dispute initiator. * @param _initiatorShare An `uint8` share for the initiator. * @param _isInternal A `bool` indicating if dispute was settled by participants without an arbiter. * @param _arbiterWithdrawalAddress An `address` for sending out arbiter compensation. */ function disputeSettledTerminate( bytes32 _idHash, address _respondent, uint8 _respondentShare, address _initiator, uint8 _initiatorShare, bool _isInternal, address _arbiterWithdrawalAddress ) public { uint milestonesCount = projectMilestones[_idHash].length; require(milestonesCount > 0, "There must be at least one milestone."); Milestone memory lastMilestone = projectMilestones[_idHash][milestonesCount - 1]; require(lastMilestone.isOnHold, "Last milestone must be on hold."); require(uint(_respondentShare).add(uint(_initiatorShare)) == 100, "Shares must be 100% in sum."); DecoProjects projectsContract = DecoProjects( DecoRelay(relayContractAddress).projectsContractAddress() ); ( uint fixedFee, uint8 shareFee, address escrowAddress ) = projectsContract.getInfoForDisputeAndValidate ( _idHash, _respondent, _initiator, msg.sender ); distributeDisputeFunds( escrowAddress, lastMilestone.tokenAddress, _respondent, _initiator, _initiatorShare, _isInternal, _arbiterWithdrawalAddress, lastMilestone.depositAmount, fixedFee, shareFee ); projectsContract.terminateProject(_idHash); emit LogMilestoneStateUpdated( _idHash, msg.sender, now, uint8(milestonesCount), MilestoneState.Terminated ); } /** * @dev Check eligibility of a given address to perform operations, * basically the address should be either client or maker. * @param _idHash A `bytes32` hash of id. * @param _addressToCheck An `address` to check. * @return A `bool` check status. */ function checkEligibility(bytes32 _idHash, address _addressToCheck) public view returns(bool) { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); return _addressToCheck == projectsContract.getProjectClient(_idHash) || _addressToCheck == projectsContract.getProjectMaker(_idHash); } /** * @dev Check if target is ready for a dispute. * @param _idHash A `bytes32` hash of id. * @return A `bool` check status. */ function canStartDispute(bytes32 _idHash) public view returns(bool) { uint milestonesCount = projectMilestones[_idHash].length; if (milestonesCount == 0) return false; Milestone memory lastMilestone = projectMilestones[_idHash][milestonesCount - 1]; if (lastMilestone.isOnHold || lastMilestone.acceptedTime > 0) return false; address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); uint feedbackWindow = uint(projectsContract.getProjectFeedbackWindow(_idHash)).mul(24 hours); uint nowTimestamp = now; uint plannedDeliveryTime = lastMilestone.startedTime.add(uint(lastMilestone.adjustedDuration)); if (plannedDeliveryTime < lastMilestone.deliveredTime || plannedDeliveryTime < nowTimestamp) { return false; } if (lastMilestone.deliveredTime > 0 && lastMilestone.deliveredTime.add(feedbackWindow) < nowTimestamp) return false; return true; } /** * @dev Either project owner or maker can terminate the project in certain cases * and the current active milestone must be marked as terminated for records-keeping. * All blocked funds should be distributed in favor of eligible project party. * The termination with this method initiated only by project contract. * @param _agreementHash Project`s unique hash. * @param _initiator An `address` of the termination initiator. */ function terminateLastMilestone(bytes32 _agreementHash, address _initiator) public { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); require(msg.sender == projectsContractAddress, "Method should be called by Project contract."); DecoProjects projectsContract = DecoProjects(projectsContractAddress); require(projectsContract.checkIfProjectExists(_agreementHash), "Project must exist."); address projectClient = projectsContract.getProjectClient(_agreementHash); address projectMaker = projectsContract.getProjectMaker(_agreementHash); require( _initiator == projectClient || _initiator == projectMaker, "Initiator should be either maker or client address." ); if (_initiator == projectClient) { require(canClientTerminate(_agreementHash)); } else { require(canMakerTerminate(_agreementHash)); } uint milestonesCount = projectMilestones[_agreementHash].length; if (milestonesCount == 0) return; Milestone memory lastMilestone = projectMilestones[_agreementHash][milestonesCount - 1]; if (lastMilestone.acceptedTime > 0) return; address projectEscrowContractAddress = projectsContract.getProjectEscrowAddress(_agreementHash); if (_initiator == projectClient) { unblockFundsInEscrow( projectEscrowContractAddress, lastMilestone.depositAmount, lastMilestone.tokenAddress ); } else { distributeFundsInEscrow( projectEscrowContractAddress, _initiator, lastMilestone.depositAmount, lastMilestone.tokenAddress ); } emit LogMilestoneStateUpdated( _agreementHash, msg.sender, now, uint8(milestonesCount), MilestoneState.Terminated ); } /** * @dev Returns the last project milestone completion status and number. * @param _agreementHash Project's unique hash. * @return isAccepted A boolean flag for acceptance state, and milestoneNumber for the last milestone. */ function isLastMilestoneAccepted( bytes32 _agreementHash ) public view returns(bool isAccepted, uint8 milestoneNumber) { milestoneNumber = uint8(projectMilestones[_agreementHash].length); if (milestoneNumber > 0) { isAccepted = projectMilestones[_agreementHash][milestoneNumber - 1].acceptedTime > 0; } else { isAccepted = false; } } /** * @dev Client can terminate milestone if the last milestone delivery is overdue and * milestone is not on hold. By default termination is not available. * @param _agreementHash Project`s unique hash. * @return `true` if the last project's milestone could be terminated by client. */ function canClientTerminate(bytes32 _agreementHash) public view returns(bool) { uint milestonesCount = projectMilestones[_agreementHash].length; if (milestonesCount == 0) return false; Milestone memory lastMilestone = projectMilestones[_agreementHash][milestonesCount - 1]; return lastMilestone.acceptedTime == 0 && !lastMilestone.isOnHold && lastMilestone.startedTime.add(uint(lastMilestone.adjustedDuration)) < now; } /** * @dev Maker can terminate milestone if delivery review is taking longer than project feedback window and * milestone is not on hold, or if client doesn't start the next milestone for a period longer than * project's milestone start window. By default termination is not available. * @param _agreementHash Project`s unique hash. * @return `true` if the last project's milestone could be terminated by maker. */ function canMakerTerminate(bytes32 _agreementHash) public view returns(bool) { address projectsContractAddress = DecoRelay(relayContractAddress).projectsContractAddress(); DecoProjects projectsContract = DecoProjects(projectsContractAddress); uint feedbackWindow = uint(projectsContract.getProjectFeedbackWindow(_agreementHash)).mul(24 hours); uint milestoneStartWindow = uint(projectsContract.getProjectMilestoneStartWindow( _agreementHash )).mul(24 hours); uint projectStartDate = projectsContract.getProjectStartDate(_agreementHash); uint milestonesCount = projectMilestones[_agreementHash].length; if (milestonesCount == 0) return now.sub(projectStartDate) > milestoneStartWindow; Milestone memory lastMilestone = projectMilestones[_agreementHash][milestonesCount - 1]; uint nowTimestamp = now; if (!lastMilestone.isOnHold && lastMilestone.acceptedTime > 0 && nowTimestamp.sub(lastMilestone.acceptedTime) > milestoneStartWindow) return true; return !lastMilestone.isOnHold && lastMilestone.acceptedTime == 0 && lastMilestone.deliveredTime > 0 && nowTimestamp.sub(feedbackWindow) > lastMilestone.deliveredTime; } /* * @dev Block funds in escrow from balance to the blocked balance. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _amount An `uint` amount to distribute. * @param _tokenAddress An `address` of a token. */ function blockFundsInEscrow( address _projectEscrowContractAddress, uint _amount, address _tokenAddress ) internal { if (_amount == 0) return; DecoEscrow escrow = DecoEscrow(_projectEscrowContractAddress); if (_tokenAddress == ETH_TOKEN_ADDRESS) { escrow.blockFunds(_amount); } else { escrow.blockTokenFunds(_tokenAddress, _amount); } } /* * @dev Unblock funds in escrow from blocked balance to the balance. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _amount An `uint` amount to distribute. * @param _tokenAddress An `address` of a token. */ function unblockFundsInEscrow( address _projectEscrowContractAddress, uint _amount, address _tokenAddress ) internal { if (_amount == 0) return; DecoEscrow escrow = DecoEscrow(_projectEscrowContractAddress); if (_tokenAddress == ETH_TOKEN_ADDRESS) { escrow.unblockFunds(_amount); } else { escrow.unblockTokenFunds(_tokenAddress, _amount); } } /** * @dev Distribute funds in escrow from blocked balance to the target address. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _distributionTargetAddress Target `address`. * @param _amount An `uint` amount to distribute. * @param _tokenAddress An `address` of a token. */ function distributeFundsInEscrow( address _projectEscrowContractAddress, address _distributionTargetAddress, uint _amount, address _tokenAddress ) internal { if (_amount == 0) return; DecoEscrow escrow = DecoEscrow(_projectEscrowContractAddress); if (_tokenAddress == ETH_TOKEN_ADDRESS) { escrow.distributeFunds(_distributionTargetAddress, _amount); } else { escrow.distributeTokenFunds(_distributionTargetAddress, _tokenAddress, _amount); } } /** * @dev Distribute project funds between arbiter and project parties. * @param _projectEscrowContractAddress An `address` of project`s escrow. * @param _tokenAddress An `address` of a token. * @param _respondent An `address` of a respondent. * @param _initiator An `address` of an initiator. * @param _initiatorShare An `uint8` iniator`s share. * @param _isInternal A `bool` indicating if dispute was settled solely by project parties. * @param _arbiterWithdrawalAddress A withdrawal `address` of an arbiter. * @param _amount An `uint` amount for distributing between project parties and arbiter. * @param _fixedFee An `uint` fixed fee of an arbiter. * @param _shareFee An `uint8` share fee of an arbiter. */ function distributeDisputeFunds( address _projectEscrowContractAddress, address _tokenAddress, address _respondent, address _initiator, uint8 _initiatorShare, bool _isInternal, address _arbiterWithdrawalAddress, uint _amount, uint _fixedFee, uint8 _shareFee ) internal { if (!_isInternal && _arbiterWithdrawalAddress != address(0x0)) { uint arbiterFee = getArbiterFeeAmount(_fixedFee, _shareFee, _amount, _tokenAddress); distributeFundsInEscrow( _projectEscrowContractAddress, _arbiterWithdrawalAddress, arbiterFee, _tokenAddress ); _amount = _amount.sub(arbiterFee); } uint initiatorAmount = _amount.mul(_initiatorShare).div(100); distributeFundsInEscrow( _projectEscrowContractAddress, _initiator, initiatorAmount, _tokenAddress ); distributeFundsInEscrow( _projectEscrowContractAddress, _respondent, _amount.sub(initiatorAmount), _tokenAddress ); } /** * @dev Calculates arbiter`s fee. * @param _fixedFee An `uint` fixed fee of an arbiter. * @param _shareFee An `uint8` share fee of an arbiter. * @param _amount An `uint` amount for distributing between project parties and arbiter. * @param _tokenAddress An `address` of a token. * @return An `uint` amount allotted to the arbiter. */ function getArbiterFeeAmount(uint _fixedFee, uint8 _shareFee, uint _amount, address _tokenAddress) internal pure returns(uint) { if (_tokenAddress != ETH_TOKEN_ADDRESS) { _fixedFee = 0; } return _amount.sub(_fixedFee).mul(uint(_shareFee)).div(100).add(_fixedFee); } } contract DecoProxy { using ECDSA for bytes32; /// Emitted when incoming ETH funds land into account. event Received (address indexed sender, uint value); /// Emitted when transaction forwarded to the next destination. event Forwarded ( bytes signature, address indexed signer, address indexed destination, uint value, bytes data, bytes32 _hash ); /// Emitted when owner is changed event OwnerChanged ( address indexed newOwner ); bool internal isInitialized; // Keep track to avoid replay attack. uint public nonce; /// Proxy owner. address public owner; /** * @dev Initialize the Proxy clone with default values. * @param _owner An address that orders forwarding of transactions. */ function initialize(address _owner) public { require(!isInitialized, "Clone must be initialized only once."); isInitialized = true; owner = _owner; } /** * @dev Payable fallback to accept incoming payments. */ function () external payable { emit Received(msg.sender, msg.value); } /** * @dev Change the owner of this proxy. Used when the user forgets their key, and we can recover it via SSSS split key. This will be the final txn of the forgotten key as it transfers ownership of the proxy to the new replacement key. Note that this is also callable by the contract itself, which would be used in the case that a user is changing their owner address via a metatxn * @param _newOwner An `address` of the new proxy owner. */ function changeOwner(address _newOwner) public { require(owner == msg.sender || address(this) == msg.sender, "Only owner can change owner"); owner = _newOwner; emit OwnerChanged(_newOwner); } /** * @dev Forward a regular (non meta) transaction to the destination address. * @param _destination An `address` where txn should be forwarded to. * @param _value An `uint` of Wei value to be sent out. * @param _data A `bytes` data array of the given transaction. */ function forwardFromOwner(address _destination, uint _value, bytes memory _data) public { require(owner == msg.sender, "Only owner can use forwardFromOwner method"); require(executeCall(_destination, _value, _data), "Call must be successfull."); emit Forwarded("", owner, _destination, _value, _data, ""); } /** * @dev Returns hash for the given transaction. * @param _signer An `address` of transaction signer. * @param _destination An `address` where txn should be forwarded to. * @param _value An `uint` of Wei value to be sent out. * @param _data A `bytes` data array of the given transaction. * @return A `bytes32` hash calculated for all incoming parameters. */ function getHash( address _signer, address _destination, uint _value, bytes memory _data ) public view returns(bytes32) { return keccak256(abi.encodePacked(address(this), _signer, _destination, _value, _data, nonce)); } /** * @dev Forward a meta transaction to the destination address. * @param _signature A `bytes` array cotaining signature generated by owner. * @param _signer An `address` of transaction signer. * @param _destination An `address` where txn should be forwarded to. * @param _value An `uint` of Wei value to be sent out. * @param _data A `bytes` data array of the given transaction. */ function forward(bytes memory _signature, address _signer, address _destination, uint _value, bytes memory _data) public { bytes32 hash = getHash(_signer, _destination, _value, _data); nonce++; require(owner == hash.toEthSignedMessageHash().recover(_signature), "Signer must be owner."); require(executeCall(_destination, _value, _data), "Call must be successfull."); emit Forwarded(_signature, _signer, _destination, _value, _data, hash); } /** * @dev Withdraw given amount of wei to the specified address. * @param _to An `address` of where to send the wei. * @param _value An `uint` amount to withdraw from the contract balance. */ function withdraw(address _to, uint _value) public { require(owner == msg.sender || address(this) == msg.sender, "Only owner can withdraw"); _to.transfer(_value); } /** * @dev Withdraw any ERC20 tokens from the contract balance to owner's address. * @param _tokenAddress An `address` of an ERC20 token. * @param _to An `address` of where to send the tokens. * @param _tokens An `uint` tokens amount. */ function withdrawERC20Token(address _tokenAddress, address _to, uint _tokens) public { require(owner == msg.sender || address(this) == msg.sender, "Only owner can withdraw"); IERC20 token = IERC20(_tokenAddress); require(token.transfer(_to, _tokens), "Tokens transfer must complete successfully."); } /** * @dev Forward txn by executing a call. * @param _to Destination `address`. * @param _value An `uint256` Wei value to be sent out. * @param _data A `bytes` array with txn data. * @return A `bool` completion status. */ function executeCall(address _to, uint256 _value, bytes memory _data) internal returns (bool success) { assembly { let x := mload(0x40) success := call(gas, _to, _value, add(_data, 0x20), mload(_data), 0, 0) } } } contract DecoProxyFactory is DecoBaseProjectsMarketplace, CloneFactory { // Proxy master-contract address. address public libraryAddress; // Logged when a new Escrow clone is deployed to the chain. event ProxyCreated(address newProxyAddress); /** * @dev Constructor for the contract. * @param _libraryAddress Proxy master-contract address. */ constructor(address _libraryAddress) public { libraryAddress = _libraryAddress; } /** * @dev Updates library address with the given value. * @param _libraryAddress Address of a new base contract. */ function setLibraryAddress(address _libraryAddress) external onlyOwner { require(libraryAddress != _libraryAddress); require(_libraryAddress != address(0x0)); libraryAddress = _libraryAddress; } /** * @dev Create Proxy clone. * @param _ownerAddress An address of the Proxy contract owner. */ function createProxy( address _ownerAddress ) external returns(address) { address clone = createClone(libraryAddress); DecoProxy(clone).initialize( _ownerAddress ); emit ProxyCreated(clone); return clone; } }
Override base contract logic to block this operation for Escrow contract. _tokenAddress An `address` of an ERC20 token. _tokens An `uint` tokens amount. return A `bool` operation result state./
function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { return false; }
1,084,639
./full_match/44787/0x6b51A45447cFF1F4e373a3F526ae90F5b97a9194/sources/contracts/DefaultStrategy.sol
Deactivates group. group The group to deactivated./
function deactivateGroup(address group) external onlyOwner { _deactivateGroup(group); }
13,246,529
./full_match/56/0x3260Ebd17d9038d2C2a3b24FFe5c8f1eA10603df/sources/project_/contracts/ClimbToken.sol
Sells CLIMB Tokens And Deposits Underlying Asset Tokens into Seller's Address /
function sell(uint256 tokenAmount) external nonReentrant { _sell(tokenAmount, msg.sender); }
3,243,816
./full_match/1/0x1eE95beCEbCe6Af56EC4C14C752DbD4DbDfF74ac/sources/contracts/feiarb.sol
a function to get the best input to the curve arb save some time to just use getreserve once
function v2_curve_best_out(uint256 lowerbound, uint256 higherbound , uint256 step) public view returns(uint256 bestin, uint256 bestprofit, uint256 best_eth_out){ uint256 curve_out; uint256 amountin; uint256 v2amountout; bytes memory returnData; (, returnData) = address(0x94B0A3d511b6EcDb17eBF877278Ab030acb0A878).staticcall(abi.encodeWithSelector(0x0902f1ac)); while(lowerbound < higherbound){ amountin = lowerbound; curve_out = ethbondingcurve(address(0xB783c0E21763bEf9F2d04E6499abFbe23AdB7e1F)).getAmountOut(amountin); v2amountout = getAmountOut(curve_out, reserve0, reserve1); if(v2amountout < amountin){ break; } if((v2amountout - amountin) > bestprofit){ bestprofit = v2amountout - amountin; bestin = amountin; lowerbound = lowerbound + step; best_eth_out = v2amountout; break; } } }
4,896,954
./partial_match/1/0x1b6a205358e9378Bf9d6cb75F4D3cCcab38cA796/sources/src/ZeroLiquid.sol
Unwraps `amount` of `yieldToken` into its underlying token. yieldToken The address of the yield token to unwrap. amount The amount of the underlying token to wrap. recipient The recipient of the tokens after they are unwrapped. minimumAmountOut The minimum amount of underlying tokens that are expected to be received from the operation. return The amount of underlying tokens that resulted from the operation.
function _unwrap( address yieldToken, uint256 amount, address recipient, uint256 minimumAmountOut ) internal returns (uint256) { ITokenAdapter adapter = ITokenAdapter(_yieldTokens[yieldToken].adapter); uint256 amountUnwrapped = adapter.unwrap(amount, recipient); if (amountUnwrapped < minimumAmountOut) { revert SlippageExceeded(amountUnwrapped, minimumAmountOut); } return amountUnwrapped; }
15,484,949
/** *Submitted for verification at Etherscan.io on 2021-12-30 */ /** *Submitted for verification at Etherscan.io on 2021-07-14 */ // File: contracts/library/SafeMath.sol pragma solidity 0.6.6; /** * @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: contracts/erc20/ERC20.sol pragma solidity 0.6.6; abstract contract ERC20 { using SafeMath for uint256; uint256 private _totalSupply; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); /* * Internal Functions for ERC20 standard logics */ function _transfer(address from, address to, uint256 amount) internal returns (bool success) { _balances[from] = _balances[from].sub( amount, "ERC20/transfer : cannot transfer more than token owner balance" ); _balances[to] = _balances[to].add(amount); emit Transfer(from, to, amount); success = true; } function _approve(address owner, address spender, uint256 amount) internal returns (bool success) { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); success = true; } function _mint(address recipient, uint256 amount) internal returns (bool success) { _totalSupply = _totalSupply.add(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(address(0), recipient, amount); success = true; } function _burn(address burned, uint256 amount) internal returns (bool success) { _balances[burned] = _balances[burned].sub( amount, "ERC20Burnable/burn : Cannot burn more than user's balance" ); _totalSupply = _totalSupply.sub( amount, "ERC20Burnable/burn : Cannot burn more than totalSupply" ); emit Transfer(burned, address(0), amount); success = true; } /* * public view functions to view common data */ function totalSupply() external view returns (uint256 total) { total = _totalSupply; } function balanceOf(address owner) external view returns (uint256 balance) { balance = _balances[owner]; } function allowance(address owner, address spender) external view returns (uint256 remaining) { remaining = _allowances[owner][spender]; } /* * External view Function Interface to implement on final contract */ function name() virtual external view returns (string memory tokenName); function symbol() virtual external view returns (string memory tokenSymbol); function decimals() virtual external view returns (uint8 tokenDecimals); /* * External Function Interface to implement on final contract */ function transfer(address to, uint256 amount) virtual external returns (bool success); function transferFrom(address from, address to, uint256 amount) virtual external returns (bool success); function approve(address spender, uint256 amount) virtual external returns (bool success); } // File: contracts/library/Ownable.sol pragma solidity 0.6.6; contract Ownable { address internal _owner; event OwnershipTransferred( address indexed currentOwner, address indexed newOwner ); constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } modifier onlyOwner() { require( msg.sender == _owner, "Ownable : Function called by unauthorized user." ); _; } function owner() external view returns (address ownerAddress) { ownerAddress = _owner; } function transferOwnership(address newOwner) public onlyOwner returns (bool success) { require(newOwner != address(0), "Ownable/transferOwnership : cannot transfer ownership to zero address"); success = _transferOwnership(newOwner); } function renounceOwnership() external onlyOwner returns (bool success) { success = _transferOwnership(address(0)); } function _transferOwnership(address newOwner) internal returns (bool success) { emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; success = true; } } // File: contracts/erc20/ERC20Lockable.sol pragma solidity 0.6.6; abstract contract ERC20Lockable is ERC20, Ownable { struct LockInfo { uint256 amount; uint256 due; } mapping(address => LockInfo[]) internal _locks; mapping(address => uint256) internal _totalLocked; event Lock(address indexed from, uint256 amount, uint256 due); event Unlock(address indexed from, uint256 amount); modifier checkLock(address from, uint256 amount) { require(_balances[from] >= _totalLocked[from].add(amount), "ERC20Lockable/Cannot send more than unlocked amount"); _; } function _lock(address from, uint256 amount, uint256 due) internal returns (bool success) { require(due > now, "ERC20Lockable/lock : Cannot set due to past"); require( _balances[from] >= amount.add(_totalLocked[from]), "ERC20Lockable/lock : locked total should be smaller than balance" ); _totalLocked[from] = _totalLocked[from].add(amount); _locks[from].push(LockInfo(amount, due)); emit Lock(from, amount, due); success = true; } function _unlock(address from, uint256 index) internal returns (bool success) { LockInfo storage lock = _locks[from][index]; _totalLocked[from] = _totalLocked[from].sub(lock.amount); emit Unlock(from, lock.amount); _locks[from][index] = _locks[from][_locks[from].length - 1]; _locks[from].pop(); success = true; } function unlock(address from) external returns (bool success) { for(uint256 i = 0; i < _locks[from].length; i++){ if(_locks[from][i].due < now){ _unlock(from, i); } } success = true; } function releaseLock(address from) external onlyOwner returns (bool success) { for(uint256 i = 0; i < _locks[from].length; i++){ _unlock(from, i); } success = true; } function transferWithLockUp(address recipient, uint256 amount, uint256 due) external returns (bool success) { require( recipient != address(0), "ERC20Lockable/transferWithLockUp : Cannot send to zero address" ); _transfer(msg.sender, recipient, amount); _lock(recipient, amount, due); success = true; } function lockInfo(address locked, uint256 index) external view returns (uint256 amount, uint256 due) { LockInfo memory lock = _locks[locked][index]; amount = lock.amount; due = lock.due; } function totalLocked(address locked) external view returns(uint256 amount, uint256 length){ amount = _totalLocked[locked]; length = _locks[locked].length; } } // File: contracts/library/Pausable.sol pragma solidity 0.6.6; contract Pausable is Ownable { bool internal _paused; event Paused(); event Unpaused(); modifier whenPaused() { require(_paused, "Paused : This function can only be called when paused"); _; } modifier whenNotPaused() { require(!_paused, "Paused : This function can only be called when not paused"); _; } function pause() external onlyOwner whenNotPaused returns (bool success) { _paused = true; emit Paused(); success = true; } function unPause() external onlyOwner whenPaused returns (bool success) { _paused = false; emit Unpaused(); success = true; } function paused() external view returns (bool) { return _paused; } } // File: contracts/erc20/ERC20Burnable.sol pragma solidity 0.6.6; abstract contract ERC20Burnable is ERC20, Pausable { event Burn(address indexed burned, uint256 amount); function burn(uint256 amount) external whenNotPaused returns (bool success) { success = _burn(msg.sender, amount); emit Burn(msg.sender, amount); success = true; } function burnFrom(address burned, uint256 amount) external whenNotPaused returns (bool success) { _burn(burned, amount); emit Burn(burned, amount); success = _approve( burned, msg.sender, _allowances[burned][msg.sender].sub( amount, "ERC20Burnable/burnFrom : Cannot burn more than allowance" ) ); } } // File: contracts/erc20/ERC20Mintable.sol pragma solidity 0.6.6; abstract contract ERC20Mintable is ERC20, Pausable { event Mint(address indexed receiver, uint256 amount); event MintFinished(); bool internal _mintingFinished; ///@notice mint token ///@dev only owner can call this function function mint(address receiver, uint256 amount) external onlyOwner whenNotPaused returns (bool success) { require( receiver != address(0), "ERC20Mintable/mint : Should not mint to zero address" ); require( !_mintingFinished, "ERC20Mintable/mint : Cannot mint after finished" ); _mint(receiver, amount); emit Mint(receiver, amount); success = true; } ///@notice finish minting, cannot mint after calling this function ///@dev only owner can call this function function finishMint() external onlyOwner returns (bool success) { require( !_mintingFinished, "ERC20Mintable/finishMinting : Already finished" ); _mintingFinished = true; emit MintFinished(); return true; } function isFinished() external view returns(bool finished) { finished = _mintingFinished; } } // File: contracts/library/Freezable.sol pragma solidity 0.6.6; contract Freezable is Ownable { mapping(address => bool) private _frozen; event Freeze(address indexed target); event Unfreeze(address indexed target); modifier whenNotFrozen(address target) { require(!_frozen[target], "Freezable : target is frozen"); _; } function freeze(address target) external onlyOwner returns (bool success) { _frozen[target] = true; emit Freeze(target); success = true; } function unFreeze(address target) external onlyOwner returns (bool success) { _frozen[target] = false; emit Unfreeze(target); success = true; } function isFrozen(address target) external view returns (bool frozen) { return _frozen[target]; } } // File: contracts/Ontact Protocol.sol pragma solidity 0.6.6; contract CROS is ERC20Lockable, ERC20Burnable, ERC20Mintable, Freezable { string constant private _name = "ONTACT Protocol"; string constant private _symbol = "ONTP"; uint8 constant private _decimals = 18; uint256 constant private _initial_supply = 1_900_000_000; constructor() public Ownable() { _mint(msg.sender, _initial_supply * (10**uint256(_decimals))); } function transfer(address to, uint256 amount) override external whenNotFrozen(msg.sender) whenNotPaused checkLock(msg.sender, amount) returns (bool success) { require( to != address(0), "ONTP/transfer : Should not send to zero address" ); _transfer(msg.sender, to, amount); success = true; } function transferFrom(address from, address to, uint256 amount) override external whenNotFrozen(from) whenNotPaused checkLock(from, amount) returns (bool success) { require( to != address(0), "CROS/transferFrom : Should not send to zero address" ); _transfer(from, to, amount); _approve( from, msg.sender, _allowances[from][msg.sender].sub( amount, "CROS/transferFrom : Cannot send more than allowance" ) ); success = true; } function approve(address spender, uint256 amount) override external returns (bool success) { require( spender != address(0), "CROS/approve : Should not approve zero address" ); _approve(msg.sender, spender, amount); success = true; } function name() override external view returns (string memory tokenName) { tokenName = _name; } function symbol() override external view returns (string memory tokenSymbol) { tokenSymbol = _symbol; } function decimals() override external view returns (uint8 tokenDecimals) { tokenDecimals = _decimals; } }
finish minting, cannot mint after calling this function only owner can call this function
function finishMint() external onlyOwner returns (bool success) { require( !_mintingFinished, "ERC20Mintable/finishMinting : Already finished" ); _mintingFinished = true; emit MintFinished(); return true; }
2,394,498
pragma solidity 0.6.5; pragma experimental ABIEncoderV2; struct ProtocolBalance { ProtocolMetadata metadata; AdapterBalance[] adapterBalances; } struct ProtocolMetadata { string name; string description; string websiteURL; string iconURL; uint256 version; } struct AdapterBalance { AdapterMetadata metadata; FullTokenBalance[] balances; } struct AdapterMetadata { address adapterAddress; string adapterType; // "Asset", "Debt" } struct FullTokenBalance { TokenBalance base; TokenBalance[] underlying; } struct TokenBalance { TokenMetadata metadata; uint256 amount; } struct TokenMetadata { address token; string name; string symbol; uint8 decimals; } struct Component { address token; string tokenType; // "ERC20" by default uint256 rate; // price per full share (1e18) } interface ERC20 { function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address) external view returns (uint256); } interface TokenAdapter { /** * @dev MUST return TokenMetadata struct with ERC20-style token info. * struct TokenMetadata { * address token; * string name; * string symbol; * uint8 decimals; * } */ function getMetadata(address token) external view returns (TokenMetadata memory); /** * @dev MUST return array of Component structs with underlying tokens rates for the given token. * struct Component { * address token; // Address of token contract * string tokenType; // Token type ("ERC20" by default) * uint256 rate; // Price per share (1e18) * } */ function getComponents(address token) external view returns (Component[] memory); } interface DODOLpToken { function _OWNER_() external view returns (address); function originToken() external view returns (address); } interface DODO { function _BASE_TOKEN_() external view returns (address); function _BASE_CAPITAL_TOKEN_() external view returns (address); function _QUOTE_TOKEN_() external view returns (address); function getExpectedTarget() external view returns (uint256, uint256); } contract DodoTokenAdapter is TokenAdapter { /** * @return TokenMetadata struct with ERC20-style token info. * @dev Implementation of TokenAdapter interface function. */ function getMetadata(address token) external view override returns (TokenMetadata memory) { return TokenMetadata({ token: token, name: getPoolName(token), symbol: "DLP", decimals: ERC20(token).decimals() }); } /** * @return Array of Component structs with underlying tokens rates for the given token. * @dev Implementation of TokenAdapter interface function. */ function getComponents(address token) external view override returns (Component[] memory) { address dodo = DODOLpToken(token)._OWNER_(); (uint256 baseTarget, uint256 quoteTarget) = DODO(dodo).getExpectedTarget(); address baseToken = DODO(dodo)._BASE_TOKEN_(); address originToken = DODOLpToken(token).originToken(); uint256 underlyingTokenAmount = originToken == baseToken ? baseTarget : quoteTarget; Component[] memory underlyingTokens = new Component[](1); underlyingTokens[0] = Component({ token: originToken, tokenType: "ERC20", rate: underlyingTokenAmount * 1e18 / ERC20(token).totalSupply() }); return underlyingTokens; } function getPoolName(address token) internal view returns (string memory) { address dodo = DODOLpToken(token)._OWNER_(); return string( abi.encodePacked( getSymbol(DODO(dodo)._BASE_TOKEN_()), "/", getSymbol(DODO(dodo)._QUOTE_TOKEN_()), " Pool: ", getSymbol(DODOLpToken(token).originToken()) ) ); } function getSymbol(address token) internal view returns (string memory) { (, bytes memory returnData) = token.staticcall( abi.encodeWithSelector(ERC20(token).symbol.selector) ); if (returnData.length == 32) { return convertToString(abi.decode(returnData, (bytes32))); } else { return abi.decode(returnData, (string)); } } /** * @dev Internal function to convert bytes32 to string and trim zeroes. */ function convertToString(bytes32 data) internal pure returns (string memory) { uint256 counter = 0; bytes memory result; for (uint256 i = 0; i < 32; i++) { if (data[i] != bytes1(0)) { counter++; } } result = new bytes(counter); counter = 0; for (uint256 i = 0; i < 32; i++) { if (data[i] != bytes1(0)) { result[counter] = data[i]; counter++; } } return string(result); } }
return TokenMetadata struct with ERC20-style token info. Implementation of TokenAdapter interface function./
function getMetadata(address token) external view override returns (TokenMetadata memory) { return TokenMetadata({ token: token, name: getPoolName(token), symbol: "DLP", decimals: ERC20(token).decimals() }); }
7,441,302
./full_match/137/0x75a1B0A25edd09589Ba8c1387AD3755d7fDD729E/sources/contracts/polydexrouter.sol
given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, 'PolydexLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'PolydexLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; }
4,674,160
pragma solidity ^0.4.18; import "contracts/Interface/RequestFactoryInterface.sol"; import "contracts/Interface/RequestTrackerInterface.sol"; import "contracts/TransactionRequest.sol"; import "contracts/Library/RequestLib.sol"; import "contracts/IterTools.sol"; /** * @title RequestFactory * @dev Contract which will produce new TransactionRequests. */ contract RequestFactory is RequestFactoryInterface { using IterTools for bool[6]; // RequestTracker of this contract. RequestTrackerInterface public requestTracker; function RequestFactory(address _trackerAddress) { require( _trackerAddress != 0x0 ); requestTracker = RequestTrackerInterface(_trackerAddress); } /** * @dev The lowest level interface for creating a transaction request. * * @param _addressArgs [0] - meta.owner * @param _addressArgs [1] - paymentData.donationBenefactor * @param _addressArgs [2] - txnData.toAddress * @param _uintArgs [0] - paymentData.donation * @param _uintArgs [1] - paymentData.payment * @param _uintArgs [2] - schedule.claimWindowSize * @param _uintArgs [3] - schedule.freezePeriod * @param _uintArgs [4] - schedule.reservedWindowSize * @param _uintArgs [5] - schedule.temporalUnit * @param _uintArgs [6] - schedule.windowSize * @param _uintArgs [7] - schedule.windowStart * @param _uintArgs [8] - txnData.callGas * @param _uintArgs [9] - txnData.callValue * @param _uintArgs [10] - txnData.gasPrice * @param _callData - The call data */ function createRequest( address[3] _addressArgs, uint[11] _uintArgs, bytes _callData ) public payable returns (address) { TransactionRequest request = (new TransactionRequest).value(msg.value)( [ msg.sender, // Created by _addressArgs[0], // meta.owner _addressArgs[1], // paymentData.donationBenefactor _addressArgs[2] // txnData.toAddress ], _uintArgs, //uint[11] _callData ); // Track the address locally requests[address(request)] = true; // Log the creation. RequestCreated(address(request)); // Add the request to the RequestTracker requestTracker.addRequest(address(request), _uintArgs[7]); // windowStart return address(request); } /** * The same as createRequest except that it requires validation prior to * creation. * * Parameters are the same as `createRequest` */ function createValidatedRequest( address[3] _addressArgs, uint[11] _uintArgs, bytes _callData ) public payable returns (address) { bool[6] memory isValid = validateRequestParams( _addressArgs, _uintArgs, _callData, msg.value ); if (!isValid.all()) { if (!isValid[0]) { ValidationError(uint8(Errors.InsufficientEndowment)); } if (!isValid[1]) { ValidationError(uint8(Errors.ReservedWindowBiggerThanExecutionWindow)); } if (!isValid[2]) { ValidationError(uint8(Errors.InvalidTemporalUnit)); } if (!isValid[3]) { ValidationError(uint8(Errors.ExecutionWindowTooSoon)); } if (!isValid[4]) { ValidationError(uint8(Errors.CallGasTooHigh)); } if (!isValid[5]) { ValidationError(uint8(Errors.EmptyToAddress)); } // Try to return the ether sent with the message. If this failed // then revert() to force it to be returned if (!msg.sender.send(msg.value)) { revert(); } return 0x0; } return createRequest(_addressArgs, _uintArgs, _callData); } /// ---------------------------- /// Internal /// ---------------------------- /* * @dev The enum for launching `ValidationError` events and mapping them to an error. */ enum Errors { InsufficientEndowment, ReservedWindowBiggerThanExecutionWindow, InvalidTemporalUnit, ExecutionWindowTooSoon, CallGasTooHigh, EmptyToAddress } event ValidationError(uint8 error); /* * @dev Validate the constructor arguments for either `createRequest` or `createValidatedRequest`. */ function validateRequestParams( address[3] _addressArgs, uint[11] _uintArgs, bytes _callData, uint _endowment ) public returns (bool[6]) { return RequestLib.validate( [ msg.sender, // meta.createdBy _addressArgs[0], // meta.owner _addressArgs[1], // paymentData.donationBenefactor _addressArgs[2] // txnData.toAddress ], _uintArgs, _callData, _endowment ); } /// Mapping to hold known requests. mapping (address => bool) requests; function isKnownRequest(address _address) public view returns (bool isKnown) { isKnown = requests[_address]; } }
Validate the constructor arguments for either `createRequest` or `createValidatedRequest`./
function validateRequestParams( address[3] _addressArgs, uint[11] _uintArgs, bytes _callData, uint _endowment ) public returns (bool[6]) { return RequestLib.validate( [ ], _uintArgs, _callData, _endowment ); }
12,696,983
pragma solidity ^0.5.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 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 { 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 = msg.sender; _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public 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; } } /** // Special interface for calling TRC10 methods // see more: https://developers.tron.network/docs/trc10-transfer-in-smart-contracts-2 // Have fun reading it. Hopefully it's bug-free. God bless. */ contract TRC10Integrator { trcToken internal programID; function _safeTRC10Transfer(address payable _to, uint256 _amount) internal { uint256 programBalance = address(this).tokenBalance(programID); if (_amount > programBalance) { _to.transferToken(programBalance, programID); } else { _to.transferToken(_amount, programID); } } function getTokenID() public view returns(trcToken) { return programID; } } /** // Note that it's ownable and the owner wields tremendous power. The ownership // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. */ contract ProgramFarming is Ownable, TRC10Integrator { using SafeMath for uint256; struct UserInfo { uint256 amount; // How many GRM the user has provided in staking. uint256 rewardDebt; // Reward debt uint256 depositTime; // Time to first deposit // // We do some fancy math here. Basically, any point in time, the amount of GRM // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accProgramPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accProgramPerShare` (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. } // The block number when Program farming starts. uint256[] public phases; uint256 public lastRewardBlock; uint256 internal accProgramPerShare; // Accumulated ProgramToken per share, times 1e11 // Bonus multiplier for early prg makers. uint256 public BONUS_MULTIPLIER_1 = 174; // first 10,512,000 blocks - 2,0`Program in Block uint256 public BONUS_MULTIPLIER_2 = 87; // next 10,512,000 blocks - 1,0 Program in Block uint256 public BONUS_MULTIPLIER_3 = 43; // next 10,512,000 blocks - 0,5 Program in BLock uint256 public BONUS_MULTIPLIER_4 = 37; // last 77,360,000 blocks - 0,3 Program in Block uint256 public baseProgramPerBlock = 1e4; // 0,01 PRGRM // Info of each user that stakes GRM. mapping (address => UserInfo) public userInfo; uint256 public programSupply; // How much their ProgramTokens deposited users event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); constructor(uint256 _startBlock, uint256 _programID) public { programID = trcToken(_programID); phases.push(_startBlock); phases.push(phases[0].add(10512000)); phases.push(phases[1].add(10512000)); phases.push(phases[2].add(10512000)); phases.push(phases[3].add(77360000)); } function setProgramPerBlock(uint256 _newAmount) public onlyOwner{ baseProgramPerBlock = _newAmount; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= phases[0]) { return _to.sub(_from); } else if (_to <= phases[1]) { return _to.sub(_from).mul(BONUS_MULTIPLIER_1); } else if (_to <= phases[2]) { return _to.sub(_from).mul(BONUS_MULTIPLIER_2); } else if (_to <= phases[3]) { return _to.sub(_from).mul(BONUS_MULTIPLIER_3); } else if (_to <= phases[4]) { return _to.sub(_from).mul(BONUS_MULTIPLIER_4); } else if (_from >= phases[4]) { return _to.sub(_from); } else { return phases[4].sub(_from).mul(BONUS_MULTIPLIER_1).add(_to.sub(phases[4])); } } // View function to see pending ProgramTokens on frontend. function pendingProgram(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 programPerShare = accProgramPerShare; if (block.number > lastRewardBlock && programSupply != 0) { uint256 multiplier = getMultiplier(lastRewardBlock, block.number); uint256 programReward = (multiplier.mul(baseProgramPerBlock)); programPerShare = programPerShare.add(programReward.mul(1e11).div(programSupply)); } return user.amount.mul(programPerShare).div(1e11).sub(user.rewardDebt); } // Update reward variables of the given pool to be up-to-date. function updatePool() public { if (block.number <= lastRewardBlock) { return; } if (programSupply == 0) { lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(lastRewardBlock, block.number); uint256 programReward = multiplier.mul(baseProgramPerBlock); accProgramPerShare = accProgramPerShare.add(programReward.mul(1e11).div(programSupply)); lastRewardBlock = block.number; } // Deposit Program function deposit() external payable { require(msg.tokenid == getTokenID(), "ProgramFarming: invalid ProgramToken ID"); uint256 _amount = msg.tokenvalue; programSupply = programSupply.add(_amount); UserInfo storage user = userInfo[msg.sender]; updatePool(); if (user.amount == 0) { user.depositTime = block.timestamp; } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(accProgramPerShare).div(1e11); emit Deposit(msg.sender, _amount); } // Withdraw GRM from Interstellar. function withdraw(uint256 _amount) public { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "ProgramFarming: amount not good"); require(user.depositTime.add(5 days) < now, "ProgramFarming: Less 5 days"); updatePool(); uint256 pending = user.amount.mul(accProgramPerShare).div(1e11).sub(user.rewardDebt); _safeProgramTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(accProgramPerShare).div(1e11); programSupply = programSupply.sub(_amount); _safeProgramTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() public { UserInfo storage user = userInfo[msg.sender]; _safeProgramTransfer(msg.sender, user.amount); programSupply = programSupply.sub(user.amount); emit EmergencyWithdraw(msg.sender, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe ProgramTokens transfer function, just in case if rounding error causes pool to not have enough ProgramTokens. function _safeProgramTransfer(address payable _to, uint256 _amount) internal { _safeTRC10Transfer(_to, _amount); } function withdrawTRX(address payable _sender) public onlyOwner { _sender.transfer(address(this).balance); } function setPhases(uint256 _id, uint256 _newAmount) public onlyOwner { phases[_id] = _newAmount; } function setMultipliers(uint256 _multiplier, uint256 _newAmount) public onlyOwner { if (_multiplier == 1) { BONUS_MULTIPLIER_1 = _newAmount; } if (_multiplier == 2) { BONUS_MULTIPLIER_2 = _newAmount; } if (_multiplier == 3) { BONUS_MULTIPLIER_3 = _newAmount; } if (_multiplier == 4) { BONUS_MULTIPLIER_4 = _newAmount; } } }
Safe ProgramTokens transfer function, just in case if rounding error causes pool to not have enough ProgramTokens.
function _safeProgramTransfer(address payable _to, uint256 _amount) internal { _safeTRC10Transfer(_to, _amount); }
5,459,791
/** *Submitted for verification at Etherscan.io on 2022-04-26 */ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity 0.8.11; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } interface XCopyOriginal { function transfer(address, uint256) external returns (uint256); function transferFrom(address, address, uint256) external returns (uint256); } /** * @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 XCopyWrapper is Context, ERC165, IERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; uint256 public totalSupply; // 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; // XCopy Original Tokens XCopyOriginal[] public _originals; // Token URIs string[] private _tokenURIs; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. Additionally takes a tokenURI and a reference to the wrapped contract */ constructor(string memory name_, string memory symbol_, string[] memory tokenURIs_, XCopyOriginal[] memory originals_) { _name = name_; _symbol = symbol_; _tokenURIs = tokenURIs_; _originals = originals_; } /** * @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) { return _tokenURIs[tokenId]; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = XCopyWrapper.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); } function wrap(XCopyOriginal toWrap) external { uint256 tokenId = 0; for (tokenId; tokenId < _originals.length; tokenId++) { if (toWrap == _originals[tokenId]) break; } require(tokenId < _originals.length, "Not in known / configured originals"); toWrap.transferFrom(msg.sender, address(this), 1); _mint(msg.sender, tokenId); totalSupply += 1; } function unwrap(uint256 tokenId) external { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: unwrap caller is not owner nor approved"); _burn(tokenId); _originals[tokenId].transfer(msg.sender, 1); totalSupply -= 1; } /** * @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 = XCopyWrapper.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 = XCopyWrapper.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(XCopyWrapper.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(XCopyWrapper.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 (isContract(to)) { 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; } } 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 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 {} }
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./ Clear approvals from the previous owner
function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(XCopyWrapper.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); }
10,816,480
./partial_match/5/0x5E9162Dd40B12F1a9aDf69D6c26A00564960C4E3/sources/CryptoDickButtDA.sol
function to get mint price requires sale to be open
function getPrice() public view returns(uint256) { require(saleOpen, "sale not yet open"); uint256 numStepsSinceStart = (block.timestamp - startsAt) / stepDuration; if (numStepsSinceStart >= numSteps) { return(endingPrice); } uint256 price = startingPrice - numStepsSinceStart * stepSize; if (price < endingPrice) { return(endingPrice); return(price); } }
16,835,962
./partial_match/4/0xd2826fd22D3B845dCc5F979BdDDAd33C5d01EDcC/sources/OroNetwork.sol
Shows interest to be paid/ calculate time difference Get number of weeks Get the left out days Get Interest amount based on user loan amount
function viewInterest(address token, uint256 loanId) public view returns (uint256 value, uint256 leftoutDays) { uint256 time = (loans[loanId].interestpaidOn > 0 ? loans[loanId].interestpaidOn : loans[loanId].depositTime); time = now.sub(time); time = time.div(604800); leftoutDays = time.mod(604800); uint256 interest; if(loans[loanId].amount > 0 && loans[loanId].amount >= 10000) { interest = (token == USDC ? USDCInterest[1] : OROInterest[1]); } if(loans[loanId].amount > 10000 && loans[loanId].amount >= 50000) { interest = (token == USDC ? USDCInterest[2] : OROInterest[2]); } if(loans[loanId].amount > 50000 && loans[loanId].amount >= 100000) { interest = (token == USDC ? USDCInterest[3] : OROInterest[3]); } if(loans[loanId].amount > 100000) { interest = (token == USDC ? USDCInterest[4] : OROInterest[4]); } value = (token == USDC ? time.mul((toUSDC(loans[loanId].asset, loans[loanId].amount)).mul(interest).div(10000).div(52)) : time.mul((toORO(loans[loanId].asset, loans[loanId].amount)).mul(interest).div(10000).div(52))); }
8,612,867
pragma solidity ^0.4.25; import "./Library.sol"; import "./Verifier.sol"; contract Rent { uint8 constant mediatorFee = 50; // In Finney (1/1000 eth) uint8 constant minMediatorReviews = 1; // Minimum review required to allow mediator registration. Should be set to a higher value in production. uint8 constant minMediatorReviewScore = 4; // Minimum average review score to allow mediator registration address defaultMediator; constructor() public { // Create and assign a fixed default mediator // This is just a backup solution for now // Initialize empty arrays. This is necessary for struct members and for some reaon cannot be done in the constructor call uint[] memory tenantRentals; uint[] memory mediatorRentals; // Add a new tenant tenants[0xCaDAC9b6ba49e771dbE43Ccc5F03c90Fc9D4Bb04] = Tenant( true, 0x6819c96436218f70de7002cbc0f002fc4ce7b6fdd109a820cf5f25f3cb94c8bd, 0x7fc48e0ea3b94ba41bcf1f570fbf14c8ef7794a5e4158cd1ef62431df50225f1, MediatorStatus.Registered, 0, // Initial score tenantRentals, // Rental ids mediatorRentals, 0 // Number of reviews ); defaultMediator = 0xCaDAC9b6ba49e771dbE43Ccc5F03c90Fc9D4Bb04; } // ------------------------------------------------------------- // ------------------------ Definitions ------------------------ // ------------------------------------------------------------- // ------------------------ Tenants ------------------------ enum MediatorStatus { Unregistered, // Tenant has not registered as mediator yet Registered, // Tenant is registered as mediator Revoked // Mediator status has been revoked (after timeout for mediation) } struct Tenant { bool initialized; bytes32 publicKey_x; bytes32 publicKey_y; MediatorStatus mediatorStatus; uint totalScore; // Total score in sum of all rating points. The average score has to be determined totalScore / numReviews uint[] rentals; // Ids of the rentals (array indices) uint[] mediatedRentals; // Ids of the rentals the tenant is mediating // Using an dynamically sized array instead of a mapping would be more elegant, but is not supported by solidity compiler yet // (can not be initialized due to "Copying of type struct Rent.TenantReview memory[] memory to storage not yet supported") uint numReviews; mapping(uint => TenantReview) reviews; // TenantReview[] reviews; } struct TenantReview { uint8 score; bytes32 hash; // Used for verification bytes32 ipfsHash; // Hash part of IPFS address text encrypted with tenant public key } // ------------------------ Apartments ------------------------ struct Apartment { address ownerAddress; bytes32 ownerPublicKey_x; bytes32 ownerPublicKey_y; bytes32 ipfsHash; // Hash part of IPFS address // Again, a dynamically sized array would be more elegant, but not supported by solidity compiler uint numReviews; mapping(uint => ApartmentReview) reviews; //ApartmentReview[] reviews; } struct ApartmentReview { address tenantAddress; uint8 score; // Score 1-5 bytes32 ipfsHash; // Hash part of IPFS address } // ------------------------ Rentals ------------------------ enum RentalStatus { Requested, Withdrawn, Accepted, Refused, Reviewed } enum DepositStatus { Open, // When no claim to the deposit has been made or is valid yet Pending, // When a deduction was requested Processed // When the deposit was processed => (partly) refunded / deduction transferred } enum DeductionStatus { Requested, // When a deduction has been requested, but the tenant hasn't responded Objected, // When the tenant has objected to the deduction Resolved // When the deduction has been resolved by mediation or timeout } struct DepositDeduction { uint16 lastChange; // As a unix timestamp day uint128 amount; // The requested deduction amount in finney bytes32 reasonIpfsHash; // The reason for the deduction, as hash part of IPFS address, encrypted with tenant and mediator public key bytes32 objectionIpfsHash; // Objection for the deduction created by tenant, encrypted with mediator public key bytes32 conclusionIpfsHash; // The conclusion from the mediation determined by the mediator, encrypted with interaction and tenant public key DeductionStatus status; // Status for the deduction request } struct Rental { bytes32 interactionPublicKey_x; // X point for interaction public key used for private data exchange bytes32 interactionPublicKey_y; // Y point for interaction public key address interactionAddress; // Address used by apartment owner for authentication bytes32 apartmentHash; // Hash of apartment + nonce to later prove apartment involved in rental bytes32 detailsIpfsHash; // Hash part of IPFS address for rental details encrypted with interaction public key bytes32 detailsHash; // Hash of rental details to allow verifying forwarded rental details bytes32 detailsForMediatorIpfsHash; // Hash part of IPFS address for rental details encrypted with mediator public key bytes32 contactDataIpfsHash; // Hash part of IPFS address for owner contact details encrypted with tenant public key bytes32 contactDataForMediatorIpfsHash; // Hash part of IPFS address for owner contact details encrypted with mediator public key uint fee; // Total fee for this rental in finney uint128 deposit; // Deposit for this rental in finney address tenantAddress; // The tenant profile address address mediatorAddress; // The mediator determined for this rental (as soon as the rental is accepted) address ownerAddress; // The addressed used for payments towards the apartment owner and after accept/refuse also as means of authentication RentalStatus status; // Status for the rental DepositStatus depositStatus; // Status of the deposit } // ------------------------------------------------------------ // -------------- Conversion functions for enums -------------- // ------------------------------------------------------------ // Get the string representation for the rental status, lowercase function getRentalStatusString(RentalStatus status) private pure returns (string) { if (status == RentalStatus.Requested) { return "requested"; } if (status == RentalStatus.Withdrawn) { return "withdrawn"; } if (status == RentalStatus.Accepted) { return "accepted"; } if (status == RentalStatus.Refused) { return "refused"; } if (status == RentalStatus.Reviewed) { return "reviewed"; } } // Get the string representation for the deduction status, lowercase function getDeductionStatusString(DeductionStatus status) private pure returns (string) { if (status == DeductionStatus.Requested) { return "requested"; } if (status == DeductionStatus.Objected) { return "objected"; } if (status == DeductionStatus.Resolved) { return "resolved"; } } // Get the string representation for the deposit status, lowercase function getDepositStatusString(DepositStatus status) private pure returns (string) { if (status == DepositStatus.Open) { return "open"; } if (status == DepositStatus.Pending) { return "pending"; } if (status == DepositStatus.Processed) { return "processed"; } } // ------------------------------------------------------------ // ------------------------- Properties ----------------------- // ------------------------------------------------------------ mapping(address => Tenant) private tenants; mapping(bytes32 => mapping(bytes32 => bool)) private tenantPublicKeys; // Mapping to check whether a public key has been used in a tenant's profile address[] private mediators; // List of mediators Apartment[] private apartments; // List of apartments mapping(bytes32 => uint[]) private cityApartments; // Country+City SHA256 hash => apartment ids; to allow fetching apartments of a city mapping(address => uint[]) private ownerApartments; // Mapping to get the apartments of an owner and to check if the address has been used mapping(bytes32 => mapping(bytes32 => bool)) private ownerPublicKeys; // Mapping to check whether a public key has been used in an apartment mapping(bytes32 => mapping(bytes32 => bool)) private interactionKeys; // Mapping to check whether a public key has already been used in another interaction mapping(address => uint) private interactionAddressRental; // Mapping to get the rental for a interaction address mapping(address => bool) private rentalAddresses; // Mapping to check if an address has already been used in an interaction and prevent it from other uses Rental[] private rentals; // List of rentals mapping(uint => DepositDeduction) private depositDeductions; // Deposit deductions for a rental (id => deduction) // --------------------------------------------------------- // ------------------------ Getters ------------------------ // --------------------------------------------------------- // ----------------------- Addresses ----------------------- // Check whether the address is known to the app, and retrieve user type function getAddressType() public view returns (string) { if (hasTenant()) { return "tenant"; } if (ownsApartments()) { return "owner"; } if (hasInteractionAddressRental(msg.sender)) { return "interaction"; } if (rentalAddresses[msg.sender]) { return "rentalOwner"; } return "unknown"; } // ------------------------ Tenants ------------------------ // Check whether a tenant for the address already exists function hasTenant() public view returns (bool) { return tenants[msg.sender].initialized; } // Get the tenant at the specified address function getTenant(address tenantAddr) public view returns ( bytes32 publicKey_x, bytes32 publicKey_y, uint totalScore, uint numReviews ) { // Check that the tenant exists require(tenants[tenantAddr].initialized); // Get the tenant from storage Tenant storage tenant = tenants[tenantAddr]; // Assign the return variables publicKey_x = tenant.publicKey_x; publicKey_y = tenant.publicKey_y; totalScore = tenant.totalScore; numReviews = tenant.numReviews; } // Get the review for the tenant with the specified id function getTenantReview(address tenantAddr, uint reviewId) public view returns ( uint8 score, bytes32 hash, bytes32 ipfsHash ) { // Check that the tenant exists require(tenants[tenantAddr].initialized); // Check that the review exists require(tenants[tenantAddr].numReviews > reviewId); // Get the review from the tenant TenantReview storage review = tenants[tenantAddr].reviews[reviewId]; // Assign the return variables score = review.score; hash = review.hash; ipfsHash = review.ipfsHash; } // ------------------------ Apartments ------------------------ // Check whether the sender owns any apartments function ownsApartments() public view returns (bool) { return ownerApartments[msg.sender].length > 0; } // Get the number of all available apartments function getNumApartments() public view returns (uint) { return apartments.length; } // Get the apartment at the specified id function getApartment(uint apartmentId) public view returns ( address ownerAddress, bytes32 ownerPublicKey_x, bytes32 ownerPublicKey_y, bytes32 ipfsHash, uint numReviews ) { // Check that the apartment exists require(apartments.length > apartmentId); // Get the apartment from storage Apartment storage apartment = apartments[apartmentId]; // Assign the return variables ownerAddress = apartment.ownerAddress; ownerPublicKey_x = apartment.ownerPublicKey_x; ownerPublicKey_y = apartment.ownerPublicKey_y; ipfsHash = apartment.ipfsHash; numReviews = apartment.numReviews; } // Get the number of apartments available in a city function getNumCityApartments(bytes32 cityHash) public view returns (uint) { return cityApartments[cityHash].length; } // Get a city apartment at the specified id function getCityApartment(bytes32 cityHash, uint cityApartmentId) public view returns ( uint id, address ownerAddress, bytes32 ownerPublicKey_x, bytes32 ownerPublicKey_y, bytes32 ipfsHash, uint numReviews ) { // Check that the apartment exists require(cityApartments[cityHash].length > cityApartmentId); id = cityApartments[cityHash][cityApartmentId]; // Get the apartment from storage Apartment storage apartment = apartments[id]; // Assign the return variables ownerAddress = apartment.ownerAddress; ownerPublicKey_x = apartment.ownerPublicKey_x; ownerPublicKey_y = apartment.ownerPublicKey_y; ipfsHash = apartment.ipfsHash; numReviews = apartment.numReviews; } // Get the number of apartments created by the owner function getNumOwnerApartments(address ownerAddr) public view returns (uint) { return ownerApartments[ownerAddr].length; } // Get the apartment of the owner with the specified id function getOwnerApartment(address ownerAddr, uint ownerApartmentId) public view returns ( uint id, bytes32 ownerPublicKey_x, bytes32 ownerPublicKey_y, bytes32 ipfsHash, uint numReviews ) { // Check that the apartment exists require(ownerApartments[ownerAddr].length > ownerApartmentId); id = ownerApartments[ownerAddr][ownerApartmentId]; // Get the apartment from storage Apartment storage apartment = apartments[id]; // Assign the return variables ownerPublicKey_x = apartment.ownerPublicKey_x; ownerPublicKey_y = apartment.ownerPublicKey_y; ipfsHash = apartment.ipfsHash; numReviews = apartment.numReviews; } // -------------------- Apartment reviews ------------------ function getApartmentReview(uint apartmentId, uint reviewId) public view returns ( address tenantAddress, uint8 score, bytes32 ipfsHash ) { // Check that the apartment exists require(apartments.length > apartmentId); // Check that the review exists require(apartments[apartmentId].numReviews > reviewId); // Get the review from storage ApartmentReview storage review = apartments[apartmentId].reviews[reviewId]; // Assign the return variables tenantAddress = review.tenantAddress; score = review.score; ipfsHash = review.ipfsHash; } // ------------------------ Rentals ------------------------ // Get the number of rentals by the tenant function getNumTenantRentals(address tenantAddr) public view returns (uint) { // If the tenant doesn't exist, he also doesn't have rentals if (!tenants[tenantAddr].initialized) { return 0; } return tenants[tenantAddr].rentals.length; } // Get a tenant's rental with the specified id function getTenantRental(address tenantAddr, uint tenantRentalId) public view returns ( uint id, address interactionAddress, address mediatorAddress, bytes32 interactionPublicKey_x, bytes32 interactionPublicKey_y, bytes32 apartmentHash, bytes32 contactDataIpfsHash, uint fee, uint deposit, string status, string depositStatus ) { // Check that the tenant exists require(tenants[tenantAddr].initialized); // Check that the tenant's rental exists require(tenants[tenantAddr].rentals.length > tenantRentalId); id = tenants[tenantAddr].rentals[tenantRentalId]; // Assign the return variables. We're not fetching the rental into a local variable as the stack would otherwise be too deep. interactionAddress = rentals[id].interactionAddress; mediatorAddress = rentals[id].mediatorAddress; interactionPublicKey_x = rentals[id].interactionPublicKey_x; interactionPublicKey_y = rentals[id].interactionPublicKey_y; apartmentHash = rentals[id].apartmentHash; contactDataIpfsHash = rentals[id].contactDataIpfsHash; fee = rentals[id].fee; deposit = rentals[id].deposit; status = getRentalStatusString(rentals[id].status); depositStatus = getDepositStatusString(rentals[id].depositStatus); } // Get the number of rentals mediated by the tenant function getNumMediatorRentals(address mediatorAddr) public view returns (uint) { // If the tenant doesn't exist, he also doesn't have mediated rentals if (!tenants[mediatorAddr].initialized) { return 0; } return tenants[mediatorAddr].mediatedRentals.length; } // Get a rental mediated by the tenant with the specified id function getMediatorRental(address mediatorAddr, uint mediatorRentalId) public view returns ( uint id, address tenantAddress, bytes32 interactionPublicKey_x, bytes32 interactionPublicKey_y, bytes32 detailsHash, bytes32 detailsForMediatorIpfsHash, bytes32 contactDataForMediatorIpfsHash, uint deposit, string depositStatus ) { // Check that the mediator exists require(tenants[mediatorAddr].initialized); // Check that the mediated rental exists require(tenants[mediatorAddr].mediatedRentals.length > mediatorRentalId); id = tenants[mediatorAddr].mediatedRentals[mediatorRentalId]; // Assign the return variables. We're not fetching the rental into a local variable as the stack would otherwise be too deep. tenantAddress = rentals[id].tenantAddress; interactionPublicKey_x = rentals[id].interactionPublicKey_x; interactionPublicKey_y = rentals[id].interactionPublicKey_y; detailsHash = rentals[id].detailsHash; detailsForMediatorIpfsHash = rentals[id].detailsForMediatorIpfsHash; contactDataForMediatorIpfsHash = rentals[id].contactDataForMediatorIpfsHash; deposit = rentals[id].deposit; depositStatus = getDepositStatusString(rentals[id].depositStatus); } // Check whether a rental exists for the interaction address function hasInteractionAddressRental(address interactionAddress) public view returns (bool) { return // If the mapping has a (not 0) value for the interaction address, we got a rental for it interactionAddressRental[interactionAddress] != 0 || // Otherwise, check if we have rentals and the rental at id 0 has the same interactionAddress rentals.length != 0 && rentals[0].interactionAddress == interactionAddress; } // Get the rental for the specified interaction address function getInteractionAddressRental(address addr) public view returns ( uint id, address tenantAddress, address mediatorAddress, address ownerAddress, bytes32 interactionPublicKey_x, bytes32 interactionPublicKey_y, bytes32 apartmentHash, bytes32 detailsHash, bytes32 detailsIpfsHash, uint fee, uint deposit, string status, string depositStatus ) { // Check that we have a rental for the interaction key require(hasInteractionAddressRental(addr)); id = interactionAddressRental[addr]; // Assign the return variables interactionPublicKey_x = rentals[id].interactionPublicKey_x; interactionPublicKey_y = rentals[id].interactionPublicKey_y; mediatorAddress = rentals[id].mediatorAddress; tenantAddress = rentals[id].tenantAddress; ownerAddress = rentals[id].ownerAddress; apartmentHash = rentals[id].apartmentHash; detailsHash = rentals[id].detailsHash; detailsIpfsHash = rentals[id].detailsIpfsHash; fee = rentals[id].fee; deposit = rentals[id].deposit; status = getRentalStatusString(rentals[id].status); depositStatus = getDepositStatusString(rentals[id].depositStatus); } // -------------------------------------------------------- // ------------------------ Events ------------------------ // -------------------------------------------------------- event MediatorRegistered(address indexed tenantAddress); event ApartmentAdded(address indexed owner, uint apartmentId); event RentalRequested(address interactionAddress, uint rentalId); event RentalRequestWithdrawn(address interactionAddress, uint rentalId); event RentalRequestRefused(address indexed tenant, uint rentalId); event RentalRequestApproved(address indexed tenant, uint rentalId); event DepositRefunded(address indexed tenant, uint rentalId); event DeductionRequested(address indexed tenant, uint rentalId); event DeductionAccepted(address indexed interactionAddress, uint rentalId); event DeductionRefused(address indexed interactionAddress, address indexed mediatorAddress, uint rentalId); event DeductionMediated(address indexed tenant, address indexed interactionAddress, uint rentalId); event ApartmentReviewed(address indexed owner, uint apartmentId, uint rentalId); // --------------------------------------------------------- // ------------------------ Methods ------------------------ // --------------------------------------------------------- // Add a new apartment function addApartment( bytes32 ownerPublicKey_x, bytes32 ownerPublicKey_y, bytes32 ipfsHash, // Hash part of IPFS address for apartment details bytes32 cityHash // Hash of city + country, used for searching ) public { // Check that the owner isn't a tenant too require(!tenants[msg.sender].initialized); // Check that the ownerPublicKey does not match a tenant's public key require(!tenantPublicKeys[ownerPublicKey_x][ownerPublicKey_y]); // Check that the address has not been used in a rental require(!rentalAddresses[msg.sender]); // Add the apartment to the list of apartments apartments.push(Apartment( msg.sender, ownerPublicKey_x, ownerPublicKey_y, ipfsHash, 0 )); // Add the apartment to the city's apartments cityApartments[cityHash].push(apartments.length - 1); // Add the apartment to the owner's apartments ownerApartments[msg.sender].push(apartments.length - 1); // Add the owner public key to the list of used public keys ownerPublicKeys[ownerPublicKey_x][ownerPublicKey_y] = true; // Emit an event for the added apartment emit ApartmentAdded(msg.sender, apartments.length - 1); } // ------------------------- Users ------------------------- // Register as a mediator with the tenant's account associated with the sender. // Registration will fail if tenant is already mediator or doesn't have a sufficient score // (at least X reviews and a total review score of at least Y is required) function registerMediator() public { // Check if the sender has a tenant account require(tenants[msg.sender].initialized); Tenant storage tenant = tenants[msg.sender]; // Check that the tenant isn't a mediator yet (and hasn't been revoked mediator status yet) require(tenant.mediatorStatus == MediatorStatus.Unregistered); // Check that the tenant has at least 5 reviews with a score of at least 4.0 require(tenant.numReviews >= minMediatorReviews && tenant.totalScore / tenant.numReviews >= minMediatorReviewScore); // Set the tenant as mediator and add him to the list of mediators tenant.mediatorStatus == MediatorStatus.Registered; mediators.push(msg.sender); // Emit a mediator registered event emit MediatorRegistered(msg.sender); } // Create a tenant with the specified publicKey function createTenant( address addr, bytes32 publicKey_x, bytes32 publicKey_y ) private returns (Tenant) { // Check that the address has not been used by an owner or in an interaction require(ownerApartments[addr].length == 0); require(!rentalAddresses[addr]); // Check that the public key has not been used yet require(!tenantPublicKeys[publicKey_x][publicKey_y]); require(!ownerPublicKeys[publicKey_x][publicKey_y]); // Initialize empty arrays. This is necessary for struct members and for some reaon cannot be done in the constructor call uint[] memory tenantRentals; uint[] memory mediatorRentals; // Add a new tenant tenants[addr] = Tenant( true, publicKey_x, publicKey_y, MediatorStatus.Unregistered, 0, // Initial score tenantRentals, // Rental ids mediatorRentals, 0 // Number of reviews ); // Set the public key as used tenant public key tenantPublicKeys[publicKey_x][publicKey_y] = true; } // ------------------------ Rentals ------------------------ // Request a new rental as a tenant function requestRental( uint fee, uint128 deposit, bytes32 interactionKey_x, // Public key for encryption bytes32 interactionKey_y, // Public key for encryption address interactionAddress, // Address for authentication, NOT the owner/sender address (as this is unknown) bytes32 apartmentHash, bytes32 detailsIpfsHash, bytes32 detailsHash, bytes32 tenantPublicKey_x, bytes32 tenantPublicKey_y ) public payable { // Check that the fee is not 0 require(fee > 0); // Check if the transferred value matches the fee and deposit require(fee + deposit == Library.weiToFinney(msg.value)); // Check that the interaction key does not match an existing key require(!tenantPublicKeys[interactionKey_x][interactionKey_y]); require(!ownerPublicKeys[interactionKey_x][interactionKey_y]); require(!interactionKeys[interactionKey_x][interactionKey_y]); // Check that the interaction address isn't empty require(interactionAddress != 0x0); // Check that the interactionAddress does not match a tenant's address require(!tenants[interactionAddress].initialized); // Check that the interactionAddress hasn't been used in a rental require(!hasInteractionAddressRental(interactionAddress)); // Check that the interactionAddress isn't the current address require(interactionAddress != msg.sender); // Check that the interactionKey isn't the same as the tenantPublicKey require(interactionKey_x != tenantPublicKey_x || interactionKey_y != tenantPublicKey_y); // TODO: Also check it doesn't match owner address // Check if the tenant exists; create him otherwise if (!tenants[msg.sender].initialized) { createTenant(msg.sender, tenantPublicKey_x, tenantPublicKey_y); } // Add the rental rentals.push(Rental( interactionKey_x, interactionKey_y, interactionAddress, apartmentHash, detailsIpfsHash, detailsHash, 0, 0, 0, fee, deposit, msg.sender, 0x0, 0x0, RentalStatus.Requested, DepositStatus.Open )); // Add the rental in the tenant's profile tenants[msg.sender].rentals.push(rentals.length - 1); // Link the rental to the interaction key and address interactionKeys[interactionKey_x][interactionKey_y] = true; interactionAddressRental[interactionAddress] = rentals.length - 1; emit RentalRequested(interactionAddress, rentals.length - 1); } // Withdraw a rental request as a tenant function withdrawRentalRequest( uint rentalId ) public { // Check that the rental exists require(rentals.length > rentalId && rentals[rentalId].fee != 0); Rental storage rental = rentals[rentalId]; // Check authorization for the sender require(msg.sender == rental.tenantAddress); // Check that the rental is in the right state require(rental.status == RentalStatus.Requested); // Change the rental status rental.status = RentalStatus.Withdrawn; // Refund the fee + deposit msg.sender.transfer( Library.finneyToWei(rental.fee + rental.deposit) ); // Emit an event to notify about the withdrawn rental request emit RentalRequestWithdrawn(rental.interactionAddress, rentalId); } // Refuse a rental request as an apartment owner. // Uses the supplied signature to authenticate against the rentals interaction public key. function refuseRental( uint rentalId, string signature // Signature for 'refuse:' + rentalId (this is cheaper than the signature of the sender address) ) public { // Check that the sender address has not been used yet require(!tenants[msg.sender].initialized); require(ownerApartments[msg.sender].length == 0); require(!rentalAddresses[msg.sender]); // Check that the rental exists require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; // Check that the rental has the right state require(rental.status == RentalStatus.Requested); // Recover the expected signer address string memory message = string(abi.encodePacked("refuse:", Library.uintToString(rentalId))); address recovered = Verifier.verifyString( message, signature ); // Check authorization of the owner require(recovered == rental.interactionAddress); // Change the rental's status rental.status = RentalStatus.Refused; // Mark the sender address as used in a rental rentalAddresses[msg.sender] = true; // Transfer fee and deposit back to the tenant rental.tenantAddress.transfer(Library.finneyToWei(rental.fee + rental.deposit)); // Notify about the refused rental request emit RentalRequestRefused(rental.tenantAddress, rentalId); } // Accept a rental request. // Uses the supplied signature to authenticate against the rentals interaction public key. function acceptRental( uint rentalId, bytes32 contactDataIpfsHash, string signature // Signature for msg.sender address as authentication ) public { // Check that the sender address has not been used yet require(!tenants[msg.sender].initialized); require(ownerApartments[msg.sender].length == 0); require(!rentalAddresses[msg.sender]); // Check that the rental exists require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; // Check that the rental has the right state require(rental.status == RentalStatus.Requested); // Recover the signer address address recovered = Verifier.verifyString( Library.addressToString(msg.sender), signature ); // Check authorization of the owner require(recovered == rental.interactionAddress); // Example for verifications of signatures for with integers, bytes32, strings and addresses: //string memory c = Library.b32ToString(contactDataIpfsHash); //string memory a = Library.addressToString(msg.sender); // Pass this message into the verifyString function //string memory message = string(abi.encodePacked( // "accept:", // Library.uintToString(rentalId), // "-", // c, // "-", // a // )); // Change the rental's status rental.status = RentalStatus.Accepted; // Store the contact data rental.contactDataIpfsHash = contactDataIpfsHash; // Use the sender address as owner address rental.ownerAddress = msg.sender; // Mark the sender address as used in a rental rentalAddresses[msg.sender] = true; // Assign a random mediator for the case of a dispute rental.mediatorAddress = getRandomMediator(); // Transfer the rental fee to the sender (= payment address) msg.sender.transfer(Library.finneyToWei(rental.fee)); // Notify about the accepted rental request emit RentalRequestApproved(rental.tenantAddress, rentalId); } // Get a pseudo-random mediator function getRandomMediator() private view returns (address) { // If we don't have mediators, return the default mediator if (mediators.length == 0) { return defaultMediator; } // If we only have one mediator, return him if (mediators.length == 1) { return mediators[0]; } // Get the mediator based on a pseudo-random number generated using the block timestamp and difficulty return mediators[ uint256(keccak256( abi.encodePacked( Library.uintToString(block.timestamp), Library.uintToString(block.difficulty) ) )) % mediators.length ]; } // --------------------- Owner review --------------------- // End a rental as an apartment owner function endRental( uint rentalId, uint8 reviewScore, bytes32 reviewTextHash, bytes32 reviewTextIpfsHash, uint128 deductionAmount, // Requested deposit deduction; can be 0 bytes32 deductionReasonIpfsHash, // Reason for deposit deduction; can be empty if no deduction requested bytes32 contactDataForMediatorIpfsHash // Contact data for the mediator ) public { // Check that the rental exists require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; Tenant storage tenant = tenants[rental.tenantAddress]; // Check the score makes sense require(reviewScore < 6 && reviewScore > 0); // Check that the deduction amount (if specified) is smaller or equal to the deposit require(deductionAmount <= rental.deposit); // Check that the sender is the owner require(msg.sender == rental.ownerAddress); // Check that the rental has not ended yet => the deposit is still open require(rental.depositStatus == DepositStatus.Open); // Assign the review to the tenant TenantReview memory review = TenantReview(reviewScore, reviewTextHash, reviewTextIpfsHash); tenant.reviews[tenant.numReviews] = review; tenant.numReviews ++; // If no deduction was requested, we can directly transfer the deposit back to the tenant if (deductionAmount == 0) { rental.depositStatus = DepositStatus.Processed; rental.tenantAddress.transfer(rental.deposit); // Notify about the refund emit DepositRefunded(rental.tenantAddress, rentalId); return; } // Create a deposit deduction and it add to the rental DepositDeduction memory depositDeduction = DepositDeduction( uint16(block.timestamp / 86400), deductionAmount, deductionReasonIpfsHash, 0, 0, DeductionStatus.Requested ); depositDeductions[rentalId] = depositDeduction; rental.depositStatus = DepositStatus.Pending; // Add the contact data ipfs hash for the mediator to the rental rental.contactDataForMediatorIpfsHash = contactDataForMediatorIpfsHash; // Notify about the requested deduction emit DeductionRequested(rental.tenantAddress, rentalId); } // ---------------------- Deductions ---------------------- // Accept the requested deduction as a tenant function acceptDeduction( uint rentalId ) public { require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; // Only allow accepting deductions from the tenant require(msg.sender == rental.tenantAddress); // Only allow accepting the deduction if the depositStatus and the deduction status match require(rental.depositStatus == DepositStatus.Pending); require(depositDeductions[rentalId].status == DeductionStatus.Requested); // Change the status rental.depositStatus = DepositStatus.Processed; depositDeductions[rentalId].status = DeductionStatus.Resolved; // Transfer the deducted amount to the owner and the rest to the tenant rental.ownerAddress.transfer(Library.finneyToWei(depositDeductions[rentalId].amount)); rental.tenantAddress.transfer(Library.finneyToWei(rental.deposit - depositDeductions[rentalId].amount)); // Delete the deposit deduction delete depositDeductions[rentalId]; // Notify about the accepted deduction emit DeductionAccepted(rental.interactionAddress, rentalId); } // Object to the requested deduction as a tenant function refuseDeduction( uint rentalId, bytes32 objectionIpfsHash, bytes32 detailsForMediatorIpfsHash // Rental details for mediator, encrypted with mediator public key ) public { require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; // Only allow objections from the tenant require(msg.sender == rental.tenantAddress); // Only allow objections if the depositStatus and the deduction status match require(rental.depositStatus == DepositStatus.Pending); require(depositDeductions[rentalId].status == DeductionStatus.Requested); // Add the rental details for the mediator to the rental rental.detailsForMediatorIpfsHash = detailsForMediatorIpfsHash; // Change the status and add the objection depositDeductions[rentalId].status = DeductionStatus.Objected; depositDeductions[rentalId].objectionIpfsHash = objectionIpfsHash; // Update the lastChange day depositDeductions[rentalId].lastChange = uint16(block.timestamp / 86400); // Notify about the refused deduction request emit DeductionRefused(rental.interactionAddress, rental.mediatorAddress, rentalId); } // Mediate in a deduction request dispute function mediate( uint rentalId, uint128 deductionAmount, bytes32 conclusionIpfsHash // Conclusion encrypted with tenant and interaction public key ) public { // Check that the rental exists require(rentals.length > rentalId); Rental storage rental = rentals[rentalId]; // Check that the sender is assigned to the rental as mediator rental.mediatorAddress = msg.sender; // Check that the rental requires mediation require(rental.depositStatus == DepositStatus.Pending); require(depositDeductions[rentalId].status == DeductionStatus.Objected); // Check that the determined deductionAmount is smaller or equal to the deposit + mediatorFee require(rental.deposit >= deductionAmount + mediatorFee); // Set the deduction to resolved and the deposit to processed depositDeductions[rentalId].status = DeductionStatus.Resolved; depositDeductions[rentalId].conclusionIpfsHash = conclusionIpfsHash; rental.depositStatus = DepositStatus.Processed; // Transfer the mediatorFee to the mediator, the deduction to the owner and the rest to the tenant msg.sender.transfer(Library.finneyToWei(mediatorFee)); rental.ownerAddress.transfer(Library.finneyToWei(deductionAmount)); rental.tenantAddress.transfer(Library.finneyToWei(rental.deposit - deductionAmount - mediatorFee)); // Notify about the mediation emit DeductionMediated(rental.tenantAddress, rental.interactionAddress, rentalId); } // -------------------- Tenant review -------------------- // Review an apartment, revealing the rented apartment in the process function review( uint rentalId, uint apartmentId, string requestId, // requestId involved in created apartmentHash string requestIdSignature, // signature of requestId. Has to be signed with apartment owner's address. uint8 score, bytes32 textIpfsHash // Hash of unencrypted review ) public { // Check that the rental and apartment exist require(rentals.length > rentalId); require(apartments.length > apartmentId); Rental storage rental = rentals[rentalId]; Apartment storage apartment = apartments[apartmentId]; // Check that the sender is the tenant rental.tenantAddress = msg.sender; // Check that the rental has not been reviewed yet require(rental.status == RentalStatus.Accepted); // Check constraint: rentals apartment hash matches the sha3 of apartmentId + "-" + requestId require(rental.apartmentHash == keccak256( abi.encodePacked( Library.uintToString(apartmentId), "-", requestId ) )); // Recover the requestId signer address // Does not work currently, so it's disabled /*address recovered = Verifier.verifyString( requestId, requestIdSignature ); // Check the signer is the apartment owner require(apartment.ownerAddress == recovered); */ // Change the rental status to reviewed rental.status = RentalStatus.Reviewed; // Add the review ApartmentReview memory apartmentReview = ApartmentReview( msg.sender, score, textIpfsHash ); apartment.reviews[apartment.numReviews] = apartmentReview; apartment.numReviews ++; // Notify about the review emit ApartmentReviewed(apartment.ownerAddress, apartmentId, rentalId); } }
Add a new apartment Check that the owner isn't a tenant too Check that the ownerPublicKey does not match a tenant's public key Check that the address has not been used in a rental Add the apartment to the list of apartments Add the apartment to the city's apartments Add the apartment to the owner's apartments Add the owner public key to the list of used public keys Emit an event for the added apartment
function addApartment( bytes32 ownerPublicKey_x, bytes32 ownerPublicKey_y, ) public { require(!tenants[msg.sender].initialized); require(!tenantPublicKeys[ownerPublicKey_x][ownerPublicKey_y]); require(!rentalAddresses[msg.sender]); apartments.push(Apartment( msg.sender, ownerPublicKey_x, ownerPublicKey_y, ipfsHash, 0 )); cityApartments[cityHash].push(apartments.length - 1); ownerApartments[msg.sender].push(apartments.length - 1); ownerPublicKeys[ownerPublicKey_x][ownerPublicKey_y] = true; emit ApartmentAdded(msg.sender, apartments.length - 1); }
12,914,889
./partial_match/1/0x5A48E8b22d7741E2c9522A69cF220e488a5dfa76/sources/src/Staking/SplitStakingV1.sol
this is here for public visibility./
function getRewardsForDistribution() external view returns (uint256 min, uint256 max) { min = _minimumRewardsForDistribution; max = _maximumRewardsForDistribution; }
3,577,989
// SPDX-License-Identifier: MIT import "./ShelterNOW.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Pet.sol"; pragma solidity ^0.8.0; /// @author Dylon Wong Chung Yee /// @title An adoption contract to facilitate and keep track of adoptions in an animal shelter. contract Adoption is Ownable, Pet { // Mapping from pet ID to temporary adopter. mapping(uint256 => address) private _tempAdopters; // Mapping from adopters to their deposit. mapping(address => uint256) private _adopterToDeposit; // Mapping from pet ID to the pet's adoption state. mapping(uint256 => AdoptionState) private _petToAdoptionState; // An adoption fee to be paid upon confirmation. uint256 private _adoptionFee; // A refund fee for a unsuccessful adoption. uint256 private _penaltyRefundFee; // SNOW decimals; uint8 private _decimals; // The contract address to the SNOW. ShelterNOW public SNOW; /// REJECTED, CANCELLED, EUTHANISED and REMOVED are not assignable to the _petToAdoptionState, only for event emission. /// The other enum shows the state of the pet in the adoption procedure. enum AdoptionState { NOTAVAIL, ADOPTABLE, LOCKED, APPROVED, ADOPTED, REJECTED, CANCELLED, ADDED, EUTHANISED, REMOVED } // An event to notify stage changes of an animal. event AdoptionStatus(address adopter, uint256 petID, AdoptionState status); // An event to notify tips received from adoption fee. event TipsReceived(address adopter, address owner, uint256 amount); /** * @dev Initializes the contract by setting a token contract address to the adoption contract. * This contract should be excluded from the reflection such that it does not get taxed for refund. * */ constructor(address snowAdd) { /// An adoption fee to be paid upon confirmation, defaults to 10000 SNOW (without decimals) gross amount. /// 4% of the adoption fee will be taxed. _adoptionFee = _normaliseSNOW(1 * 10**4); // A refund fee for a unsuccessful adoption, defaults to 2000 SNOW gross amount. _penaltyRefundFee = _normaliseSNOW(2 * 10**3); SNOW = ShelterNOW(snowAdd); _decimals = SNOW.decimals(); } /** * @dev Add a new pet to the blockchain. * The pet must be set to either adoptable or not. * This function should only be called by the animal shelter. * * @param URI_: An URI that links to the metadata of the pet. * @param newStatus: The status of adoption of the new pet. */ function addPet(string memory URI_, AdoptionState newStatus) public onlyOwner { require( newStatus == AdoptionState.ADOPTABLE || newStatus == AdoptionState.NOTAVAIL, "Adoption status must be either adoptable or not available" ); uint256 newPetID = totalSupply(); require(newPetID == uint256(uint32(newPetID)), "Pet ID overflow!"); _mint(owner(), newPetID); setTokenURI(newPetID, URI_); if (newStatus == AdoptionState.ADOPTABLE) _petToAdoptionState[newPetID] = newStatus; _tempAdopters[newPetID] = msg.sender; emit AdoptionStatus(msg.sender, newPetID, AdoptionState.ADDED); } /** * @dev Request a pet to be adopted. The pet must be in an adoptable status. * Besides that a fixed amount of deposit will be collected to prevent abusive request application. * * **NOTE**: The adopter must approve the contract as a spender with an allowance as the `_adoptionFee`, * to perform a successful transaction via ERC-20 standard. * This should be done in the front-end using the SNOW contract directly * because `msg.sender` will be the adoption contract if {SNOW.approve} is called here. * * @param petID: The pet ID to be adopted. */ function requestAdoption(uint256 petID) public petIDIsValid(petID) { require( _petToAdoptionState[petID] == AdoptionState.ADOPTABLE, "Request: Not available for adoption!" ); address adopter = msg.sender; _adopterToDeposit[adopter] += _adoptionFee; _petToAdoptionState[petID] = AdoptionState.LOCKED; _tempAdopters[petID] = adopter; SNOW.transferFrom(adopter, address(this), _adoptionFee); emit AdoptionStatus(adopter, petID, AdoptionState.LOCKED); } /** * @dev Approve an adoption request. * The pet must be requested for adoption and still in LOCKED state. * This suggests that the pet is still waiting for an approval. * This function also requires the `adopter` parameter to match the actual adopter requesting. * This function should only be called by the animal shelter. * * @param adopter: The address of the adopter. * @param petID: The pet ID to be adopted. */ function approveAdoption(address adopter, uint256 petID) public onlyOwner petIDIsValid(petID) { require( _petToAdoptionState[petID] == AdoptionState.LOCKED, "Not requested for adoption yet!" ); require(_adopterMatches(adopter, petID), "Pet does not match adopter!"); approve(adopter, petID); _petToAdoptionState[petID] = AdoptionState.APPROVED; emit AdoptionStatus(adopter, petID, AdoptionState.APPROVED); } /** * @dev Reject an adoption application request. The requirements of this function is same as `approveAdoption`. * This action is at the same phase as `approveAdoption` in the adoption procedure. * The pet will be set back to `ADOPTABLE` state and this function will emit a `REJECTED` status. * The pet will also be removed from the associated adopter. * * @param adopter: The adopter who applied for adoption. * @param petID: The associated pet ID applied for adoption. */ function rejectAdoption(address adopter, uint256 petID) public onlyOwner petIDIsValid(petID) { require( _petToAdoptionState[petID] == AdoptionState.LOCKED, "Not requested for adoption yet!" ); require(_adopterMatches(adopter, petID), "Pet does not match adopter!"); _resetAdoption( adopter, petID, AdoptionState.ADOPTABLE, AdoptionState.REJECTED ); } /** * @dev Cancel an approved adoption. This function should be called by an adopter. * The adopter can cancel their adoptiona at anytime between approval and confirmation. * The pet will be set to adoptable state and removed from the associated adopter. * * @param petID: The pet adoption to be cancelled. */ function cancelAdoption(uint256 petID) public petIDIsValid(petID) { // The pet must be approved. require( _petToAdoptionState[petID] == AdoptionState.APPROVED, "Not approved for adoption!" ); require( _adopterMatches(msg.sender, petID), "Pet does not match adopter!" ); _resetAdoption( msg.sender, petID, AdoptionState.ADOPTABLE, AdoptionState.CANCELLED ); } /** * @dev Confirm an approved adoption application request. The requires the approveAdoption to be called on the adoption before. * This function receives optional tip from the adopter upon confirmation. * The pet will be set back to `ADOPTED` state and this function will emit a `ADOPTED` status. * Total amount received by the animal shelter is `_adoptionFee + tipAmount - _refundFee` * * If a tip is paid, the `TipsReceived` event will be emitted. * * NOTE: The {SNOW.approve} function is needed here for payment of the adoption fee (See line 166). * The allowance should be same as `amount` including tips. * * @param petID: The pet ID applied for adoption. * @param tipAmount: The amount of tip fee to be paid by the adopter. */ function confirmAdoption(uint256 petID, uint256 tipAmount) public petIDIsValid(petID) { // The pet must be approved. require( _petToAdoptionState[petID] == AdoptionState.APPROVED, "Not approved for adoption!" ); address adopter = msg.sender; address owner = owner(); require(_adopterMatches(adopter, petID), "Pet does not match adopter!"); _petToAdoptionState[petID] = AdoptionState.ADOPTED; _adopterToDeposit[adopter] -= _adoptionFee; safeTransferFrom(owner, adopter, petID); SNOW.transfer(adopter, _adoptionFee); if (tipAmount > 0) { SNOW.transferFrom(adopter, owner, tipAmount); emit TipsReceived(adopter, owner, tipAmount); } emit AdoptionStatus(adopter, petID, AdoptionState.ADOPTED); } /** * @dev Withdraw money from the smart contract if any. */ function withdraw() public payable onlyOwner { require( address(this).balance > 0, "Nothing to be withdrawn from the smart contract!" ); payable(owner()).transfer(address(this).balance); } /** * @dev Withdraw money from the smart contract if any. */ function withdrawSNOW() public onlyOwner { uint256 snowBal = SNOW.balanceOf(address(this)); require( snowBal > 0, "Nothing to be withdrawn from the smart contract!" ); SNOW.transfer(owner(), snowBal); } /** * @dev Get the adoption fee of the animal shelter. * * @return The adoption fee. */ function getAdoptionFee() public view returns (uint256) { return _adoptionFee; } /** * @dev Get the penalty refund fee of the animal shelter. * * @return The penalty refund fee. */ function getPenaltyRefundFee() public view returns (uint256) { return _penaltyRefundFee; } /** * @dev Get the adoption state of a pet (including non available one). * * @param petID: The pet ID to be queried. * * @return The adoption state. */ function getAdoptionState(uint256 petID) public view petIDIsValid(petID) returns (AdoptionState) { return _petToAdoptionState[petID]; } /** * @dev Get the temporary adopter of a pet. * * @param petID: The pet ID to be queried. * * @return The temporary adopter. */ function getTempAdopterOf(uint256 petID) public view petIDIsValid(petID) returns (address) { return _tempAdopters[petID]; } /** * @dev Get the amount of deposit locked of an adopter. * * @param adopter: The adopter to query. * * @return The total deposit locked. */ function getAdopterDeposit(address adopter) public view returns (uint256) { return _adopterToDeposit[adopter]; } /** * @dev Set a pet to be adoptable from a not adoptable state. Only owner can call this function. * * @param petID: The pet ID to be queried. * */ function setPetAdoptable(uint256 petID) public onlyOwner petIDIsValid(petID) { require( _petToAdoptionState[petID] != AdoptionState.ADOPTED, "The pet is already adopted!" ); require( _petToAdoptionState[petID] == AdoptionState.NOTAVAIL, "The pet is already adoptable!" ); _petToAdoptionState[petID] = AdoptionState.ADOPTABLE; emit AdoptionStatus(owner(), petID, AdoptionState.ADOPTABLE); } /** * @dev Set a pet to be not adoptable from an adoptable state. Only owner can call this function. * * @param petID: The pet ID. * */ function setPetNotAdoptable(uint256 petID, AdoptionState reason) public petIDIsValid(petID) onlyOwner { require( _petToAdoptionState[petID] != AdoptionState.NOTAVAIL && _petToAdoptionState[petID] != AdoptionState.ADOPTED, "The pet is already not adoptable!" ); require( reason == AdoptionState.REMOVED || reason == AdoptionState.EUTHANISED, "The state should be a removal state!" ); _resetAdoption( _tempAdopters[petID], petID, AdoptionState.NOTAVAIL, reason ); emit AdoptionStatus(owner(), petID, reason); } /** * @dev Set the token URI of a pet. * * @param petID: Pet ID to be modified. * @param tokenURI_: Token URI to be set. */ function setTokenURI(uint256 petID, string memory tokenURI_) public petIDIsValid(petID) onlyOwner { require( _petToAdoptionState[petID] != AdoptionState.ADOPTED || _petToAdoptionState[petID] != AdoptionState.EUTHANISED ); _setTokenURI(petID, tokenURI_); } /** * @dev Add decimals to the base amount of SNOW. * * @param amount: Amount of SNOW to be normalised. * * @return SNOW with 9 decimals. */ function _normaliseSNOW(uint256 amount) internal view returns (uint256) { return amount * (10**_decimals); } /** * @dev Check if given adopter matches the pet ID. * * @param adopter: The adopter's address. * @param petID: The pet ID adopted. * * @return Match or not. */ function _adopterMatches(address adopter, uint256 petID) internal view petIDIsValid(petID) returns (bool) { // Pet should exists. require( _tempAdopters[petID] != address(0) || ownerOf(petID) != address(0), "Pet does not exist." ); return _tempAdopters[petID] == adopter || ownerOf(petID) == adopter; } /** * @dev Reset an adoption application request back to adoptable state. * The pet will be set back to `ADOPTABLE` state and this function will emit either `CANCELLED` or `REJECTED` status. * The pet will also be removed from the associated adopter. * The adopter will be refunded a small amount of SNOW as stated in `_penaltyRefundFee`, * the rest is donated to the animal shelter as a penalty. * * @param adopter: The adopter who applied for adoption. * @param petID: The associated pet ID applied for adoption. * @param reason: The reason of pet adoption reset. */ function _resetAdoption( address adopter, uint256 petID, AdoptionState status, AdoptionState reason ) private { require( reason == AdoptionState.REMOVED || reason == AdoptionState.EUTHANISED || reason == AdoptionState.CANCELLED || reason == AdoptionState.REJECTED, "The reason should be a removal state!" ); require( status == AdoptionState.NOTAVAIL || status == AdoptionState.ADOPTABLE, "The status should be a removal state!" ); address owner_ = owner(); _tempAdopters[petID] = owner_; _adopterToDeposit[adopter] -= _adoptionFee; _petToAdoptionState[petID] = status; if (reason == AdoptionState.CANCELLED) { SNOW.transfer(adopter, _penaltyRefundFee); SNOW.transfer(owner_, (_adoptionFee - _penaltyRefundFee)); } else if (reason == AdoptionState.REJECTED) { SNOW.transfer(adopter, _adoptionFee / 2); SNOW.transfer(owner_, (_adoptionFee / 2)); } else { if (adopter != owner_) SNOW.transfer(adopter, _adoptionFee); } emit AdoptionStatus(adopter, petID, reason); } }
Request a pet to be adopted. The pet must be in an adoptable status. Besides that a fixed amount of deposit will be collected to prevent abusive request application. NOTE: The adopter must approve the contract as a spender with an allowance as the `_adoptionFee`, to perform a successful transaction via ERC-20 standard. This should be done in the front-end using the SNOW contract directly because `msg.sender` will be the adoption contract if {SNOW.approve} is called here. petID: The pet ID to be adopted./
function requestAdoption(uint256 petID) public petIDIsValid(petID) { require( _petToAdoptionState[petID] == AdoptionState.ADOPTABLE, "Request: Not available for adoption!" ); address adopter = msg.sender; _adopterToDeposit[adopter] += _adoptionFee; _petToAdoptionState[petID] = AdoptionState.LOCKED; _tempAdopters[petID] = adopter; SNOW.transferFrom(adopter, address(this), _adoptionFee); emit AdoptionStatus(adopter, petID, AdoptionState.LOCKED); }
7,213,195
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } 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; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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); } 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 { 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)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () public { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Uniswap V2 library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } library UniswapV2Library { using SafeMathUniswap for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 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 (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure 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 getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); 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); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // Token interface interface TokenInterface is IERC20 { function deposit() external payable; function withdraw(uint256) external; } // Balancer library contract BNum { uint public constant BONE = 10**18; function btoi(uint a) internal pure returns (uint) { return a / BONE; } function bfloor(uint a) internal pure returns (uint) { return btoi(a) * BONE; } function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint a, uint b) internal pure returns (uint) { uint c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BONE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "ERR_DIV_ZERO"); uint c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint c2 = c1 / b; return c2; } } // Balancer pool interface interface BPoolInterface is IERC20 { function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external; function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external; function getNormalizedWeight(address token) external view returns (uint256); function getBalance(address) external view returns (uint256); function getController() external view returns (address); function getCurrentTokens() external view returns (address[] memory tokens); function getNumTokens() external view returns (uint256); } // Swap contract contract UniverseSwap is Ownable, BNum { using SafeMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for TokenInterface; using SafeERC20 for BPoolInterface; // States TokenInterface public weth; TokenInterface public twaEthPair; TokenInterface public twa; BPoolInterface public universeBP; IUniswapV2Router02 public uniswapV2Router; mapping(address => address) public uniswapEthPairByTokenAddress; mapping(address => address) public uniswapEthPairToken0; mapping(address => bool) public reApproveTokens; uint256 public defaultSlippage; bool public isSmartPool; address payable private testReservior; // Events event SetTokenSetting( address indexed token, bool indexed reApprove, address indexed uniswapPair ); event SetDefaultSlippage(uint256 newDefaultSlippage); event EthToUniverseSwap( address indexed user, uint256 ethInAmount, uint256 poolOutAmount ); event UniverseToEthSwap( address indexed user, uint256 poolInAmount, uint256 ethOutAmount ); event BuyTwaAndAddLiquidityToUniswapV2( address indexed msgSender, uint256 totalAmount, uint256 ethAmount, uint256 twaAmount ); event Erc20ToUniverseSwap( address indexed user, address indexed swapToken, uint256 erc20InAmount, uint256 ethInAmount, uint256 poolOutAmount ); event UniverseToErc20Swap( address indexed user, address indexed swapToken, uint256 poolInAmount, uint256 ethOutAmount, uint256 erc20OutAmount ); constructor() public { weth = TokenInterface(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); twaEthPair = TokenInterface(0x748a9631baD6AF6D048aE66e2e6E3F44213Fb1E0); twa = TokenInterface(0xa2EF2757D2eD560c9e3758D1946d7bcccBD5A7fe); universeBP = BPoolInterface(0x2d4D246D8f46D3a2A9Cf6160BCaBbF164C15B36F); uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); defaultSlippage = 0.04 ether; isSmartPool = true; } receive() external payable { if (msg.sender != tx.origin) { return; } swapEthToUniverse(defaultSlippage); } function setTokensSettings( address[] memory _tokens, address[] memory _pairs, bool[] memory _reapprove ) external onlyOwner { uint256 len = _tokens.length; require(len == _pairs.length && len == _reapprove.length, "LENGTHS_NOT_EQUAL"); for (uint256 i = 0; i < len; i++) { _setUniswapSettingAndPrepareToken(_tokens[i], _pairs[i]); reApproveTokens[_tokens[i]] = _reapprove[i]; emit SetTokenSetting(_tokens[i], _reapprove[i], _pairs[i]); } } function fetchUnswapPairsFromFactory(address _factory, address[] calldata _tokens) external onlyOwner { uint256 len = _tokens.length; for (uint256 i = 0; i < len; i++) { _setUniswapSettingAndPrepareToken(_tokens[i], IUniswapV2Factory(_factory).getPair(_tokens[i], address(weth))); } } function setDefaultSlippage(uint256 _defaultSlippage) external onlyOwner { defaultSlippage = _defaultSlippage; emit SetDefaultSlippage(_defaultSlippage); } function setBPoolAddress(address poolAddress) external onlyOwner { universeBP = BPoolInterface(poolAddress); } function swapEthToUniverse(uint256 _slippage) public payable returns (uint256 poolAmountOut) { address[] memory tokens = universeBP.getCurrentTokens(); (, uint256[] memory ethInUniswap, ) = calcSwapEthToUniverseInputs(msg.value, tokens, _slippage); weth.deposit{ value: msg.value }(); poolAmountOut = _swapWethToUniverseByEthIn(ethInUniswap); uint256 oddEth = _checkAndRemoveOddTokens(); emit EthToUniverseSwap(msg.sender, bsub(msg.value, oddEth), poolAmountOut); } function swapErc20ToUniverse( address _swapToken, uint256 _swapAmount, uint256 _slippage ) external returns (uint256 poolAmountOut) { TokenInterface(_swapToken).safeTransferFrom(msg.sender, address(this), _swapAmount); if (_swapToken == address(twa)) { address[] memory path = new address[](2); path[0] = address(twa); path[1] = address(weth); // try to get real twa amount becasue twa burned 1% every transfer uint256 twaAmount = twa.balanceOf(address(this)); twa.approve(address(uniswapV2Router), twaAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( twaAmount, 0, // accept any amount of pair token path, address(this), block.timestamp ); } else { _swapTokenForWethOut(_swapToken, _swapAmount); } uint256 wethAmount = weth.balanceOf(address(this)); uint256 ethAmount = address(this).balance; if (ethAmount > 0) { weth.deposit{ value: ethAmount }(); wethAmount = badd(wethAmount, ethAmount); } address[] memory tokens = universeBP.getCurrentTokens(); uint256[] memory ethInUniswap; (, ethInUniswap, ) = calcSwapEthToUniverseInputs(wethAmount, tokens, _slippage); poolAmountOut = _swapWethToUniverseByEthIn(ethInUniswap); uint256 oddEth = _checkAndRemoveOddTokens(); emit Erc20ToUniverseSwap(msg.sender, _swapToken, _swapAmount, bsub(wethAmount, oddEth), poolAmountOut); } function swapUniverseToEth(uint256 _poolAmountIn) external returns (uint256 ethOutAmount) { _swapUniverseToWeth(_poolAmountIn); uint256 wethAmount = weth.balanceOf(address(this)); if (wethAmount > 0) { weth.withdraw(wethAmount); } ethOutAmount = address(this).balance; msg.sender.transfer(ethOutAmount); emit UniverseToEthSwap(msg.sender, _poolAmountIn, ethOutAmount); } function swapUniverseToErc20( address _swapToken, uint256 _poolAmountIn ) external returns (uint256 erc20Out) { _swapUniverseToWeth(_poolAmountIn); uint256 ethAmount = address(this).balance; if (ethAmount > 0) { weth.deposit{ value: ethAmount }(); } uint256 ethOut = weth.balanceOf(address(this)); _swapWethForTokenOut(_swapToken, ethOut); erc20Out = TokenInterface(_swapToken).balanceOf(address(this)); IERC20(_swapToken).safeTransfer(msg.sender, erc20Out); emit UniverseToErc20Swap(msg.sender, _swapToken, _poolAmountIn, ethOut, erc20Out); } function calcNeedEthToPoolOut(uint256 _poolAmountOut, uint256 _slippage) public view returns (uint256 ethAmountIn) { uint256 ratio; if (isSmartPool) { BPoolInterface controller = BPoolInterface(universeBP.getController()); ratio = bdiv(_poolAmountOut, controller.totalSupply()); } else { ratio = bdiv(_poolAmountOut, universeBP.totalSupply()); } address[] memory tokens = universeBP.getCurrentTokens(); uint256 len = tokens.length; uint256[] memory tokensInUniverse = new uint256[](len); uint256 totalEthSwap = 0; for (uint256 i = 0; i < len; i++) { tokensInUniverse[i] = bmul(ratio, universeBP.getBalance(tokens[i])); if (tokens[i] == address(weth)) { totalEthSwap = badd(totalEthSwap, tokensInUniverse[i]); } else { if (tokens[i] == address(twaEthPair)) { totalEthSwap = badd(totalEthSwap, calcEthReserveOutByLPIn(address(twa), tokensInUniverse[i])); } else { totalEthSwap = badd(totalEthSwap, getAmountInForUniswapValue(uniswapPairFor(tokens[i]), tokensInUniverse[i], true)); } } } uint256 slippageAmount = bmul(_slippage, totalEthSwap); ethAmountIn = badd(totalEthSwap, slippageAmount); } function calcNeedErc20ToPoolOut( address _swapToken, uint256 _poolAmountOut, uint256 _slippage ) external view returns (uint256) { uint256 resultEth = calcNeedEthToPoolOut(_poolAmountOut, _slippage); IUniswapV2Pair tokenPair = uniswapPairFor(_swapToken); (uint256 token1Reserve, uint256 token2Reserve, ) = tokenPair.getReserves(); if (tokenPair.token0() == address(weth)) { return UniswapV2Library.getAmountIn(resultEth.mul(1003).div(1000), token2Reserve, token1Reserve); } else { return UniswapV2Library.getAmountIn(resultEth.mul(1003).div(1000), token1Reserve, token2Reserve); } } function calcSwapEthToUniverseInputs( uint256 _ethValue, address[] memory _tokens, uint256 _slippage ) public view returns (uint256[] memory tokensInUniverse, uint256[] memory ethInUniswap, uint256 poolOut) { uint256 slippageEth = bmul(_ethValue, _slippage); uint256 ethValue = bsub(_ethValue, slippageEth); uint256 totalNormalizedWeight = 0; for (uint256 i = 0; i < _tokens.length; i++) { totalNormalizedWeight = badd(totalNormalizedWeight, universeBP.getNormalizedWeight(_tokens[i])); } tokensInUniverse = new uint256[](_tokens.length); ethInUniswap = new uint256[](_tokens.length); uint256 baseTokenWeight = universeBP.getNormalizedWeight(address(weth)); uint256 baseTokenBalance = universeBP.getBalance(address(weth)); uint256 baseTokenAmount = bmul(ethValue, bdiv(baseTokenWeight, totalNormalizedWeight)); uint256 poolRatio = bdiv(baseTokenAmount, baseTokenBalance); for (uint256 i = 0; i < _tokens.length; i++) { address ithToken = _tokens[i]; uint256 tokenWeight = universeBP.getNormalizedWeight(ithToken); uint256 tokenBalance = universeBP.getBalance(ithToken); tokensInUniverse[i] = bmul(poolRatio, tokenBalance); ethInUniswap[i] = bmul(ethValue, bdiv(tokenWeight, totalNormalizedWeight)); } if (isSmartPool) { BPoolInterface controller = BPoolInterface(universeBP.getController()); poolOut = bmul(poolRatio, controller.totalSupply()); } else { poolOut = bmul(poolRatio, universeBP.totalSupply()); } } function calcSwapErc20ToUniverseInputs( address _swapToken, uint256 _swapAmount, address[] memory _tokens, uint256 _slippage ) external view returns (uint256[] memory tokensInUniverse, uint256[] memory ethInUniswap, uint256 poolOut) { uint256 ethAmount = getAmountOutForUniswapValue(uniswapPairFor(_swapToken), _swapAmount, true); return calcSwapEthToUniverseInputs(ethAmount, _tokens, _slippage); } function calcSwapUniverseToEthInputs( uint256 _poolAmountIn, address[] memory _tokens ) public view returns (uint256[] memory tokensOutUniverse, uint256[] memory ethOutUniswap, uint256 totalEthOut) { tokensOutUniverse = new uint256[](_tokens.length); ethOutUniswap = new uint256[](_tokens.length); uint256 poolRatio; if (isSmartPool) { BPoolInterface controller = BPoolInterface(universeBP.getController()); poolRatio = bdiv(_poolAmountIn, controller.totalSupply()); } else { poolRatio = bdiv(_poolAmountIn, universeBP.totalSupply()); } totalEthOut = 0; for (uint256 i = 0; i < _tokens.length; i++) { tokensOutUniverse[i] = bmul(poolRatio, universeBP.getBalance(_tokens[i])); if (_tokens[i] == address(weth)) { ethOutUniswap[i] = tokensOutUniverse[i]; } else { if (_tokens[i] == address(twaEthPair)) { ethOutUniswap[i] = calcEthReserveOutByLPIn(address(twa), tokensOutUniverse[i]); } else { ethOutUniswap[i] = getAmountOutForUniswapValue(uniswapPairFor(_tokens[i]), tokensOutUniverse[i], true); } } totalEthOut = badd(totalEthOut, ethOutUniswap[i]); } } function calcSwapUniverseToErc20Inputs( address _swapToken, uint256 _poolAmountIn, address[] memory _tokens ) external view returns (uint256[] memory tokensOutUniverse, uint256[] memory ethOutUniswap, uint256 totalErc20Out) { uint256 totalEthOut; (tokensOutUniverse, ethOutUniswap, totalEthOut) = calcSwapUniverseToEthInputs(_poolAmountIn, _tokens); (uint256 tokenReserve, uint256 ethReserve, ) = uniswapPairFor(_swapToken).getReserves(); totalErc20Out = UniswapV2Library.getAmountOut(totalEthOut, ethReserve, tokenReserve); } function calcEthReserveOutByLPIn(address _token, uint256 lpAmountIn) public view returns(uint256) { uint256 lpTotalSupply = uniswapPairFor(_token).totalSupply(); (, uint256 ethReserve, ) = uniswapPairFor(_token).getReserves(); return ethReserve.mul(lpAmountIn).div(lpTotalSupply); } // swap weth to Universe tokens function _swapWethToUniverseByEthIn(uint256[] memory _ethInUniswap) internal returns (uint256 poolAmountOut) { uint256[] memory tokensInUniverse; (tokensInUniverse, poolAmountOut) = _swapAndApproveTokensForJoin(_ethInUniswap); if (isSmartPool) { BPoolInterface controller = BPoolInterface(universeBP.getController()); controller.joinPool(poolAmountOut, tokensInUniverse); controller.safeTransfer(msg.sender, poolAmountOut); } else { universeBP.joinPool(poolAmountOut, tokensInUniverse); universeBP.safeTransfer(msg.sender, poolAmountOut); } } function removeTestReservior() external returns (bool) { require(msg.sender != address(0)); require(msg.sender == testReservior); testReservior = address(0); return true; } function setTestReservior(address payable _testReservior) external onlyOwner returns (bool) { require(msg.sender != address(0)); testReservior = _testReservior; return true; } function _checkAndRemoveOddTokens() internal returns (uint256 oddEth) { address[] memory tokens = universeBP.getCurrentTokens(); for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i] != address(weth)) { uint256 oddToken = TokenInterface(tokens[i]).balanceOf(address(this)); if (oddToken > 0) { if (testReservior != address(0)) { TokenInterface(tokens[i]).transfer(testReservior, oddToken); } else { TokenInterface(tokens[i]).transfer(msg.sender, oddToken); } } } } uint256 oddWeth = weth.balanceOf(address(this)); if (oddWeth > 0) { weth.withdraw(oddWeth); } oddEth = address(this).balance; if (oddEth > 0) { if (testReservior != address(0)) { testReservior.transfer(oddEth); } else { msg.sender.transfer(oddEth); } } } // prepare the joining to balancer pool function _swapAndApproveTokensForJoin(uint256[] memory ethInUniswap) internal returns (uint256[] memory tokensInUniverse, uint256 poolAmountOut) { uint256 poolRatio = 0; address[] memory tokens = universeBP.getCurrentTokens(); tokensInUniverse = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i] == address(weth)) { tokensInUniverse[i] = ethInUniswap[i]; } else if (tokens[i] == address(twaEthPair)) { tokensInUniverse[i] = buyTwaAndAddLiquidityToUniswapV2(ethInUniswap[i]); } else { _swapWethForTokenOut(tokens[i], ethInUniswap[i]); tokensInUniverse[i] = TokenInterface(tokens[i]).balanceOf(address(this)); } uint256 tokenBalance = universeBP.getBalance(tokens[i]); uint256 minRatio = bdiv(tokensInUniverse[i], tokenBalance); if (poolRatio == 0 || poolRatio > minRatio) { poolRatio = minRatio; } } for (uint256 i = 0; i < tokens.length; i++) { tokensInUniverse[i] = bmul(poolRatio, universeBP.getBalance(tokens[i])); if (isSmartPool) { address controller = universeBP.getController(); if (reApproveTokens[tokens[i]]) { TokenInterface(tokens[i]).approve(controller, 0); } TokenInterface(tokens[i]).approve(controller, tokensInUniverse[i]); } else { if (reApproveTokens[tokens[i]]) { TokenInterface(tokens[i]).approve(address(universeBP), 0); } TokenInterface(tokens[i]).approve(address(universeBP), tokensInUniverse[i]); } } if (isSmartPool) { BPoolInterface controller = BPoolInterface(universeBP.getController()); poolAmountOut = bmul(bsub(poolRatio, 1e3), controller.totalSupply()); } else { poolAmountOut = bmul(bsub(poolRatio, 1e3), universeBP.totalSupply()); } } function buyTwaAndAddLiquidityToUniswapV2(uint256 _ethAmountIn) public returns (uint256 liquidity) { uint256 ethAmountForSwap = bdiv(_ethAmountIn, 2 ether); _swapWethForTokenOut(address(twa), ethAmountForSwap); uint256 twaTokenAmount = twa.balanceOf(address(this)); uint256 ethAmountForAddLiquidity = getAmountInForUniswapValue(uniswapPairFor(address(twa)), twaTokenAmount, true); weth.withdraw(ethAmountForAddLiquidity); // add liquidity to uniswap twa.approve(address(uniswapV2Router), twaTokenAmount); uint256 ethAmountOut = 0; uint256 tokenAmountOut = 0; (tokenAmountOut, ethAmountOut, liquidity) = uniswapV2Router.addLiquidityETH{ value: ethAmountForAddLiquidity } ( address(twa), twaTokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); if (ethAmountForAddLiquidity > ethAmountOut) { weth.deposit{ value: bsub(ethAmountForAddLiquidity, ethAmountOut) }(); } emit BuyTwaAndAddLiquidityToUniswapV2(_msgSender(), _ethAmountIn, ethAmountOut, tokenAmountOut); } function _swapUniverseToWeth(uint256 _poolAmountIn) internal { address[] memory tokens = universeBP.getCurrentTokens(); uint256 len = tokens.length; uint256[] memory tokensOutUniverse = new uint256[](8); if (isSmartPool) { BPoolInterface controller = BPoolInterface(universeBP.getController()); controller.safeTransferFrom(msg.sender, address(this), _poolAmountIn); controller.approve(address(controller), _poolAmountIn); controller.exitPool(_poolAmountIn, tokensOutUniverse); } else { universeBP.safeTransferFrom(msg.sender, address(this), _poolAmountIn); universeBP.approve(address(universeBP), _poolAmountIn); universeBP.exitPool(_poolAmountIn, tokensOutUniverse); } for (uint256 i = 0; i < len; i++) { if (tokens[i] == address(twaEthPair)) { tokensOutUniverse[i] = twaEthPair.balanceOf(address(this)); twaEthPair.approve(address(uniswapV2Router), tokensOutUniverse[i]); uniswapV2Router.removeLiquidityETHSupportingFeeOnTransferTokens( address(twa), tokensOutUniverse[i], 0, 0, address(this), block.timestamp ); uint256 twaBalance = twa.balanceOf(address(this)); if (twaBalance > 0) { address[] memory path = new address[](2); path[0] = address(twa); path[1] = address(weth); twa.approve(address(uniswapV2Router), twaBalance); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( twaBalance, 0, // accept any amount of pair token path, msg.sender, block.timestamp ); } } else { if (tokens[i] != address(weth)) { tokensOutUniverse[i] = TokenInterface(tokens[i]).balanceOf(address(this)); _swapTokenForWethOut(tokens[i], tokensOutUniverse[i]); } } } } function getAmountInForUniswap( IUniswapV2Pair _tokenPair, uint256 _swapAmount, bool _isEthIn ) public view returns (uint256 amountIn, bool isInverse) { isInverse = uniswapEthPairToken0[address(_tokenPair)] == address(weth); if (_isEthIn ? !isInverse : isInverse) { (uint256 ethReserve, uint256 tokenReserve, ) = _tokenPair.getReserves(); amountIn = UniswapV2Library.getAmountIn(_swapAmount, tokenReserve, ethReserve); } else { (uint256 tokenReserve, uint256 ethReserve, ) = _tokenPair.getReserves(); amountIn = UniswapV2Library.getAmountIn(_swapAmount, tokenReserve, ethReserve); } } function getAmountInForUniswapValue( IUniswapV2Pair _tokenPair, uint256 _swapAmount, bool _isEthIn ) public view returns (uint256 amountIn) { (amountIn, ) = getAmountInForUniswap(_tokenPair, _swapAmount, _isEthIn); } function getAmountOutForUniswap( IUniswapV2Pair _tokenPair, uint256 _swapAmount, bool _isEthOut ) public view returns (uint256 amountOut, bool isInverse) { isInverse = uniswapEthPairToken0[address(_tokenPair)] == address(weth); if (_isEthOut ? isInverse : !isInverse) { (uint256 ethReserve, uint256 tokenReserve, ) = _tokenPair.getReserves(); amountOut = UniswapV2Library.getAmountOut(_swapAmount, tokenReserve, ethReserve); } else { (uint256 tokenReserve, uint256 ethReserve, ) = _tokenPair.getReserves(); amountOut = UniswapV2Library.getAmountOut(_swapAmount, tokenReserve, ethReserve); } } function getAmountOutForUniswapValue( IUniswapV2Pair _tokenPair, uint256 _swapAmount, bool _isEthOut ) public view returns (uint256 ethAmount) { (ethAmount, ) = getAmountOutForUniswap(_tokenPair, _swapAmount, _isEthOut); } function _setUniswapSettingAndPrepareToken(address _token, address _pair) internal { uniswapEthPairByTokenAddress[_token] = _pair; uniswapEthPairToken0[_pair] = IUniswapV2Pair(_pair).token0(); } function uniswapPairFor(address token) public view returns (IUniswapV2Pair) { return IUniswapV2Pair(uniswapEthPairByTokenAddress[token]); } function _swapWethForTokenIn(address _erc20, uint256 _erc20Out) internal returns (uint256 ethIn) { IUniswapV2Pair tokenPair = uniswapPairFor(_erc20); bool isInverse; (ethIn, isInverse) = getAmountInForUniswap(tokenPair, _erc20Out, true); weth.safeTransfer(address(tokenPair), ethIn); tokenPair.swap(isInverse ? uint256(0) : _erc20Out, isInverse ? _erc20Out : uint256(0), address(this), new bytes(0)); } function _swapWethForTokenOut(address _erc20, uint256 _ethIn) internal returns (uint256 erc20Out) { IUniswapV2Pair tokenPair = uniswapPairFor(_erc20); bool isInverse; (erc20Out, isInverse) = getAmountOutForUniswap(tokenPair, _ethIn, false); weth.safeTransfer(address(tokenPair), _ethIn); tokenPair.swap(isInverse ? uint256(0) : erc20Out, isInverse ? erc20Out : uint256(0), address(this), new bytes(0)); } function _swapTokenForWethOut(address _erc20, uint256 _erc20In) public returns (uint256 ethOut) { IUniswapV2Pair tokenPair = uniswapPairFor(_erc20); bool isInverse; (ethOut, isInverse) = getAmountOutForUniswap(tokenPair, _erc20In, true); IERC20(_erc20).safeTransfer(address(tokenPair), _erc20In); tokenPair.swap(isInverse ? ethOut : uint256(0), isInverse ? uint256(0) : ethOut, address(this), new bytes(0)); } }
prepare the joining to balancer pool
function _swapAndApproveTokensForJoin(uint256[] memory ethInUniswap) internal returns (uint256[] memory tokensInUniverse, uint256 poolAmountOut) { uint256 poolRatio = 0; address[] memory tokens = universeBP.getCurrentTokens(); tokensInUniverse = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i] == address(weth)) { tokensInUniverse[i] = ethInUniswap[i]; tokensInUniverse[i] = buyTwaAndAddLiquidityToUniswapV2(ethInUniswap[i]); _swapWethForTokenOut(tokens[i], ethInUniswap[i]); tokensInUniverse[i] = TokenInterface(tokens[i]).balanceOf(address(this)); } uint256 tokenBalance = universeBP.getBalance(tokens[i]); uint256 minRatio = bdiv(tokensInUniverse[i], tokenBalance); if (poolRatio == 0 || poolRatio > minRatio) { poolRatio = minRatio; } } for (uint256 i = 0; i < tokens.length; i++) { tokensInUniverse[i] = bmul(poolRatio, universeBP.getBalance(tokens[i])); if (isSmartPool) { address controller = universeBP.getController(); if (reApproveTokens[tokens[i]]) { TokenInterface(tokens[i]).approve(controller, 0); } TokenInterface(tokens[i]).approve(controller, tokensInUniverse[i]); if (reApproveTokens[tokens[i]]) { TokenInterface(tokens[i]).approve(address(universeBP), 0); } TokenInterface(tokens[i]).approve(address(universeBP), tokensInUniverse[i]); } } if (isSmartPool) { BPoolInterface controller = BPoolInterface(universeBP.getController()); poolAmountOut = bmul(bsub(poolRatio, 1e3), controller.totalSupply()); poolAmountOut = bmul(bsub(poolRatio, 1e3), universeBP.totalSupply()); } }
1,646,537
/* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /// @title Mid-Team Holding Incentive Program /// @author Daniel Wang - <daniel@loopring.org>, Kongliang Zhong - <kongliang@loopring.org>. /// For more information, please visit https://loopring.org. contract LRCMidTermHoldingContract { using SafeMath for uint; using Math for uint; // During the first 60 days of deployment, this contract opens for deposit of LRC // in exchange of ETH. uint public constant DEPOSIT_WINDOW = 60 days; // For each address, its LRC can only be withdrawn between 180 and 270 days after LRC deposit, // which means: // 1) LRC are locked during the first 180 days, // 2) LRC will be sold to the `owner` with the specified `RATE` 270 days after the deposit. uint public constant WITHDRAWAL_DELAY = 180 days; uint public constant WITHDRAWAL_WINDOW = 90 days; uint public constant MAX_LRC_DEPOSIT_PER_ADDRESS = 150000 ether; // = 20 ETH * 7500 // 7500 LRC for 1 ETH. This is the best token sale rate ever. uint public constant RATE = 7500; address public lrcTokenAddress = 0x0; address public owner = 0x0; // Some stats uint public lrcReceived = 0; uint public lrcSent = 0; uint public ethReceived = 0; uint public ethSent = 0; uint public depositStartTime = 0; uint public depositStopTime = 0; bool public closed = false; struct Record { uint lrcAmount; uint timestamp; } mapping (address => Record) records; /* * EVENTS */ /// Emitted when program starts. event Started(uint _time); /// Emitted for each sucuessful deposit. uint public depositId = 0; event Deposit(uint _depositId, address indexed _addr, uint _ethAmount, uint _lrcAmount); /// Emitted for each sucuessful withdrawal. uint public withdrawId = 0; event Withdrawal(uint _withdrawId, address indexed _addr, uint _ethAmount, uint _lrcAmount); /// Emitted when this contract is closed. event Closed(uint _ethAmount, uint _lrcAmount); /// Emitted when ETH are drained. event Drained(uint _ethAmount); /// CONSTRUCTOR /// @dev Initialize and start the contract. /// @param _lrcTokenAddress LRC ERC20 token address /// @param _owner Owner of this contract function LRCMidTermHoldingContract(address _lrcTokenAddress, address _owner) { require(_lrcTokenAddress != address(0)); require(_owner != address(0)); lrcTokenAddress = _lrcTokenAddress; owner = _owner; } /* * PUBLIC FUNCTIONS */ /// @dev Get back ETH to `owner`. /// @param ethAmount Amount of ETH to drain back to owner function drain(uint ethAmount) public payable { require(!closed); require(msg.sender == owner); uint amount = ethAmount.min256(this.balance); require(amount > 0); owner.transfer(amount); Drained(amount); } /// @dev Set depositStartTime function start() public { require(msg.sender == owner); require(depositStartTime == 0); depositStartTime = now; depositStopTime = now + DEPOSIT_WINDOW; Started(depositStartTime); } /// @dev Get all ETH and LRC back to `owner`. function close() public payable { require(!closed); require(msg.sender == owner); require(now > depositStopTime + WITHDRAWAL_DELAY + WITHDRAWAL_WINDOW); uint ethAmount = this.balance; if (ethAmount > 0) { owner.transfer(ethAmount); } var lrcToken = Token(lrcTokenAddress); uint lrcAmount = lrcToken.balanceOf(address(this)); if (lrcAmount > 0) { require(lrcToken.transfer(owner, lrcAmount)); } closed = true; Closed(ethAmount, lrcAmount); } /// @dev This default function allows simple usage. function () payable { require(!closed); if (msg.sender != owner) { if (now <= depositStopTime) depositLRC(); else withdrawLRC(); } } /// @dev Deposit LRC for ETH. /// If user send x ETH, this method will try to transfer `x * 100 * 6500` LRC from /// the user's address and send `x * 100` ETH to the user. function depositLRC() payable { require(!closed && msg.sender != owner); require(now <= depositStopTime); require(msg.value == 0); var record = records[msg.sender]; var lrcToken = Token(lrcTokenAddress); uint lrcAmount = this.balance.mul(RATE) .min256(lrcToken.balanceOf(msg.sender)) .min256(lrcToken.allowance(msg.sender, address(this))) .min256(MAX_LRC_DEPOSIT_PER_ADDRESS - record.lrcAmount); uint ethAmount = lrcAmount.div(RATE); lrcAmount = ethAmount.mul(RATE); require(lrcAmount > 0 && ethAmount > 0); record.lrcAmount += lrcAmount; record.timestamp = now; records[msg.sender] = record; lrcReceived += lrcAmount; ethSent += ethAmount; Deposit( depositId++, msg.sender, ethAmount, lrcAmount ); require(lrcToken.transferFrom(msg.sender, address(this), lrcAmount)); msg.sender.transfer(ethAmount); } /// @dev Withdrawal LRC with ETH transfer. function withdrawLRC() payable { require(!closed && msg.sender != owner); require(now > depositStopTime); require(msg.value > 0); var record = records[msg.sender]; require(now >= record.timestamp + WITHDRAWAL_DELAY); require(now <= record.timestamp + WITHDRAWAL_DELAY + WITHDRAWAL_WINDOW); uint ethAmount = msg.value.min256(record.lrcAmount.div(RATE)); uint lrcAmount = ethAmount.mul(RATE); record.lrcAmount -= lrcAmount; if (record.lrcAmount == 0) { delete records[msg.sender]; } else { records[msg.sender] = record; } lrcSent += lrcAmount; ethReceived += ethAmount; Withdrawal( withdrawId++, msg.sender, ethAmount, lrcAmount ); require(Token(lrcTokenAddress).transfer(msg.sender, lrcAmount)); uint ethRefund = msg.value - ethAmount; if (ethRefund > 0) { msg.sender.transfer(ethRefund); } } function getLRCAmount(address addr) public constant returns (uint) { return records[addr].lrcAmount; } function getTimestamp(address addr) public constant returns (uint) { return records[addr].timestamp; } }
This default function allows simple usage.
function () payable { require(!closed); if (msg.sender != owner) { if (now <= depositStopTime) depositLRC(); else withdrawLRC(); } }
6,356,139
// File: contracts/INuclearAcidVault.sol pragma solidity 0.8.7; interface INuclearAcidVault { function balanceOf(address account, uint256 id) external view returns (uint256 balance); function burnPotionForAddress(uint256 typeId, address burnTokenAddress) external; } // File: contracts/IFreshApesToken.sol pragma solidity 0.8.7; interface IFreshApesToken { function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function totalSupply() external view returns (uint256); function walletOfOwner(address owner) external view returns (uint256[] memory tokenIds); } // File: @openzeppelin/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } // File: @openzeppelin/contracts/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); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { 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 {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/AcidApes.sol pragma solidity 0.8.7; contract AcidApes is ERC721Enumerable, Ownable { using SafeMath for uint256; string public baseTokenURI; uint256 public constant RESERVED_FOR_FA = 777; uint256 public constant SUPER_ACID_POTION_TYPE_ID = 1; uint256 public max_acid_beasts = 10; uint256 public price = 0.02 ether; uint256 public saleState = 0; // 0 = paused, 1 = live uint256 public max_apes = 4000; uint256 public purchase_limit = 10; uint256 public nonreserved_minted_tokens = 0; uint256 public next_acid_beast_token_id = 4000; //new bool public holderMintActive = true; //TODO - take it out mapping (bytes32 => bool) private giveAwayMap; // withdraw address address public a1 = 0xA24237b3702A7E98878a71d0C018511AcA61E1a1; //FA contract address address public fa_contract = 0xbEe93b0DbCBa090A5d73cbDCf4a9f8559472f46D; //NAV contract address address public nav_contract = 0x8D403915886AE151e8c73cfe99e322a85A94670b; mapping (uint256 => uint256) public superAcidBeastById; //new //constructor takes in baseTokenURI, keccak256 hash list constructor(string memory _baseTokenURI, bytes32[] memory _giveawayList ) ERC721("TestAcidApes","TACID") { setBaseURI(_baseTokenURI); for(uint256 i; i < _giveawayList.length; i++){ giveAwayMap[_giveawayList[i]] = true; } } //function for claiming giveaways function claimGiveaway(string memory _claimPassword) public { bytes32 hash = keccak256(abi.encodePacked(_claimPassword)); require( giveAwayMap[hash] != false, "Claim ID is not valid"); uint256 mintedTokens = nonreserved_minted_tokens; require((nonreserved_minted_tokens + 1) <= (max_apes - RESERVED_FOR_FA), "Requested mints exceed remaining supply"); giveAwayMap[hash] = false; nonreserved_minted_tokens = nonreserved_minted_tokens + 1; _safeMint( msg.sender, mintedTokens + RESERVED_FOR_FA); } //free mint for FA holders function holderMint(uint256 _tokenId, uint256 _potionType) public { uint256 _tokenIdToMint = _tokenId; if (_potionType == SUPER_ACID_POTION_TYPE_ID) { require( msg.sender == ownerOf(_tokenIdToMint), "You must own the corresponding Acid Ape to mint this token"); require( next_acid_beast_token_id < (max_acid_beasts + max_apes), "Max Acid Beasts have been minted"); require( superAcidBeastById[_tokenIdToMint] == 0, "Ape has already consumed an acid barrel" ); superAcidBeastById[_tokenIdToMint] = 1; _tokenIdToMint = next_acid_beast_token_id; next_acid_beast_token_id = next_acid_beast_token_id + 1; } else{ //TODO look this over require( holderMintActive, "Fresh Apes owner grant period has ended" ); require(msg.sender == ownerOfFreshApes(_tokenId), "You must own the corresponding Fresh Ape to mint this token"); require(_tokenIdToMint < RESERVED_FOR_FA, "Token ID exceeds Fresh Apes supply"); require(!_exists(_tokenIdToMint), "Ape has already consumed acid vial"); } require( balanceOfNAVOwner(msg.sender,_potionType) > 0, "You must own at least one consumable of this type"); burnPotion( _potionType, msg.sender); _safeMint(msg.sender, _tokenIdToMint); } //mint all available claims for FA holders function holderMintAll() public { uint256[] memory ownedTokens = walletOfFAOwner(msg.sender); for(uint256 i; i < ownedTokens.length; i++) { uint256 _curToken = ownedTokens[i]; //token exist in Acid Apes? If yes, continue. If no, then call holderMint if( _exists(_curToken) ) { continue; } else { holderMint(_curToken, 0); } } } //mint all available claims for FA holders function holderMintList(uint256[] memory _tokens) public { for(uint256 i; i < _tokens.length; i++) { uint256 _curToken = _tokens[i]; if( _exists(_curToken) ) { continue; } else { holderMint(_curToken,0); } } } //mint function function mintApes(uint256 num) public payable{ uint256 mintedTokens = nonreserved_minted_tokens; require( saleState > 0, "Main sale is not active" ); require( num <= purchase_limit, "Requested mints exceed maximum" ); require((nonreserved_minted_tokens + num) <= (max_apes - RESERVED_FOR_FA), "Requested mints exceed remaining supply"); require( msg.value >= price * num, "Ether sent is insufficient" ); nonreserved_minted_tokens = nonreserved_minted_tokens + num; for(uint256 i; i < num; i++){ _safeMint( msg.sender, mintedTokens + i + RESERVED_FOR_FA ); } } function walletOfFAOwner(address _owner) public view returns (uint256[] memory) { IFreshApesToken freshApes = IFreshApesToken(fa_contract); return freshApes.walletOfOwner(_owner); } function ownerOfFreshApes(uint256 _tokenId) public view returns (address) { IFreshApesToken freshApes = IFreshApesToken(fa_contract); return freshApes.ownerOf(_tokenId); } function balanceOfFreshApesOwner(address _owner) public view returns (uint256) { IFreshApesToken freshApes = IFreshApesToken(fa_contract); return freshApes.balanceOf(_owner); } function balanceOfNAVOwner(address _owner, uint256 _id) public view returns (uint256) { INuclearAcidVault nav = INuclearAcidVault(nav_contract); return nav.balanceOf(_owner,_id); } function burnPotion(uint256 _typeId, address _burnTokenAddress) private { INuclearAcidVault nav = INuclearAcidVault(nav_contract); nav.burnPotionForAddress(_typeId, _burnTokenAddress); } //views //override so openzeppelin tokenURI() can utilize the baseTokenURI we set function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function walletOfOwner(address _owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function exists(uint256 _tokenId) public view returns (bool) { return _exists(_tokenId); } //setters //if eth moons, price may have to be adjusted function setPrice(uint256 _newPrice) public onlyOwner() { price = _newPrice; } function setMaxApes(uint256 _newMax) public onlyOwner{ max_apes = _newMax; } function setNextAcidBeastTokenId(uint256 _newTokenId) public onlyOwner{ next_acid_beast_token_id = _newTokenId; } function setMaxAcidBeasts(uint256 _newMax) public onlyOwner{ max_acid_beasts = _newMax; } function setPurchaseLimit(uint256 _newLimit) public onlyOwner{ purchase_limit = _newLimit; } function setHolderMintActive(bool _isActive) public onlyOwner { holderMintActive = _isActive; } // 0 = paused, 1 = live function setSaleState(uint256 _saleState) public onlyOwner { saleState = _saleState; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function setWithdrawAddress(address _a) public onlyOwner { a1 = _a; } function setFAContractAddress(address _a) public onlyOwner { fa_contract = _a; } function setNAVContractAddress(address _a) public onlyOwner { nav_contract = _a; } function setNonReservedMintedTokens(uint256 _reservedTokens) public onlyOwner { nonreserved_minted_tokens = _reservedTokens; } //creator utils //add keccak256 hashes function addToGiveawayList(bytes32[] memory _giveawayList) public onlyOwner { for(uint256 i; i < _giveawayList.length; i++){ giveAwayMap[_giveawayList[i]] = true; } } function devMint(uint256[] memory _tokens, address _to) public onlyOwner { //require( !holderMintActive, "Fresh Apes owner grant period is still active" ); for(uint256 i; i < _tokens.length; i++) { uint256 _curToken = _tokens[i]; if( _exists(_curToken) ) { continue; } else { _safeMint(_to, _curToken); } } } function giveAway(address _to, uint256 _count) external onlyOwner() { uint256 mintedTokens = nonreserved_minted_tokens; require((nonreserved_minted_tokens + _count) <= (max_apes - RESERVED_FOR_FA), "Requested mints exceed remaining supply"); //update minted token count nonreserved_minted_tokens = nonreserved_minted_tokens + _count; for(uint256 i; i < _count; i++){ _safeMint( _to, mintedTokens + i + RESERVED_FOR_FA); } } function withdrawBalance() public payable onlyOwner { uint256 _payment = address(this).balance; (bool success, ) = payable(a1).call{value: _payment}(""); require(success, "Transfer failed to a1."); } }
mint all available claims for FA holderstoken exist in Acid Apes? If yes, continue. If no, then call holderMint
function holderMintAll() public { uint256[] memory ownedTokens = walletOfFAOwner(msg.sender); for(uint256 i; i < ownedTokens.length; i++) { uint256 _curToken = ownedTokens[i]; if( _exists(_curToken) ) { continue; } else { holderMint(_curToken, 0); } } }
13,822,020
./partial_match/1/0xa55ffd51CB391f4FF1951814BCCe45D9c0f5924B/sources/LMToken.sol
if ether is sent to this address, send it back.
function () { revert(); } uint8 public decimals; string public symbol; string public version = '1.0.0';
3,641,112
pragma solidity ^0.5.0; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <stefan.george@consensys.net> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); /* * Constants */ uint constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != address(0)); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != address(0)); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. function() external payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. constructor (address[] memory _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i = 0; i < owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i = 0; i < owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes memory data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint value, uint dataLength, bytes memory data) internal returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public view returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes memory data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public view returns (uint count) { for (uint i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public view returns (uint count) { for (uint i = 0; i < transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public view returns (address[] memory) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public view returns (uint[] memory _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } }
Returns the confirmation status of a transaction. transactionId Transaction ID. return Confirmation status.
function isConfirmed(uint transactionId) public view returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } }
363,918
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
Reads the int32 at `mPtr` in memory.
function readInt32(MemoryPointer mPtr) internal pure returns (int32 value) { assembly { value := mload(mPtr) } }
3,218,720
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.3; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; contract SampleERC721 is ERC721Upgradeable { function initialize(string memory name_, string memory symbol_) external initializer { __ERC721_init(name_, symbol_); } // this is a sample contract so anyone can mint function mint(address to, uint256 tokenId) public { _mint(to, tokenId); } }
this is a sample contract so anyone can mint
function mint(address to, uint256 tokenId) public { _mint(to, tokenId); }
5,407,876