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/44787/0xBDDA3887dd89CAeac73c5AfbcD7af0793F55B715/sources/contracts/StarFarm.sol
require (_pid != 0, 'withdraw STAR by unstaking');if (_pid == 0) require(userNFTs[_msgSender()].length == 0, "nft user");
function testdeposit(uint256 _pid, uint256 _amount) public returns(uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; updatePool(_pid); (uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(); uint256 _useramount = user.amount.sub(user.nftAmount); uint256 _amountGain = _useramount.add(_useramount.mul(_selfGain).div(100)); if (_amountGain > 0) { uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt).sub(user.rewardDebt); if(pending > 0) { if (user.lastDeposit > block.timestamp.sub(604800)) { pending = pending.mul(90).div(100); starToken.safeTransfer(bonusAddr, pending.mul(10).div(100)); } starToken.safeTransfer(_msgSender(), pending); starNode.settleNode(_msgSender(), user.amount); } } }
13,279,631
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; contract ProjectRegister{ mapping (address => bool) public whitelist; mapping(bytes32 => election) public projectsRegistered; uint public whitelistedCount; uint public threshold; address public admin; struct Voter { uint weight; // weight is accumulated by delegation bool voted; // if true, that person already voted address delegate; // person delegated to bool initialized; // if initialized and weight assigned bool decision; } struct election{ uint approved; uint rejected; address proposer; bool finalized; bool decision; mapping (address => Voter) voters; } event Register( address indexed from, bytes32 projectHash ); event ProjectEvaluation( bytes32 indexed projectHash, bool isApproved ); event Vote( bytes32 indexed project, address from, bool decision, uint weight ); event VoteDelegate( address from, address to, bytes32 project, uint weight ); event WhitelistInsert( address indexed user ); event WhitelistRemove( address indexed user ); event AdminChange( address from, address to ); constructor(uint _threshold){ admin = msg.sender; threshold = _threshold; } modifier onlyAdmin { require(admin == msg.sender, "Only admin"); _; } modifier weightGiven(address voter, bytes32 fileHash){ if(!projectsRegistered[fileHash].voters[voter].initialized){ projectsRegistered[fileHash].voters[voter].weight = 1; projectsRegistered[fileHash].voters[voter].initialized = true; } _; } modifier onlyWhiteListed { require(whitelist[msg.sender], "User is not in whitelist"); _; } modifier projectExists(bytes32 fileHash) { require(projectsRegistered[fileHash].proposer != address(0), "Project does not exist"); _; } modifier notVoted(bytes32 fileHash) { require(!projectsRegistered[fileHash].voters[msg.sender].voted, "User already voted"); _; } function addToWhiteList(address addrToAdd) public onlyAdmin{ require(!whitelist[addrToAdd], "Address already in whitelist."); whitelist[addrToAdd] = true; whitelistedCount +=1; emit WhitelistInsert(addrToAdd); } function removeFromWhiteList(address addrToRemove) public onlyAdmin{ require(whitelist[addrToRemove], "remove address not in whitelist."); whitelist[addrToRemove] = false; whitelistedCount -=1; emit WhitelistRemove(addrToRemove); } function changeAdmin(address addr) public onlyAdmin{ require(addr != address(0), "address field zero address"); admin = addr; emit AdminChange(msg.sender, addr); } function registerProject(bytes32 fileHash) public{ require(projectsRegistered[fileHash].proposer == address(0), "Project Already Exists!!!"); projectsRegistered[fileHash].proposer = msg.sender; emit Register(msg.sender, fileHash); } /// @notice Explain to an end user what this does /// @dev Explain to a developer any extra details /// @param fileHash a parameter just like in doxygen (must be followed by parameter name)= function voteProposal(bytes32 fileHash, bool decision) public onlyWhiteListed projectExists(fileHash) notVoted(fileHash) weightGiven(msg.sender, fileHash){ require(!projectsRegistered[fileHash].finalized, "This proposal already come to a decision."); uint weight = projectsRegistered[fileHash].voters[msg.sender].weight; projectsRegistered[fileHash].voters[msg.sender].weight = 0; projectsRegistered[fileHash].voters[msg.sender].voted = true; projectsRegistered[fileHash].voters[msg.sender].decision = decision; if (decision){ projectsRegistered[fileHash].approved += weight; }else{ projectsRegistered[fileHash].rejected += weight; } emit Vote(fileHash, msg.sender, decision, weight); if(projectsRegistered[fileHash].approved > whitelistedCount*threshold/100 || projectsRegistered[fileHash].rejected > whitelistedCount*threshold/100){ evaluatePendingProjectStatus(fileHash); } } function evaluatePendingProjectStatus(bytes32 fileHash) private{ //console.log("Approve count: %s, Reject count: %s", projectsRegistered[fileHash].approved, projectsRegistered[fileHash].rejected); if (projectsRegistered[fileHash].approved > projectsRegistered[fileHash].rejected) { projectsRegistered[fileHash].decision = true; } projectsRegistered[fileHash].finalized = true; emit ProjectEvaluation(fileHash, projectsRegistered[fileHash].decision); } /** * @dev Delegate your vote to the voter 'to'. * @param to address to which vote is delegated */ function delegate(address to, bytes32 fileHash) public onlyWhiteListed notVoted(fileHash) weightGiven(msg.sender, fileHash) weightGiven(to, fileHash){ Voter storage sender = projectsRegistered[fileHash].voters[msg.sender]; require(to != msg.sender, "Self-delegation is disallowed."); while (projectsRegistered[fileHash].voters[to].delegate != address(0)) { to = projectsRegistered[fileHash].voters[to].delegate; // We found a loop in the delegation, not allowed. require(to != msg.sender, "Found loop in delegation."); } sender.voted = true; sender.delegate = to; Voter storage delegate_ = projectsRegistered[fileHash].voters[to]; if (delegate_.voted) { // If the delegate already voted, // directly add to the number of votes delegate_.decision ? (projectsRegistered[fileHash].approved += sender.weight) : (projectsRegistered[fileHash].rejected += sender.weight); } else { // If the delegate did not vote yet, // add to her weight. delegate_.weight += sender.weight; } emit VoteDelegate(msg.sender, to, fileHash, sender.weight); if(projectsRegistered[fileHash].approved > whitelistedCount*threshold/100 || projectsRegistered[fileHash].rejected > whitelistedCount*threshold/100){ evaluatePendingProjectStatus(fileHash); } } function isValidToDistribute(address addr, bytes32 fileHash) external view returns(bool){ require(projectsRegistered[fileHash].proposer == addr, "Proposer address does not match!"); require(projectsRegistered[fileHash].finalized, "Project voting hasnt finished"); require(projectsRegistered[fileHash].decision, "Project rejected"); return true; } }
console.log("Approve count: %s, Reject count: %s", projectsRegistered[fileHash].approved, projectsRegistered[fileHash].rejected);
function evaluatePendingProjectStatus(bytes32 fileHash) private{ if (projectsRegistered[fileHash].approved > projectsRegistered[fileHash].rejected) { projectsRegistered[fileHash].decision = true; } projectsRegistered[fileHash].finalized = true; emit ProjectEvaluation(fileHash, projectsRegistered[fileHash].decision); }
5,461,891
./partial_match/4/0xd2074450711Ab029d57D16bae1158534B01aa935/sources/Fortuna.sol
uint previousBalances = balanceOf[_from] + balanceOf[_to]; cback assert(balanceOf[_from] + balanceOf[_to] == previousBalances); cback
function _cleantransfer(address _from, address _to, uint _value) internal { require(_to != address(0x0)); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); }
8,506,835
./partial_match/4/0xA916bB3Dd5F48561bB4A25eaA5e072a6ce1B6d45/sources/SmolMuseum.sol
Returns the applicable booster of a user, for a pool, from a staked NFT set./
function getBoosterForUser(address _addr, uint256 _pid) public view returns (uint256) { return userPoolBoosts[_addr][_pid].div(1e5); }
8,641,720
./partial_match/137/0x66768ad00746aC4d68ded9f64886d55d5243f5Ec/sources/REBALANCE.sol
Medium _tTaxTierMediumFee
function setTaxTierMediumFee(uint256 tTaxAmount) external onlyOwner() { require(tTaxAmount > 0, "Tax medium amount must be greater than 0"); _tTaxTierMediumFee = tTaxAmount; }
3,514,295
// SPDX-License-Identifier: MIT pragma solidity >=0.5.17 <0.9.0; import "@unlock-protocol/contracts/dist/PublicLock/IPublicLockV10.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Base64.sol"; import "hardhat/console.sol"; import "./Layer.sol"; import { BokkyPooBahsDateTimeLibrary } from "./BokkyPooBahsDateTimeLibrary.sol"; /** * @notice Functions to be implemented by a tokenURIHook. * @dev Lock hooks are configured on the lock contract by calling `setEventHooks` on the lock. */ contract Hook { address public _avatarLock; address public _buntaiLock; address public _gundanLock; address public _mappingContract; string public _ipfsHash; /** * The hook is initialized with each lock contract as well as each layer contract */ constructor( address avatarLock, address buntaiLock, address gundanLock, address mappingContract, string memory ipfsHash ) { _avatarLock = avatarLock; _buntaiLock = buntaiLock; _gundanLock = gundanLock; _mappingContract = mappingContract; _ipfsHash = ipfsHash; } /** * Not altering the price by default */ function keyPurchasePrice( address, /* from */ address, /* recipient */ address, /* referrer */ bytes calldata /* data */ ) external view returns (uint256 minKeyPrice) { // TODO Let's look at the list? return IPublicLock(msg.sender).keyPrice(); } /** * When a new key is purchased, we need to grant a weapon * Challenge: we */ function onKeyPurchase( address, /*from*/ address recipient, address, /*referrer*/ bytes calldata, /*data*/ uint256, /*minKeyPrice*/ uint256 /*pricePaid*/ ) external { if (msg.sender == _avatarLock) { // If the sender is the avatar lock IPublicLock avatar = IPublicLock(_avatarLock); uint id = avatar.totalSupply(); address[] memory recipients = new address[](1); recipients[0] = recipient; uint[] memory expirations = new uint[](1); expirations[0] = type(uint256).max; // Not expiring! address[] memory managers = new address[](1); managers[0] = recipient; if (id % 2 == 0) { IPublicLock(_buntaiLock).grantKeys(recipients, expirations, managers); } else { IPublicLock(_gundanLock).grantKeys(recipients, expirations, managers); } } } // see https://github.com/unlock-protocol/unlock/blob/master/smart-contracts/contracts/interfaces/hooks/IHook.sol function tokenURI( address, // lockAddress, address, // operator, // We could alter the rendering based on _who_ is viewing! address, // owner, uint256, // keyId, uint256 //expirationTimestamp // a cool trick could be to render based on how far the expiration of the key is! ) external view returns (string memory) { // uint timeOfDay = 0; // string memory kind = ""; string memory image = "QmYkkshevBxHg7XwdP1pw6A4T82xzD8G2RpLDFo6KDy3zm"; // (, , , uint hour, , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(block.timestamp); // if (hour <= 8) { // timeOfDay = 0; // 0 => night // } else if (hour <= 17) { // timeOfDay = 1; // 1 => day // } else if (hour <= 21) { // timeOfDay = 2; // 2 => sunset // } else { // timeOfDay = 0; // 0 => night // } // // If the calling contract is the avatar contract // if (lockAddress == _avatarLock) { // kind = "avatars"; // uint weapon = 0; // // Check if there is a mapping! // if (avatarsWeapons[keyId] > 0) { // // If there is one, let's check the owner and make sure it's the correct one // IPublicLock weaponLock = IPublicLock(_weaponLock); // // TODO change me in v10! // uint weaponExpiration = weaponLock.keyExpirationTimestampFor(owner); // address weaponOwner = weaponLock.ownerOf(keyId); // if (weaponExpiration > block.timestamp && weaponOwner == owner) { // weapon = avatarsWeapons[keyId]; // } // } // image = string( // abi.encodePacked( // _ipfsHash, // "/", // kind, // "/", // Strings.toString(keyId), // "-", // Strings.toString(weapon), // "-", // Strings.toString(timeOfDay) // ) // ); // } // else if (lockAddress == _weaponLock) { // kind = "weapons"; // image = string( // abi.encodePacked( // _ipfsHash, // "/", // kind, // "/", // Strings.toString(keyId) // ) // ); // } // create the json that includes the image // We need to include more properties! string memory json = string( abi.encodePacked('{"image":"', image, '"}') ); // render the base64 encoded json metadata return string( abi.encodePacked( "data:application/json;base64,", Base64.encode(bytes(abi.encodePacked(json))) ) ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.17 <0.9.0; pragma experimental ABIEncoderV2; /** * @title The PublicLock Interface * @author Nick Furfaro (unlock-protocol.com) */ interface IPublicLock { // See indentationissue description here: // https://github.com/duaraghav8/Ethlint/issues/268 // solium-disable indentation /// Functions function initialize( address _lockCreator, uint _expirationDuration, address _tokenAddress, uint _keyPrice, uint _maxNumberOfKeys, string calldata _lockName ) external; /** * @notice Allow the contract to accept tips in ETH sent directly to the contract. * @dev This is okay to use even if the lock is priced in ERC-20 tokens */ // receive() external payable; // roles function DEFAULT_ADMIN_ROLE() external pure returns (bytes32); function KEY_GRANTER_ROLE() external pure returns (bytes32); function LOCK_MANAGER_ROLE() external pure returns (bytes32); /** * @notice The version number of the current implementation on this network. * @return The current version number. */ function publicLockVersion() external pure returns (uint16); /** * @dev Called by a lock manager or beneficiary to withdraw all funds from the lock and send them to the `beneficiary`. * @dev Throws if called by other than a lock manager or beneficiary * @param _tokenAddress specifies the token address to withdraw or 0 for ETH. This is usually * the same as `tokenAddress` in MixinFunds. * @param _amount specifies the max amount to withdraw, which may be reduced when * considering the available balance. Set to 0 or MAX_UINT to withdraw everything. * -- however be wary of draining funds as it breaks the `cancelAndRefund` and `expireAndRefundFor` * use cases. */ function withdraw( address _tokenAddress, uint _amount ) external; /** * @notice An ERC-20 style approval, allowing the spender to transfer funds directly from this lock. */ function approveBeneficiary( address _spender, uint _amount ) external returns (bool); /** * A function which lets a Lock manager of the lock to change the price for future purchases. * @dev Throws if called by other than a Lock manager * @dev Throws if lock has been disabled * @dev Throws if _tokenAddress is not a valid token * @param _keyPrice The new price to set for keys * @param _tokenAddress The address of the erc20 token to use for pricing the keys, * or 0 to use ETH */ function updateKeyPricing( uint _keyPrice, address _tokenAddress ) external; /** * A function to change the default duration of each key in the lock * @notice keys previously bought are unaffected by this change (i.e. * existing keys timestamps are not recalculated/updated) * @param _newExpirationDuration the new amount of time for each key purchased * or type(uint).max for a non-expiring key */ function setExpirationDuration(uint _newExpirationDuration) external; /** * A function which lets a Lock manager update the beneficiary account, * which receives funds on withdrawal. * @dev Throws if called by other than a Lock manager or beneficiary * @dev Throws if _beneficiary is address(0) * @param _beneficiary The new address to set as the beneficiary */ function updateBeneficiary( address _beneficiary ) external; /** * Checks if the user has a non-expired key. * @param _user The address of the key owner */ function getHasValidKey( address _user ) external view returns (bool); /** * @dev Returns the key's ExpirationTimestamp field for a given owner. * @param _tokenId the id of the key * @dev Returns 0 if the owner has never owned a key for this lock */ function keyExpirationTimestampFor( uint _tokenId ) external view returns (uint timestamp); /** * Public function which returns the total number of unique owners (both expired * and valid). This may be larger than totalSupply. */ function numberOfOwners() external view returns (uint); /** * Allows a Lock manager to assign a descriptive name for this Lock. * @param _lockName The new name for the lock * @dev Throws if called by other than a Lock manager */ function updateLockName( string calldata _lockName ) external; /** * Allows a Lock manager to assign a Symbol for this Lock. * @param _lockSymbol The new Symbol for the lock * @dev Throws if called by other than a Lock manager */ function updateLockSymbol( string calldata _lockSymbol ) external; /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory); /** * Allows a Lock manager to update the baseTokenURI for this Lock. * @dev Throws if called by other than a Lock manager * @param _baseTokenURI String representing the base of the URI for this lock. */ function setBaseTokenURI( string calldata _baseTokenURI ) external; /** @notice A distinct Uniform Resource Identifier (URI) for a given asset. * @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC * 3986. The URI may point to a JSON file that conforms to the "ERC721 * Metadata JSON Schema". * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * @param _tokenId The tokenID we're inquiring about * @return String representing the URI for the requested token */ function tokenURI( uint256 _tokenId ) external view returns(string memory); /** * @notice Allows a Lock manager to add or remove an event hook */ function setEventHooks( address _onKeyPurchaseHook, address _onKeyCancelHook, address _onValidKeyHook, address _onTokenURIHook ) external; /** * Allows a Lock manager to give a collection of users a key with no charge. * Each key may be assigned a different expiration date. * @dev Throws if called by other than a Lock manager * @param _recipients An array of receiving addresses * @param _expirationTimestamps An array of expiration Timestamps for the keys being granted */ function grantKeys( address[] calldata _recipients, uint[] calldata _expirationTimestamps, address[] calldata _keyManagers ) external; /** * @dev Purchase function * @param _values array of tokens amount to pay for this purchase >= the current keyPrice - any applicable discount * (_values is ignored when using ETH) * @param _recipients array of addresses of the recipients of the purchased key * @param _referrers array of addresses of the users making the referral * @param _keyManagers optional array of addresses to grant managing rights to a specific address on creation * @param _data array of arbitrary data populated by the front-end which initiated the sale * @notice when called for an existing and non-expired key, the `_keyManager` param will be ignored * @dev Setting _value to keyPrice exactly doubles as a security feature. That way if the lock owner increases the * price while my transaction is pending I can't be charged more than I expected (only applicable to ERC-20 when more * than keyPrice is approved for spending). */ function purchase( uint256[] calldata _values, address[] calldata _recipients, address[] calldata _referrers, address[] calldata _keyManagers, bytes[] calldata _data ) external payable; /** * @dev Extend function * @param _value the number of tokens to pay for this purchase >= the current keyPrice - any applicable discount * (_value is ignored when using ETH) * @param _tokenId the id of the key to extend * @param _referrer address of the user making the referral * @param _data arbitrary data populated by the front-end which initiated the sale * @dev Throws if lock is disabled or key does not exist for _recipient. Throws if _recipient == address(0). */ function extend( uint _value, uint _tokenId, address _referrer, bytes calldata _data ) external payable; /** * Merge existing keys * @param _tokenIdFrom the id of the token to substract time from * @param _tokenIdTo the id of the destination token to add time * @param _amount the amount of time to transfer (in seconds) */ function mergeKeys(uint _tokenIdFrom, uint _tokenIdTo, uint _amount) external; /** * Deactivate an existing key * @param _tokenId the id of token to burn * @notice the key will be expired and ownership records will be destroyed */ function burn(uint _tokenId) external; /** * @param _gasRefundValue price in wei or token in smallest price unit * @dev Set the value to be refunded to the sender on purchase */ function setGasRefundValue(uint256 _gasRefundValue) external; /** * _gasRefundValue price in wei or token in smallest price unit * @dev Returns the value/rpice to be refunded to the sender on purchase */ function gasRefundValue() external view returns (uint256 _gasRefundValue); /** * @notice returns the minimum price paid for a purchase with these params. * @dev this considers any discount from Unlock or the OnKeyPurchase hook. */ function purchasePriceFor( address _recipient, address _referrer, bytes calldata _data ) external view returns (uint); /** * Allow a Lock manager to change the transfer fee. * @dev Throws if called by other than a Lock manager * @param _transferFeeBasisPoints The new transfer fee in basis-points(bps). * Ex: 200 bps = 2% */ function updateTransferFee( uint _transferFeeBasisPoints ) external; /** * Determines how much of a fee would need to be paid in order to * transfer to another account. This is pro-rated so the fee goes * down overtime. * @dev Throws if _tokenId does not have a valid key * @param _tokenId The id of the key check the transfer fee for. * @param _time The amount of time to calculate the fee for. * @return The transfer fee in seconds. */ function getTransferFee( uint _tokenId, uint _time ) external view returns (uint); /** * @dev Invoked by a Lock manager to expire the user's key * and perform a refund and cancellation of the key * @param _tokenId The key id we wish to refund to * @param _amount The amount to refund to the key-owner * @dev Throws if called by other than a Lock manager * @dev Throws if _keyOwner does not have a valid key */ function expireAndRefundFor( uint _tokenId, uint _amount ) external; /** * @dev allows the key manager to expire a given tokenId * and send a refund to the keyOwner based on the amount of time remaining. * @param _tokenId The id of the key to cancel. */ function cancelAndRefund(uint _tokenId) external; /** * Allow a Lock manager to change the refund penalty. * @dev Throws if called by other than a Lock manager * @param _freeTrialLength The new duration of free trials for this lock * @param _refundPenaltyBasisPoints The new refund penaly in basis-points(bps) */ function updateRefundPenalty( uint _freeTrialLength, uint _refundPenaltyBasisPoints ) external; /** * @dev Determines how much of a refund a key owner would receive if they issued * @param _keyOwner The key owner to get the refund value for. * a cancelAndRefund block.timestamp. * Note that due to the time required to mine a tx, the actual refund amount will be lower * than what the user reads from this call. */ function getCancelAndRefundValue( address _keyOwner ) external view returns (uint refund); function addKeyGranter(address account) external; function addLockManager(address account) external; function isKeyGranter(address account) external view returns (bool); function isLockManager(address account) external view returns (bool); function onKeyPurchaseHook() external view returns(address); function onKeyCancelHook() external view returns(address); function onValidKeyHook() external view returns(bool); function onTokenURIHook() external view returns(string memory); function revokeKeyGranter(address _granter) external; function renounceLockManager() external; /** * @dev Change the maximum number of keys the lock can edit * @param _maxNumberOfKeys uint the maximum number of keys */ function setMaxNumberOfKeys (uint _maxNumberOfKeys) external; /** * Set the maximum number of keys a specific address can use * @param _maxKeysPerAddress the maximum amount of key a user can own */ function setMaxKeysPerAddress (uint _maxKeysPerAddress) external; /** * @return the maximum number of key allowed for a single address */ function maxKeysPerAddress() external view returns (uint); ///=================================================================== /// Auto-generated getter functions from public state variables function beneficiary() external view returns (address ); function expirationDuration() external view returns (uint256 ); function freeTrialLength() external view returns (uint256 ); function keyPrice() external view returns (uint256 ); function maxNumberOfKeys() external view returns (uint256 ); function refundPenaltyBasisPoints() external view returns (uint256 ); function tokenAddress() external view returns (address ); function transferFeeBasisPoints() external view returns (uint256 ); function unlockProtocol() external view returns (address ); function keyManagerOf(uint) external view returns (address ); ///=================================================================== /** * @notice Allows the key owner to safely share their key (parent key) by * transferring a portion of the remaining time to a new key (child key). * @dev Throws if key is not valid. * @dev Throws if `_to` is the zero address * @param _to The recipient of the shared key * @param _tokenId the key to share * @param _timeShared The amount of time shared * checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256('onERC721Received(address,address,uint,bytes)'))`. * @dev Emit Transfer event */ function shareKey( address _to, uint _tokenId, uint _timeShared ) external; /** * @notice Update transfer and cancel rights for a given key * @param _tokenId The id of the key to assign rights for * @param _keyManager The address to assign the rights to for the given key */ function setKeyManagerOf( uint _tokenId, address _keyManager ) external; /** * Check if a certain key is valid * @param _tokenId the id of the key to check validity * @notice this makes use of the onValidKeyHook if it is set */ function isValidKey( uint _tokenId ) external view returns (bool); /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string memory _name); ///=================================================================== /// From ERC165.sol function supportsInterface(bytes4 interfaceId) external view returns (bool); ///=================================================================== /// From ERC-721 /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external view returns (address _owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; /** * @notice Get the approved address for a single NFT * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for * @return operator The approved address for this NFT, or the zero address if there is none */ function getApproved(uint256 _tokenId) external view returns (address operator); /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _operator operator address to set the approval * @param _approved representing the status of the approval to be set * @notice disabled when transfers are disabled */ function setApprovalForAll(address _operator, bool _approved) external; /** * @dev Tells whether an operator is approved by a given keyManager * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); /** * Innherited from Open Zeppelin AccessControl.sol */ 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; function hasRole(bytes32 role, address account) external view returns (bool); /** * @notice An ERC-20 style transfer. * @param _value sends a token with _value * expirationDuration (the amount of time remaining on a standard purchase). * @dev The typical use case would be to call this with _value 1, which is on par with calling `transferFrom`. If the user * has more than `expirationDuration` time remaining this may use the `shareKey` function to send some but not all of the token. */ function transfer( address _to, uint _value ) external returns (bool success); /** `owner()` is provided as an helper to mimick the `Ownable` contract ABI. * The `Ownable` logic is used by many 3rd party services to determine * contract ownership - e.g. who is allowed to edit metadata on Opensea. * * @notice This logic is NOT used internally by the Unlock Protocol and is made * available only as a convenience helper. */ function owner() external view returns (address); function setOwner(address account) external; function isOwner(address account) external returns (bool); /** * Migrate data from the previous single owner => key mapping to * the new data structure w multiple tokens. * @param _calldata an ABI-encoded representation of the params (v10: the number of records to migrate as `uint`) * @dev when all record schemas are sucessfully upgraded, this function will update the `schemaVersion` * variable to the latest/current lock version */ function migrate(bytes calldata _calldata) external; /** * Returns the version number of the data schema currently used by the lock * @notice if this is different from `publicLockVersion`, then the ability to purchase, grant * or extend keys is disabled. * @dev will return 0 if no ;igration has ever been run */ function schemaVersion() external view returns (uint); /** * Set the schema version to the latest * @notice only lock manager call call this */ function updateSchemaVersion() external; /** * Renew a given token * @notice only works for non-free, expiring, ERC20 locks * @param _tokenId the ID fo the token to renew * @param _referrer the address of the person to be granted UDT */ function renewMembershipFor( uint _tokenId, address _referrer ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Base64.sol) pragma solidity ^0.8.0; /** * @dev Provides a set of functions to operate with Base64 strings. * * _Available since v4.5._ */ library Base64 { /** * @dev Base64 Encoding/Decoding Table */ string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** * @dev Converts a `bytes` to its Bytes64 `string` representation. */ function encode(bytes memory data) internal pure returns (string memory) { /** * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol */ if (data.length == 0) return ""; // Loads the table into memory string memory table = _TABLE; // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter // and split into 4 numbers of 6 bits. // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up // - `data.length + 2` -> Round up // - `/ 3` -> Number of 3-bytes chunks // - `4 *` -> 4 characters for each chunk string memory result = new string(4 * ((data.length + 2) / 3)); assembly { // Prepare the lookup table (skip the first "length" byte) let tablePtr := add(table, 1) // Prepare result pointer, jump over length let resultPtr := add(result, 32) // Run over the input, 3 bytes at a time for { let dataPtr := data let endPtr := add(data, mload(data)) } lt(dataPtr, endPtr) { } { // Advance 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // To write each character, shift the 3 bytes (18 bits) chunk // 4 times in blocks of 6 bits for each character (18, 12, 6, 0) // and apply logical AND with 0x3F which is the number of // the previous character in the ASCII table prior to the Base64 Table // The result is then added to the table to get the character to write, // and finally write it in the result pointer but with a left shift // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) resultPtr := add(resultPtr, 1) // Advance } // When data `bytes` is not exactly 3 bytes long // it is padded with `=` characters at the end switch mod(mload(data), 3) case 1 { mstore8(sub(resultPtr, 1), 0x3d) mstore8(sub(resultPtr, 2), 0x3d) } case 2 { mstore8(sub(resultPtr, 1), 0x3d) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.17 <0.9.0; /** * A very basic layer contract that's initialized with different version of a layer * and then serves a layer based on an index. */ contract Layer { string[] private _layers; constructor(string[] memory layers) { _layers = layers; } function getLayerCount() external view returns (uint256 length) { return _layers.length; } function getLayer(uint256 index) external view returns (string memory) { return _layers[index]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // https://aa.usno.navy.mil/faq/JD_formula.html // 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(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint 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(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint 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(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint 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(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint 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(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint 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(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint 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(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } }
see https:github.com/unlock-protocol/unlock/blob/master/smart-contracts/contracts/interfaces/hooks/IHook.sol uint timeOfDay = 0; string memory kind = ""; (, , , uint hour, , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(block.timestamp); if (hour <= 8) { timeOfDay = 0; 0 => night } else if (hour <= 17) { timeOfDay = 1; 1 => day } else if (hour <= 21) { timeOfDay = 2; 2 => sunset } else { timeOfDay = 0; 0 => night } If the calling contract is the avatar contract if (lockAddress == _avatarLock) { kind = "avatars"; uint weapon = 0; Check if there is a mapping! if (avatarsWeapons[keyId] > 0) { If there is one, let's check the owner and make sure it's the correct one IPublicLock weaponLock = IPublicLock(_weaponLock); TODO change me in v10! uint weaponExpiration = weaponLock.keyExpirationTimestampFor(owner); address weaponOwner = weaponLock.ownerOf(keyId); if (weaponExpiration > block.timestamp && weaponOwner == owner) { weapon = avatarsWeapons[keyId]; } } image = string( abi.encodePacked( _ipfsHash, "/", kind, "/", Strings.toString(keyId), "-", Strings.toString(weapon), "-", Strings.toString(timeOfDay) ) ); } else if (lockAddress == _weaponLock) { kind = "weapons"; image = string( abi.encodePacked( _ipfsHash, "/", kind, "/", Strings.toString(keyId) ) ); } create the json that includes the image We need to include more properties! render the base64 encoded json metadata
function tokenURI( ) external view returns (string memory) { string memory image = "QmYkkshevBxHg7XwdP1pw6A4T82xzD8G2RpLDFo6KDy3zm"; string memory json = string( ); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode(bytes(abi.encodePacked(json))) ) ); }
572,692
./partial_match/4/0xb822796865033B466770CE88B9C1E2f1B1ed56f0/sources/J2TS.sol
Prevent overflow when multiplying INT256_MIN with -1 https:github.com/RequestNetwork/requestNetwork/issues/43
function mul(int256 a, int256 b) internal pure returns (int256) { require(!(a == - 2 ** 255 && b == - 1) && !(b == - 2 ** 255 && a == - 1)); int256 c = a * b; require((b == 0) || (c / b == a)); return c; }
8,687,845
./partial_match/1/0x8a3B9BF2ee8016F9B6B59FEDaA1639E276c04e42/sources/Staker.sol
Cap token price at 1 eth, can't be called if makeUnchangeable() was called
function capPrice(bool input) public{ require(!unchangeable(), "makeUnchangeable() function was already called"); priceCapped = input; }
16,028,500
./partial_match/1/0xCEaC66ab21240FeD157391b2A792be37FbF5c6B9/sources/BuccaneerLOCK.sol
One way deposit function
function depositToLOCK(uint256 amountToDeposit) public onlyOwner returns (bool) { require (doubleLOCK == msg.sender); buccInstance = BuccV2(v2Address); numberofBUCC += amountToDeposit; return buccInstance.transferFrom(doubleLOCK, address(this), amountToDeposit); }
4,477,949
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./IERC721LibBeforeTokenTransferHook.sol"; /* Functionality used to whitelist OpenSea trading address, if desired */ contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, the Enumerable extension, and Pausable. * * Closely based on and mirrors the excellent https://openzeppelin.com/contracts/. */ library ERC721Lib { using Address for address; using Strings for uint256; /** * @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 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); struct ERC721Storage { // Token name string _name; // Token symbol string _symbol; // Mapping from token ID to owner address mapping (uint256 => address) _owners; // Mapping owner address to token count mapping (address => uint256) _balances; // Mapping from token ID to approved address mapping (uint256 => address) _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) _operatorApprovals; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) _allTokensIndex; // Base URI string _baseURI; // True if token transfers are paused bool _paused; // Hook function that can be called before token is transferred, along with a pointer to its storage struct IERC721LibBeforeTokenTransferHook _beforeTokenTransferHookInterface; bytes32 _beforeTokenTransferHookStorageSlot; address proxyRegistryAddress; } function init(ERC721Storage storage s, string memory _name, string memory _symbol) external { s._name = _name; s._symbol = _symbol; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) external pure returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId; } // // Start of ERC721 functions // /** * @dev See {IERC721-balanceOf}. */ function _balanceOf(ERC721Storage storage s, address owner) internal view returns (uint256) { require(owner != address(0), "Balance query for address zero"); return s._balances[owner]; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(ERC721Storage storage s, address owner) external view returns (uint256) { return _balanceOf(s, owner); } /** * @dev See {IERC721-ownerOf}. */ function _ownerOf(ERC721Storage storage s, uint256 tokenId) internal view returns (address) { address owner = s._owners[tokenId]; require(owner != address(0), "Owner query for nonexist. token"); return owner; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(ERC721Storage storage s, uint256 tokenId) external view returns (address) { return _ownerOf(s, tokenId); } /** * @dev See {IERC721Metadata-name}. */ function name(ERC721Storage storage s) external view returns (string memory) { return s._name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol(ERC721Storage storage s) external view returns (string memory) { return s._symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(ERC721Storage storage s, uint256 tokenId) external view returns (string memory) { require(_exists(s, tokenId), "URI query for nonexistent token"); return bytes(s._baseURI).length > 0 ? string(abi.encodePacked(s._baseURI, tokenId.toString())) : ""; } /** * @dev Set base URI */ function setBaseURI(ERC721Storage storage s, string memory baseTokenURI) external { s._baseURI = baseTokenURI; } /** * @dev See {IERC721-approve}. */ function approve(ERC721Storage storage s, address to, uint256 tokenId) external { address owner = _ownerOf(s, tokenId); require(to != owner, "Approval to current owner"); require(msg.sender == owner || _isApprovedForAll(s, owner, msg.sender), "Not owner nor approved for all" ); _approve(s, to, tokenId); } /** * @dev Approve independently of who's the owner * * Obviously expose with care... */ function overrideApprove(ERC721Storage storage s, address to, uint256 tokenId) external { _approve(s, to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function _getApproved(ERC721Storage storage s, uint256 tokenId) internal view returns (address) { require(_exists(s, tokenId), "Approved query nonexist. token"); return s._tokenApprovals[tokenId]; } /** * @dev See {IERC721-getApproved}. */ function getApproved(ERC721Storage storage s, uint256 tokenId) external view returns (address) { return _getApproved(s, tokenId); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(ERC721Storage storage s, address operator, bool approved) external { require(operator != msg.sender, "Attempted approve to caller"); s._operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function _isApprovedForAll(ERC721Storage storage s, address owner, address operator) internal view returns (bool) { // Whitelist OpenSea proxy contract for easy trading - if we have a valid proxy registry address on file if (s.proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(s.proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } } return s._operatorApprovals[owner][operator]; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(ERC721Storage storage s, address owner, address operator) external view returns (bool) { return _isApprovedForAll(s, owner, operator); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved"); _transfer(s, from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId) external { _safeTransferFrom(s, from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function _safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal { require(_isApprovedOrOwner(s, msg.sender, tokenId), "TransferFrom not owner/approved"); _safeTransfer(s, from, to, tokenId, _data); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external { _safeTransferFrom(s, 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(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) internal { _transfer(s, from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "Transfer to non ERC721Receiver"); } /** * @dev directSafeTransfer * * CAREFUL, this does not verify the previous ownership - only use if ownership/eligibility has been asserted by other means */ function directSafeTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId, bytes memory _data) external { _safeTransfer(s, from, to, tokenId, _data); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(ERC721Storage storage s, uint256 tokenId) internal view returns (bool) { return s._owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(ERC721Storage storage s, address spender, uint256 tokenId) internal view returns (bool) { require(_exists(s, tokenId), "Operator query nonexist. token"); address owner = _ownerOf(s, tokenId); return (spender == owner || _getApproved(s, tokenId) == spender || _isApprovedForAll(s, 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(ERC721Storage storage s, address to, uint256 tokenId) internal { _safeMint(s, 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(ERC721Storage storage s, address to, uint256 tokenId, bytes memory _data) internal { _unsafeMint(s, to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "Transfer to non ERC721Receiver"); } /** * @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 _unsafeMint(ERC721Storage storage s, address to, uint256 tokenId) internal { require(to != address(0), "Mint to the zero address"); require(!_exists(s, tokenId), "Token already minted"); _beforeTokenTransfer(s, address(0), to, tokenId); s._balances[to] += 1; s._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(ERC721Storage storage s, uint256 tokenId) internal { address owner = _ownerOf(s, tokenId); _beforeTokenTransfer(s, owner, address(0), tokenId); // Clear approvals _approve(s, address(0), tokenId); s._balances[owner] -= 1; delete s._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(ERC721Storage storage s, address from, address to, uint256 tokenId) internal { require(_ownerOf(s, tokenId) == from, "TransferFrom not owner/approved"); require(to != address(0), "Transfer to the zero address"); _beforeTokenTransfer(s, from, to, tokenId); // Clear approvals from the previous owner _approve(s, address(0), tokenId); s._balances[from] -= 1; s._balances[to] += 1; s._owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(ERC721Storage storage s, address to, uint256 tokenId) internal { s._tokenApprovals[tokenId] = to; emit Approval(_ownerOf(s, 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(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("Transfer to non ERC721Receiver"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // // Start of functions from ERC721Enumerable // /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(ERC721Storage storage s, address owner, uint256 index) external view returns (uint256) { require(index < _balanceOf(s, owner), "Owner index out of bounds"); return s._ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function _totalSupply(ERC721Storage storage s) internal view returns (uint256) { return s._allTokens.length; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply(ERC721Storage storage s) external view returns (uint256) { return s._allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(ERC721Storage storage s, uint256 index) external view returns (uint256) { require(index < _totalSupply(s), "Global index out of bounds"); return s._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(ERC721Storage storage s, address from, address to, uint256 tokenId) internal { if(address(s._beforeTokenTransferHookInterface) != address(0)) { // We have a hook that we need to delegate call (bool success, ) = address(s._beforeTokenTransferHookInterface).delegatecall( abi.encodeWithSelector(s._beforeTokenTransferHookInterface._beforeTokenTransferHook.selector, s._beforeTokenTransferHookStorageSlot, from, to, tokenId) ); if(!success) { // Bubble up the revert message assembly { let ptr := mload(0x40) let size := returndatasize() returndatacopy(ptr, 0, size) revert(ptr, size) } } } require(!_paused(s), "No token transfer while paused"); if (from == address(0)) { _addTokenToAllTokensEnumeration(s, tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(s, from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(s, tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(s, 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(ERC721Storage storage s, address to, uint256 tokenId) private { uint256 length = _balanceOf(s, to); s._ownedTokens[to][length] = tokenId; s._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(ERC721Storage storage s, uint256 tokenId) private { s._allTokensIndex[tokenId] = s._allTokens.length; s._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(ERC721Storage storage s, 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 = _balanceOf(s, from) - 1; uint256 tokenIndex = s._ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = s._ownedTokens[from][lastTokenIndex]; s._ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token s._ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete s._ownedTokensIndex[tokenId]; delete s._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(ERC721Storage storage s, 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 = s._allTokens.length - 1; uint256 tokenIndex = s._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 = s._allTokens[lastTokenIndex]; s._allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token s._allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete s._allTokensIndex[tokenId]; s._allTokens.pop(); } // // Start of functions from Pausable // /** * @dev Returns true if the contract is paused, and false otherwise. */ function _paused(ERC721Storage storage s) internal view returns (bool) { return s._paused; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused(ERC721Storage storage s) external view returns (bool) { return s._paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused(ERC721Storage storage s) { require(!_paused(s), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused(ERC721Storage storage s) { require(_paused(s), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause(ERC721Storage storage s) external whenNotPaused(s) { s._paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause(ERC721Storage storage s) external whenPaused(s) { s._paused = false; emit Unpaused(msg.sender); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; /** * @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); } } } } // 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) { 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.8.0; /** * @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); } } // 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 "./ERC721Lib.sol"; /** * @dev Interface that can be used to hook additional beforeTokenTransfer functions into ERC721Lib */ interface IERC721LibBeforeTokenTransferHook { /** * @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 _beforeTokenTransferHook(bytes32 storagePosition, address from, address to, uint256 tokenId) 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); }
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.adocusing-hooks[Using Hooks]./ We have a hook that we need to delegate call Bubble up the revert message
function _beforeTokenTransfer(ERC721Storage storage s, address from, address to, uint256 tokenId) internal { if(address(s._beforeTokenTransferHookInterface) != address(0)) { (bool success, ) = address(s._beforeTokenTransferHookInterface).delegatecall( abi.encodeWithSelector(s._beforeTokenTransferHookInterface._beforeTokenTransferHook.selector, s._beforeTokenTransferHookStorageSlot, from, to, tokenId) ); if(!success) { assembly { let ptr := mload(0x40) let size := returndatasize() returndatacopy(ptr, 0, size) revert(ptr, size) } } } require(!_paused(s), "No token transfer while paused"); if (from == address(0)) { _addTokenToAllTokensEnumeration(s, tokenId); _removeTokenFromOwnerEnumeration(s, from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(s, tokenId); _addTokenToOwnerEnumeration(s, to, tokenId); } }
6,935,804
pragma solidity 0.4.25; // * Samurai Quest - Levelling game that pay ether. Version 1. // // * Developer - Studio California // "You can check out any time you like, but you can never leave" // // * Uses Linked List to store player level // // * Refer to https://samurai-quest.hostedwiki.co/ for detailed description. contract SamuraiQuest { using SafeMath for uint256; using LinkedListLib for LinkedListLib.LinkedList; // ***Event Section event NewSamuraiIncoming(uint256 id, bytes32 name); event TheLastSamuraiBorn(uint256 id, bytes32 name, uint256 winning); event Retreat(uint256 id, bytes32 name, uint256 balance); address public owner; uint256 public currentSamuraiId; uint256 public totalProcessingFee; uint256 public theLastSamuraiPot; uint256 public theLastSamuraiEndTime; // ***Constant Section uint256 private constant MAX_LEVEL = 8; uint256 private constant JOINING_FEE = 0.03 ether; uint256 private constant PROCESSING_FEE = 0.001 ether; uint256 private constant REFERRAL_FEE = 0.002 ether; uint256 private constant THE_LAST_SAMURAI_FEE = 0.002 ether; uint256 private constant THE_LAST_SAMURAI_COOLDOWN = 1 days; struct Samurai { uint256 level; uint256 supporterWallet; uint256 referralWallet; uint256 theLastSamuraiWallet; bytes32 name; address addr; bool isRetreat; bool autoLevelUp; } mapping (address => uint256) public addressToId; mapping (uint256 => Samurai) public idToSamurai; mapping (uint256 => uint256) public idToSamuraiHeadId; mapping (uint256 => uint256) public idToAffiliateId; mapping (uint256 => uint256) public supporterCount; mapping (uint256 => uint256) public referralCount; mapping (uint256 => LinkedListLib.LinkedList) private levelChain; // level up chain uint256[9] public levelUpFee; // level up fees // Constructor. Deliberately does not take any parameters. constructor() public { // Set the contract owner owner = msg.sender; totalProcessingFee = 0; theLastSamuraiPot = 0; currentSamuraiId = 1; // Level up fee levelUpFee[1] = 0.02 ether; // 0 > 1 levelUpFee[2] = 0.04 ether; // 1 > 2 levelUpFee[3] = 0.08 ether; // 2 > 3 levelUpFee[4] = 0.16 ether; // 3 > 4 levelUpFee[5] = 0.32 ether; // 4 > 5 levelUpFee[6] = 0.64 ether; // 5 > 6 levelUpFee[7] = 1.28 ether; // 6 > 7 levelUpFee[8] = 2.56 ether; // 7 > 8 } modifier onlyOwner() { require(msg.sender == owner, "OnlyOwner method called by non owner"); _; } // Fund withdrawal to cover costs of operation function withdrawProcessingFee() public onlyOwner { require(totalProcessingFee <= address(this).balance, "not enough fund"); uint256 amount = totalProcessingFee; totalProcessingFee = 0; owner.transfer(amount); } // Fallback function deliberately left empty. function () public payable { } /// *** join Logic // Set the samurai info and level to 0, then level up it // _name - Name of the samurai // _affiliateId - Affiliate Id, affiliate will get 0.002ETH of each action // performed by it's referral // _autoLevelUp - Let player control the level up type function join(bytes32 _name, uint256 _affiliateId, bool _autoLevelUp) public payable { require(msg.value == JOINING_FEE, "you have no enough courage"); require(addressToId[msg.sender] == 0, "you're already in"); require(_affiliateId >= 0 && _affiliateId < currentSamuraiId, "invalid affiliate"); Samurai storage samurai = idToSamurai[currentSamuraiId]; samurai.level = 0; samurai.addr = msg.sender; samurai.referralWallet = 0; samurai.theLastSamuraiWallet = 0; samurai.name = _name; samurai.isRetreat = false; samurai.autoLevelUp = _autoLevelUp; samurai.supporterWallet = JOINING_FEE; addressToId[msg.sender] = currentSamuraiId; if (_affiliateId > 0) { idToAffiliateId[currentSamuraiId] = _affiliateId; referralCount[_affiliateId] = referralCount[_affiliateId].add(1); } levelUp(currentSamuraiId); emit NewSamuraiIncoming(currentSamuraiId, samurai.name); // Increase the count for next samurai currentSamuraiId = currentSamuraiId.add(1); theLastSamuraiEndTime = now.add(THE_LAST_SAMURAI_COOLDOWN); } /// *** levelUp Logic // Level up the samurai, push it to the next level chain // Help checking the last samurai pot // Distribute the fund to corresponding accounts // Help levelling up the head of samurai // _samuraiId - Id of the samurai to be levelled up function levelUp(uint256 _samuraiId) public { bool exist; uint256 samuraiHeadId; Samurai storage samurai = idToSamurai[_samuraiId]; require(canLevelUp(_samuraiId), "cannot level up"); uint256 balance = samurai.supporterWallet.add(samurai.referralWallet).add(samurai.theLastSamuraiWallet); require( balance >= levelUpFee[samurai.level.add(1)].add(PROCESSING_FEE).add(THE_LAST_SAMURAI_FEE).add(REFERRAL_FEE), "not enough fund to level up" ); // level up samurai.level = samurai.level.add(1); // help checking the last samurai pot distributeTheLastSamuraiPot(); // push the samurai Id to the corresponding level chain push(levelChain[samurai.level], _samuraiId); supporterCount[_samuraiId] = 0; // Check if head exist, and get it's Id (exist, samuraiHeadId) = levelChain[samurai.level].getAdjacent(0, true); // Distribute 0.001 ETH to poor developer samurai.supporterWallet = samurai.supporterWallet.sub(PROCESSING_FEE); totalProcessingFee = totalProcessingFee.add(PROCESSING_FEE); // Distribute 0.002 ETH to the last samurai pot samurai.supporterWallet = samurai.supporterWallet.sub(THE_LAST_SAMURAI_FEE); theLastSamuraiPot = theLastSamuraiPot.add(THE_LAST_SAMURAI_FEE); // Distribute 0.002 ETH to affiliate/the last samurai pot uint256 affiliateId = idToAffiliateId[_samuraiId]; samurai.supporterWallet = samurai.supporterWallet.sub(REFERRAL_FEE); if (affiliateId == 0) { theLastSamuraiPot = theLastSamuraiPot.add(REFERRAL_FEE); } else { Samurai storage affiliate = idToSamurai[affiliateId]; affiliate.referralWallet = affiliate.referralWallet.add(REFERRAL_FEE); } // check if samuraiHead exist and it should not be Samurai itself if (exist && samuraiHeadId != _samuraiId) { Samurai storage samuraiHead = idToSamurai[samuraiHeadId]; // Distribute the level up fee to samuraiHead samurai.supporterWallet = samurai.supporterWallet.sub(levelUpFee[samurai.level]); samuraiHead.supporterWallet = samuraiHead.supporterWallet.add(levelUpFee[samurai.level]); // Map the samuraiId to samuraiHead struct idToSamuraiHeadId[_samuraiId] = samuraiHeadId; // Add up the supporter count of samuraiHead supporterCount[samuraiHeadId] = supporterCount[samuraiHeadId].add(1); // nested loop to level up samuraiHead if(canLevelUp(samuraiHeadId)) { // pop the samurai headoff the leve chain pop(levelChain[samuraiHead.level]); if(samuraiHead.autoLevelUp) { levelUp(samuraiHeadId); } else { return; } } else { return; } } } /// *** retreat Logic // Retreat the samurai, pop it off the level chain // Help checking the last samurai pot // Distribute the fund to corresponding accounts // _samuraiId - Id of the samurai to be retreat function retreat(uint256 _samuraiId) public { Samurai storage samurai = idToSamurai[_samuraiId]; require(!samurai.isRetreat, "you've already quit!"); require(samurai.addr == msg.sender, "you must be a yokai spy!"); uint256 balance = samurai.supporterWallet.add(samurai.referralWallet).add(samurai.theLastSamuraiWallet); require(balance >= 0.005 ether, "fee is required, even when retreating"); // Clear the balance, prevent re-entrancy samurai.supporterWallet = 0; samurai.theLastSamuraiWallet = 0; samurai.referralWallet = 0; // pop the player off the level chain and mark the retreat flag remove(levelChain[samurai.level], _samuraiId); samurai.isRetreat = true; // Transfer the processing fee to poor developer balance = balance.sub(PROCESSING_FEE); totalProcessingFee = totalProcessingFee.add(PROCESSING_FEE); balance = balance.sub(THE_LAST_SAMURAI_FEE); theLastSamuraiPot = theLastSamuraiPot.add(THE_LAST_SAMURAI_FEE); balance = balance.sub(REFERRAL_FEE); uint256 affiliateId = idToAffiliateId[_samuraiId]; // No affiliate, distribute the referral fee to the last samurai pot if (affiliateId == 0) { theLastSamuraiPot = theLastSamuraiPot.add(REFERRAL_FEE); } else { Samurai storage affiliate = idToSamurai[affiliateId]; affiliate.referralWallet = affiliate.referralWallet.add(REFERRAL_FEE); } // transfer balance to account holder samurai.addr.transfer(balance); // help checking the last samurai pot distributeTheLastSamuraiPot(); emit Retreat(_samuraiId, samurai.name, balance); } /// *** withdraw Logic // Withdraw the left over fund in wallet after retreat // _samuraiId - Id of the samurai function withdraw(uint256 _samuraiId) public { Samurai storage samurai = idToSamurai[_samuraiId]; require(samurai.addr == msg.sender, "you must be a yokai spy!"); uint256 balance = samurai.supporterWallet.add(samurai.referralWallet).add(samurai.theLastSamuraiWallet); require(balance <= address(this).balance, "not enough fund"); // Prevent re-entrancy samurai.supporterWallet = 0; samurai.theLastSamuraiWallet = 0; samurai.referralWallet = 0; // transfer balance to account holder samurai.addr.transfer(balance); } /// *** distributeTheLastSamuraiPot Logic // Distribute the last samurai pot to winner when no joining after 24 hours // Distribute the fund to corresponding accounts // _samuraiId - Id of the samurai to be retreat function distributeTheLastSamuraiPot() public { require(theLastSamuraiPot <= address(this).balance, "not enough fund"); // When the remaining time is over if (theLastSamuraiEndTime <= now) { uint256 samuraiId = currentSamuraiId.sub(1); Samurai storage samurai = idToSamurai[samuraiId]; uint256 total = theLastSamuraiPot; // again, prevent re-entrancy theLastSamuraiPot = 0; samurai.theLastSamuraiWallet = samurai.theLastSamuraiWallet.add(total); emit TheLastSamuraiBorn(samuraiId, samurai.name, total); } } /// *** toggleAutoLevelUp Logic // Toggle auto level up, for those who don't intend to play longer, // can set the auto level up to false // _samuraiId - Id of the samurai function toggleAutoLevelUp(uint256 _samuraiId) public { Samurai storage samurai = idToSamurai[_samuraiId]; require(!samurai.isRetreat, "you've already quit!"); require(msg.sender == samurai.addr, "you must be a yokai spy"); samurai.autoLevelUp = !samurai.autoLevelUp; } //*** For UI // Returns - Id function getSamuraiId() public view returns(uint256) { return addressToId[msg.sender]; } // Returns - 0: id, 1: level, 2: name, 3: isRetreat, 4: autoLevelUp, 5: isHead function getSamuraiInfo(uint256 _samuraiId) public view returns(uint256, uint256, bytes32, bool, bool, bool) { Samurai memory samurai = idToSamurai[_samuraiId]; bool isHead = isHeadOfSamurai(_samuraiId); return (_samuraiId, samurai.level, samurai.name, samurai.isRetreat, samurai.autoLevelUp, isHead); } // Returns - 0: supperterWallet, 1: theLastSamuraiWallet, 2: referralWallet function getSamuraiWallet(uint256 _samuraiId) public view returns(uint256, uint256, uint256) { Samurai memory samurai = idToSamurai[_samuraiId]; return (samurai.supporterWallet, samurai.theLastSamuraiWallet, samurai.referralWallet); } // Returns - 0: affiliateId, 1: affiliateName function getAffiliateInfo(uint256 _samuraiId) public view returns(uint256, bytes32) { uint256 affiliateId = idToAffiliateId[_samuraiId]; Samurai memory affiliate = idToSamurai[affiliateId]; return (affiliateId, affiliate.name); } // Returns - 0: samuraiHeadId, 1: samuraiHeadName function contributeTo(uint256 _samuraiId) public view returns(uint256, bytes32) { uint256 samuraiHeadId = idToSamuraiHeadId[_samuraiId]; Samurai memory samuraiHead = idToSamurai[samuraiHeadId]; return (samuraiHeadId, samuraiHead.name); } // Returns - 0: theLastSamuraiEndTime, 1: theLastSamuraiPot, 2: lastSamuraiId, 3: lastSamuraiName function getTheLastSamuraiInfo() public view returns(uint256, uint256, uint256, bytes32) { uint256 lastSamuraiId = currentSamuraiId.sub(1); return (theLastSamuraiEndTime, theLastSamuraiPot, lastSamuraiId, idToSamurai[lastSamuraiId].name); } // Returns - canLevelUp function canLevelUp(uint256 _id) public view returns(bool) { Samurai memory samurai = idToSamurai[_id]; return !samurai.isRetreat && (samurai.level == 0 || (supporterCount[_id] == 2 ** samurai.level && samurai.level <= MAX_LEVEL)); } // Returns - canRetreat function canRetreat(uint256 _id) public view returns(bool) { Samurai memory samurai = idToSamurai[_id]; uint256 balance = samurai.supporterWallet.add(samurai.referralWallet).add(samurai.theLastSamuraiWallet); return !samurai.isRetreat && (balance >= 0.005 ether); } // Returns - canWithdraw function canWithdraw(uint256 _id) public view returns(bool) { Samurai memory samurai = idToSamurai[_id]; uint256 balance = samurai.supporterWallet.add(samurai.referralWallet).add(samurai.theLastSamuraiWallet); return samurai.isRetreat && (balance > 0); } // Returns - isHeadOfSamurai function isHeadOfSamurai(uint256 _id) public view returns(bool) { Samurai memory samurai = idToSamurai[_id]; bool exist; uint256 samuraiHeadId; (exist, samuraiHeadId) = levelChain[samurai.level].getAdjacent(0, true); return (exist && samuraiHeadId == _id); } // For linked list manipulation function push(LinkedListLib.LinkedList storage _levelChain, uint256 _samuraiId) private { _levelChain.push(_samuraiId, false); } function pop(LinkedListLib.LinkedList storage _levelChain) private { _levelChain.pop(true); } function remove(LinkedListLib.LinkedList storage _levelChain, uint256 _samuraiId) private { _levelChain.remove(_samuraiId); } } /** * @title LinkedListLib * @author Darryl Morris (o0ragman0o) and Modular.network * * This utility library was forked from https://github.com/o0ragman0o/LibCLL * into the Modular-Network ethereum-libraries repo at https://github.com/Modular-Network/ethereum-libraries * It has been updated to add additional functionality and be more compatible with solidity 0.4.18 * coding patterns. * * version 1.0.0 * Copyright (c) 2017 Modular Inc. * The MIT License (MIT) * https://github.com/Modular-Network/ethereum-libraries/blob/master/LICENSE * * The LinkedListLib provides functionality for implementing data indexing using * a circlular linked list. * * Modular provides smart contract services and security reviews for contract * deployments in addition to working on open source projects in the Ethereum * community. Our purpose is to test, document, and deploy reusable code onto the * blockchain and improve both security and usability. We also educate non-profits, * schools, and other community members about the application of blockchain * technology. For further information: modular.network. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library LinkedListLib { uint256 private constant NULL = 0; uint256 private constant HEAD = 0; bool private constant PREV = false; bool private constant NEXT = true; struct LinkedList { mapping (uint256 => mapping (bool => uint256)) list; } /// @dev returns true if the list exists /// @param self stored linked list from contract function listExists(LinkedList storage self) internal view returns (bool) { // if the head nodes previous or next pointers both point to itself, then there are no items in the list if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) { return true; } else { return false; } } /// @dev returns true if the node exists /// @param self stored linked list from contract /// @param _node a node to search for function nodeExists(LinkedList storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) { if (self.list[HEAD][NEXT] == _node) { return true; } else { return false; } } else { return true; } } /// @dev Returns the number of elements in the list /// @param self stored linked list from contract function sizeOf(LinkedList storage self) internal view returns (uint256 numElements) { bool exists; uint256 i; (exists, i) = getAdjacent(self, HEAD, NEXT); while (i != HEAD) { (exists, i) = getAdjacent(self, i, NEXT); numElements++; } return; } /// @dev Returns the links of a node as a tuple /// @param self stored linked list from contract /// @param _node id of the node to get function getNode(LinkedList storage self, uint256 _node) internal view returns (bool, uint256, uint256) { if (!nodeExists(self, _node)) { return (false, 0, 0); } else { return (true, self.list[_node][PREV], self.list[_node][NEXT]); } } /// @dev Returns the link of a node `_node` in direction `_direction`. /// @param self stored linked list from contract /// @param _node id of the node to step from /// @param _direction direction to step in function getAdjacent(LinkedList storage self, uint256 _node, bool _direction) internal view returns (bool, uint256) { if (!nodeExists(self, _node)) { return (false, 0); } else { return (true, self.list[_node][_direction]); } } /// @dev Can be used before `insert` to build an ordered list /// @param self stored linked list from contract /// @param _node an existing node to search from, e.g. HEAD. /// @param _value value to seek /// @param _direction direction to seek in // @return next first node beyond '_node' in direction `_direction` function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction) internal view returns (uint256) { if (sizeOf(self) == 0) { return 0; } require((_node == 0) || nodeExists(self, _node)); bool exists; uint256 next; (exists, next) = getAdjacent(self, _node, _direction); while ((next != 0) && (_value != next) && ((_value < next) != _direction)) { next = self.list[next][_direction]; } return next; } /// @dev Creates a bidirectional link between two nodes on direction `_direction` /// @param self stored linked list from contract /// @param _node first node for linking /// @param _link node to link to in the _direction function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction) internal { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } /// @dev Insert node `_new` beside existing node `_node` in direction `_direction`. /// @param self stored linked list from contract /// @param _node existing node /// @param _new new node to insert /// @param _direction direction to insert node in function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; createLink(self, _node, _new, _direction); createLink(self, _new, c, _direction); return true; } else { return false; } } /// @dev removes an entry from the linked list /// @param self stored linked list from contract /// @param _node node to remove from the list function remove(LinkedList storage self, uint256 _node) internal returns (uint256) { if ((_node == NULL) || (!nodeExists(self, _node))) { return 0; } createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT); delete self.list[_node][PREV]; delete self.list[_node][NEXT]; return _node; } /// @dev pushes an entry to the head of the linked list /// @param self stored linked list from contract /// @param _node new entry to push to the head /// @param _direction push to the head (NEXT) or tail (PREV) function push(LinkedList storage self, uint256 _node, bool _direction) internal returns (bool) { return insert(self, HEAD, _node, _direction); } /// @dev pops the first entry from the linked list /// @param self stored linked list from contract /// @param _direction pop from the head (NEXT) or the tail (PREV) function pop(LinkedList storage self, bool _direction) internal returns (uint256) { bool exists; uint256 adj; (exists, adj) = getAdjacent(self, HEAD, _direction); return remove(self, adj); } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ 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; } }
Insert node `_new` beside existing node `_node` in direction `_direction`. self stored linked list from contract _node existing node _new new node to insert _direction direction to insert node in
function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) { if (!nodeExists(self, _new) && nodeExists(self, _node)) { uint256 c = self.list[_node][_direction]; createLink(self, _node, _new, _direction); createLink(self, _new, c, _direction); return true; return false; } }
13,088,972
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/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 virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_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 virtual returns (uint8) { return _decimals; } /** * @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); _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 virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/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; /** * @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 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; } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | 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/token/RocketTokenRPLInterface.sol"; import "../../interface/rewards/RocketRewardsPoolInterface.sol"; import "../../interface/dao/protocol/settings/RocketDAOProtocolSettingsRewardsInterface.sol"; import "../../interface/RocketVaultInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // Holds RPL generated by the network for claiming from stakers (node operators etc) contract RocketRewardsPool is RocketBase, RocketRewardsPoolInterface { // Libs using SafeMath for uint; // Events event RPLTokensClaimed(address indexed claimingContract, address indexed claimingAddress, uint256 amount, uint256 time); // Modifiers /** * @dev Throws if called by any sender that doesn't match a Rocket Pool claim contract */ modifier onlyClaimContract() { require(getClaimingContractExists(getContractName(msg.sender)), "Not a valid rewards claiming contact"); _; } /** * @dev Throws if called by any sender that doesn't match an enabled Rocket Pool claim contract */ modifier onlyEnabledClaimContract() { require(getClaimingContractEnabled(getContractName(msg.sender)), "Not a valid rewards claiming contact or it has been disabled"); _; } // Construct constructor(RocketStorageInterface _rocketStorageAddress) RocketBase(_rocketStorageAddress) { // Version version = 1; // Set the claim interval start time as the current time setUint(keccak256("rewards.pool.claim.interval.time.start"), block.timestamp); } /** * Get how much RPL the Rewards Pool contract currently has assigned to it as a whole * @return uint256 Returns rpl balance of rocket rewards contract */ function getRPLBalance() override external view returns(uint256) { // Get the vault contract instance RocketVaultInterface rocketVault = RocketVaultInterface(getContractAddress("rocketVault")); // Check per contract return rocketVault.balanceOfToken("rocketRewardsPool", IERC20(getContractAddress("rocketTokenRPL"))); } /** * Get the last set interval start time * @return uint256 Last set start timestamp for a claim interval */ function getClaimIntervalTimeStart() override public view returns(uint256) { return getUint(keccak256("rewards.pool.claim.interval.time.start")); } /** * Compute the current start time before a claim is made, takes into account intervals that may have passed * @return uint256 Computed starting timestamp for next possible claim */ function getClaimIntervalTimeStartComputed() override public view returns(uint256) { // If intervals have passed, a new start timestamp will be used for the next claim, if it's the same interval then return that uint256 claimIntervalTimeStart = getClaimIntervalTimeStart(); uint256 claimIntervalTime = getClaimIntervalTime(); return _getClaimIntervalTimeStartComputed(claimIntervalTimeStart, claimIntervalTime); } function _getClaimIntervalTimeStartComputed(uint256 _claimIntervalTimeStart, uint256 _claimIntervalTime) private view returns (uint256) { uint256 claimIntervalsPassed = _getClaimIntervalsPassed(_claimIntervalTimeStart, _claimIntervalTime); return claimIntervalsPassed == 0 ? _claimIntervalTimeStart : _claimIntervalTimeStart.add(_claimIntervalTime.mul(claimIntervalsPassed)); } /** * Compute intervals since last claim period * @return uint256 Time intervals since last update */ function getClaimIntervalsPassed() override public view returns(uint256) { // Calculate now if inflation has begun return _getClaimIntervalsPassed(getClaimIntervalTimeStart(), getClaimIntervalTime()); } function _getClaimIntervalsPassed(uint256 _claimIntervalTimeStart, uint256 _claimIntervalTime) private view returns (uint256) { return block.timestamp.sub(_claimIntervalTimeStart).div(_claimIntervalTime); } /** * Get how many seconds in a claim interval * @return uint256 Number of seconds in a claim interval */ function getClaimIntervalTime() override public view returns(uint256) { // Get from the DAO settings RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); return daoSettingsRewards.getRewardsClaimIntervalTime(); } /** * Get the last time a claim was made * @return uint256 Last time a claim was made */ function getClaimTimeLastMade() override external view returns(uint256) { return getUint(keccak256("rewards.pool.claim.interval.time.last")); } // Check whether a claiming contract exists function getClaimingContractExists(string memory _contractName) override public view returns (bool) { RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); return (daoSettingsRewards.getRewardsClaimerPercTimeUpdated(_contractName) > 0); } // If the claiming contact has a % allocated to it higher than 0, it can claim function getClaimingContractEnabled(string memory _contractName) override public view returns (bool) { // Load contract RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); // Now verify this contract can claim by having a claim perc > 0 return daoSettingsRewards.getRewardsClaimerPerc(_contractName) > 0 ? true : false; } /** * The current claim amount total for this interval per claiming contract * @return uint256 The current claim amount for this interval for the claiming contract */ function getClaimingContractTotalClaimed(string memory _claimingContract) override external view returns(uint256) { return _getClaimingContractTotalClaimed(_claimingContract, getClaimIntervalTimeStartComputed()); } function _getClaimingContractTotalClaimed(string memory _claimingContract, uint256 _claimIntervalTimeStartComputed) private view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.total", _claimIntervalTimeStartComputed, _claimingContract))); } /** * Have they claimed already during this interval? * @return bool Returns true if they can claim during this interval */ function getClaimingContractUserHasClaimed(uint256 _claimIntervalStartTime, string memory _claimingContract, address _claimerAddress) override public view returns(bool) { // Check per contract return getBool(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimer.address", _claimIntervalStartTime, _claimingContract, _claimerAddress))); } /** * Get the time this account registered as a claimer at * @return uint256 Returns the time the account was registered at */ function getClaimingContractUserRegisteredTime(string memory _claimingContract, address _claimerAddress) override public view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.time", _claimingContract, _claimerAddress))); } /** * Get whether this address can currently make a claim * @return bool Returns true if the _claimerAddress can make a claim */ function getClaimingContractUserCanClaim(string memory _claimingContract, address _claimerAddress) override public view returns(bool) { return _getClaimingContractUserCanClaim(_claimingContract, _claimerAddress, getClaimIntervalTime()); } function _getClaimingContractUserCanClaim(string memory _claimingContract, address _claimerAddress, uint256 _claimIntervalTime) private view returns(bool) { // Get the time they registered at uint256 registeredTime = getClaimingContractUserRegisteredTime(_claimingContract, _claimerAddress); // If it's 0 or hasn't passed one interval yet, they can't claim return registeredTime > 0 && registeredTime.add(_claimIntervalTime) <= block.timestamp && getClaimingContractPerc(_claimingContract) > 0 ? true : false; } /** * Get the number of claimers for the current interval per claiming contract * @return uint256 Returns number of claimers for the current interval per claiming contract */ function getClaimingContractUserTotalCurrent(string memory _claimingContract) override external view returns(uint256) { // Return the current interval amount if in that interval, if we are moving to the next one upon next claim, use that return getClaimIntervalsPassed() == 0 ? getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.current", _claimingContract))) : getClaimingContractUserTotalNext(_claimingContract); } /** * Get the number of claimers that will be added/removed on the next interval * @return uint256 Returns the number of claimers that will be added/removed on the next interval */ function getClaimingContractUserTotalNext(string memory _claimingContract) override public view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", _claimingContract))); } /** * Get contract claiming percentage last recorded * @return uint256 Returns the contract claiming percentage last recorded */ function getClaimingContractPercLast(string memory _claimingContract) override public view returns(uint256) { return getUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.perc.current", _claimingContract))); } /** * Get the approx amount of rewards available for this claim interval * @return uint256 Rewards amount for current claim interval */ function getClaimIntervalRewardsTotal() override public view returns(uint256) { // Get the RPL contract instance RocketTokenRPLInterface rplContract = RocketTokenRPLInterface(getContractAddress("rocketTokenRPL")); // Get the vault contract instance RocketVaultInterface rocketVault = RocketVaultInterface(getContractAddress("rocketVault")); // Rewards amount uint256 rewardsTotal = 0; // Is this the first claim of this interval? If so, calculate expected inflation RPL + any RPL already in the pool if(getClaimIntervalsPassed() > 0) { // Get the balance of tokens that will be transferred to the vault for this contract when the first claim is made // Also account for any RPL tokens already in the vault for the rewards pool rewardsTotal = rplContract.inflationCalculate().add(rocketVault.balanceOfToken("rocketRewardsPool", IERC20(getContractAddress("rocketTokenRPL")))); }else{ // Claims have already been made, lets retrieve rewards total stored on first claim of this interval rewardsTotal = getUint(keccak256("rewards.pool.claim.interval.total")); } // Done return rewardsTotal; } /** * Get the percentage this contract can claim in this interval * @return uint256 Rewards percentage this contract can claim in this interval */ function getClaimingContractPerc(string memory _claimingContract) override public view returns(uint256) { // Load contract RocketDAOProtocolSettingsRewardsInterface daoSettingsRewards = RocketDAOProtocolSettingsRewardsInterface(getContractAddress("rocketDAOProtocolSettingsRewards")); // Get the % amount allocated to this claim contract uint256 claimContractPerc = daoSettingsRewards.getRewardsClaimerPerc(_claimingContract); // Get the time the % was changed at, it will only use this % on the next interval if(daoSettingsRewards.getRewardsClaimerPercTimeUpdated(_claimingContract) > getClaimIntervalTimeStartComputed()) { // Ok so this percentage was set during this interval, we must use the current % assigned to the last claim and the new one will kick in the next interval // If this is 0, the contract hasn't made a claim yet and can only do so on the next interval claimContractPerc = getClaimingContractPercLast(_claimingContract); } // Done return claimContractPerc; } /** * Get the approx amount of rewards available for this claim interval per claiming contract * @return uint256 Rewards amount for current claim interval per claiming contract */ function getClaimingContractAllowance(string memory _claimingContract) override public view returns(uint256) { // Get the % amount this claim contract will get uint256 claimContractPerc = getClaimingContractPerc(_claimingContract); // How much rewards are available for this claim interval? uint256 claimIntervalRewardsTotal = getClaimIntervalRewardsTotal(); // How much this claiming contract is entitled to in perc uint256 contractClaimTotal = 0; // Check now if(claimContractPerc > 0 && claimIntervalRewardsTotal > 0) { // Calculate how much rewards this claimer will receive based on their claiming perc contractClaimTotal = claimContractPerc.mul(claimIntervalRewardsTotal).div(calcBase); } // Done return contractClaimTotal; } // How much this claimer is entitled to claim, checks parameters that claim() will check function getClaimAmount(string memory _claimingContract, address _claimerAddress, uint256 _claimerAmountPerc) override external view returns (uint256) { if (!getClaimingContractUserCanClaim(_claimingContract, _claimerAddress)) { return 0; } uint256 claimIntervalTimeStartComptued = getClaimIntervalTimeStartComputed(); uint256 claimingContractTotalClaimed = _getClaimingContractTotalClaimed(_claimingContract, claimIntervalTimeStartComptued); return _getClaimAmount(_claimingContract, _claimerAddress, _claimerAmountPerc, claimIntervalTimeStartComptued, claimingContractTotalClaimed); } function _getClaimAmount(string memory _claimingContract, address _claimerAddress, uint256 _claimerAmountPerc, uint256 _claimIntervalTimeStartComputed, uint256 _claimingContractTotalClaimed) private view returns (uint256) { // Get the total rewards available for this claiming contract uint256 contractClaimTotal = getClaimingContractAllowance(_claimingContract); // How much of the above that this claimer will receive uint256 claimerTotal = 0; // Are we good to proceed? if( contractClaimTotal > 0 && _claimerAmountPerc > 0 && _claimerAmountPerc <= 1 ether && _claimerAddress != address(0x0) && getClaimingContractEnabled(_claimingContract) && !getClaimingContractUserHasClaimed(_claimIntervalTimeStartComputed, _claimingContract, _claimerAddress)) { // Now calculate how much this claimer would receive claimerTotal = _claimerAmountPerc.mul(contractClaimTotal).div(calcBase); // Is it more than currently available + the amount claimed already for this claim interval? claimerTotal = claimerTotal.add(_claimingContractTotalClaimed) <= contractClaimTotal ? claimerTotal : 0; } // Done return claimerTotal; } // An account must be registered to claim from the rewards pool. They must wait one claim interval before they can collect. // Also keeps track of total function registerClaimer(address _claimerAddress, bool _enabled) override external onlyClaimContract { // The name of the claiming contract string memory contractName = getContractName(msg.sender); // Record the time they are registering at uint256 registeredTime = 0; // How many users are to be included in next interval uint256 claimersIntervalTotalUpdate = getClaimingContractUserTotalNext(contractName); // Ok register if(_enabled) { // Make sure they are not already registered require(getClaimingContractUserRegisteredTime(contractName, _claimerAddress) == 0, "Claimer is already registered"); // Update time registeredTime = block.timestamp; // Update the total registered claimers for next interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.add(1)); }else{ // Make sure they are already registered require(getClaimingContractUserRegisteredTime(contractName, _claimerAddress) != 0, "Claimer is not registered"); // Update the total registered claimers for next interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.sub(1)); } // Save the registered time setUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.time", contractName, _claimerAddress)), registeredTime); } // A claiming contract claiming for a user and the percentage of the rewards they are allowed to receive function claim(address _claimerAddress, address _toAddress, uint256 _claimerAmountPerc) override external onlyEnabledClaimContract { // The name of the claiming contract string memory contractName = getContractName(msg.sender); // Check to see if this registered claimer has waited one interval before collecting uint256 claimIntervalTime = getClaimIntervalTime(); require(_getClaimingContractUserCanClaim(contractName, _claimerAddress, claimIntervalTime), "Registered claimer is not registered to claim or has not waited one claim interval"); // RPL contract address address rplContractAddress = getContractAddress("rocketTokenRPL"); // RPL contract instance RocketTokenRPLInterface rplContract = RocketTokenRPLInterface(rplContractAddress); // Get the vault contract instance RocketVaultInterface rocketVault = RocketVaultInterface(getContractAddress("rocketVault")); // Get the start of the last claim interval as this may have just changed for a new interval beginning uint256 claimIntervalTimeStart = getClaimIntervalTimeStart(); uint256 claimIntervalTimeStartComputed = _getClaimIntervalTimeStartComputed(claimIntervalTimeStart, claimIntervalTime); uint256 claimIntervalsPassed = _getClaimIntervalsPassed(claimIntervalTimeStart, claimIntervalTime); // Is this the first claim of this interval? If so, set the rewards total for this interval if (claimIntervalsPassed > 0) { // Mint any new tokens from the RPL inflation rplContract.inflationMintTokens(); // Get how many tokens are in the reward pool to be available for this claim period setUint(keccak256("rewards.pool.claim.interval.total"), rocketVault.balanceOfToken("rocketRewardsPool", rplContract)); // Set this as the start of the new claim interval setUint(keccak256("rewards.pool.claim.interval.time.start"), claimIntervalTimeStartComputed); // Soon as we mint new tokens, send the DAO's share to it's claiming contract, then attempt to transfer them to the dao if possible uint256 daoClaimContractAllowance = getClaimingContractAllowance("rocketClaimDAO"); // Are we sending any? if (daoClaimContractAllowance > 0) { // Get the DAO claim contract address address daoClaimContractAddress = getContractAddress("rocketClaimDAO"); // Transfers the DAO's tokens to it's claiming contract from the rewards pool rocketVault.transferToken("rocketClaimDAO", rplContract, daoClaimContractAllowance); // Set the current claim percentage this contract is entitled to for this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.perc.current", "rocketClaimDAO")), getClaimingContractPerc("rocketClaimDAO")); // Store the total RPL rewards claim for this claiming contract in this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.total", claimIntervalTimeStartComputed, "rocketClaimDAO")), _getClaimingContractTotalClaimed("rocketClaimDAO", claimIntervalTimeStartComputed).add(daoClaimContractAllowance)); // Log it emit RPLTokensClaimed(daoClaimContractAddress, daoClaimContractAddress, daoClaimContractAllowance, block.timestamp); } } // Has anyone claimed from this contract so far in this interval? If not then set the interval settings for the contract if (_getClaimingContractTotalClaimed(contractName, claimIntervalTimeStartComputed) == 0) { // Get the amount allocated to this claim contract uint256 claimContractAllowance = getClaimingContractAllowance(contractName); // Make sure this is ok require(claimContractAllowance > 0, "Claiming contract must have an allowance of more than 0"); // Set the current claim percentage this contract is entitled too for this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.perc.current", contractName)), getClaimingContractPerc(contractName)); // Set the current claim allowance amount for this contract for this claim interval (if the claim amount is changed, it will kick in on the next interval) setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.allowance", contractName)), claimContractAllowance); // Set the current amount of claimers for this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.current", contractName)), getClaimingContractUserTotalNext(contractName)); } // Check if they have a valid claim amount uint256 claimingContractTotalClaimed = _getClaimingContractTotalClaimed(contractName, claimIntervalTimeStartComputed); uint256 claimAmount = _getClaimAmount(contractName, _claimerAddress, _claimerAmountPerc, claimIntervalTimeStartComputed, claimingContractTotalClaimed); // First initial checks require(claimAmount > 0, "Claimer is not entitled to tokens, they have already claimed in this interval or they are claiming more rewards than available to this claiming contract."); // Send tokens now rocketVault.withdrawToken(_toAddress, rplContract, claimAmount); // Store the claiming record for this interval and claiming contract setBool(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimer.address", claimIntervalTimeStartComputed, contractName, _claimerAddress)), true); // Store the total RPL rewards claim for this claiming contract in this interval setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.contract.total", claimIntervalTimeStartComputed, contractName)), claimingContractTotalClaimed.add(claimAmount)); // Store the last time a claim was made setUint(keccak256("rewards.pool.claim.interval.time.last"), block.timestamp); // Log it emit RPLTokensClaimed(getContractAddress(contractName), _claimerAddress, claimAmount, block.timestamp); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | 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 import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; interface RocketVaultInterface { function balanceOf(string memory _networkContractName) external view returns (uint256); function depositEther() external payable; function withdrawEther(uint256 _amount) external; function depositToken(string memory _networkContractName, IERC20 _tokenAddress, uint256 _amount) external; function withdrawToken(address _withdrawalAddress, IERC20 _tokenAddress, uint256 _amount) external; function balanceOfToken(string memory _networkContractName, IERC20 _tokenAddress) external view returns (uint256); function transferToken(string memory _networkContractName, IERC20 _tokenAddress, uint256 _amount) external; function burnToken(ERC20Burnable _tokenAddress, uint256 _amount) 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 RocketDAOProtocolSettingsRewardsInterface { function setSettingRewardsClaimer(string memory _contractName, uint256 _perc) external; function getRewardsClaimerPerc(string memory _contractName) external view returns (uint256); function getRewardsClaimerPercTimeUpdated(string memory _contractName) external view returns (uint256); function getRewardsClaimersPercTotal() external view returns (uint256); function getRewardsClaimIntervalTime() external view returns (uint256); } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | 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 RocketRewardsPoolInterface { function getRPLBalance() external view returns(uint256); function getClaimIntervalTimeStart() external view returns(uint256); function getClaimIntervalTimeStartComputed() external view returns(uint256); function getClaimIntervalsPassed() external view returns(uint256); function getClaimIntervalTime() external view returns(uint256); function getClaimTimeLastMade() external view returns(uint256); function getClaimIntervalRewardsTotal() external view returns(uint256); function getClaimingContractTotalClaimed(string memory _claimingContract) external view returns(uint256); function getClaimingContractUserTotalNext(string memory _claimingContract) external view returns(uint256); function getClaimingContractUserTotalCurrent(string memory _claimingContract) external view returns(uint256); function getClaimingContractUserHasClaimed(uint256 _claimIntervalStartTime, string memory _claimingContract, address _claimerAddress) external view returns(bool); function getClaimingContractUserCanClaim(string memory _claimingContract, address _claimerAddress) external view returns(bool); function getClaimingContractUserRegisteredTime(string memory _claimingContract, address _claimerAddress) external view returns(uint256); function getClaimingContractAllowance(string memory _claimingContract) external view returns(uint256); function getClaimingContractPerc(string memory _claimingContract) external view returns(uint256); function getClaimingContractPercLast(string memory _claimingContract) external view returns(uint256); function getClaimingContractExists(string memory _contractName) external view returns (bool); function getClaimingContractEnabled(string memory _contractName) external view returns (bool); function getClaimAmount(string memory _claimingContract, address _claimerAddress, uint256 _claimerAmountPerc) external view returns (uint256); function registerClaimer(address _claimerAddress, bool _enabled) external; function claim(address _claimerAddress, address _toAddress, uint256 _claimerAmount) 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 import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface RocketTokenRPLInterface is IERC20 { function getInflationCalcTime() external view returns(uint256); function getInflationIntervalTime() external view returns(uint256); function getInflationIntervalRate() external view returns(uint256); function getInflationIntervalsPassed() external view returns(uint256); function getInflationIntervalStartTime() external view returns(uint256); function getInflationRewardsContractAddress() external view returns(address); function inflationCalculate() external view returns (uint256); function inflationMintTokens() external returns (uint256); function swapTokens(uint256 _amount) external; }
Have they claimed already during this interval? return bool Returns true if they can claim during this interval/ Check per contract
function getClaimingContractUserHasClaimed(uint256 _claimIntervalStartTime, string memory _claimingContract, address _claimerAddress) override public view returns(bool) { return getBool(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimer.address", _claimIntervalStartTime, _claimingContract, _claimerAddress))); }
12,064,628
pragma solidity ^0.4.24; /** * @title AdvertisingInterface */ interface AdvertisingInterface { function incrementBetCounter() external returns (bool); } // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol /** * @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; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } contract developed { address public developer; /** * Constructor */ constructor() public { developer = msg.sender; } /** * @dev Checks only developer address is calling */ modifier onlyDeveloper { require(msg.sender == developer); _; } /** * @dev Allows developer to switch developer address * @param _developer The new developer address to be set */ function changeDeveloper(address _developer) public onlyDeveloper { developer = _developer; } /** * @dev Allows developer to withdraw ERC20 Token */ function withdrawToken(address tokenContractAddress) public onlyDeveloper { TokenERC20 _token = TokenERC20(tokenContractAddress); if (_token.balanceOf(this) > 0) { _token.transfer(developer, _token.balanceOf(this)); } } } /** * @title Advertising */ contract Advertising is developed, AdvertisingInterface { using SafeMath for uint256; address private incrementer; bool public paused; bool public contractKilled; uint256 public numCreatives; uint256 public numCreativeTypes; uint256 public maxCountPerCreativeType; uint256 public earnedBalance; struct Creative { bytes32 creativeId; address advertiser; uint256 creativeTypeId; // This determines the creative size and where we display it string name; uint256 weiBudget; uint256 weiPerBet; uint256 betCounter; int256 position; string url; string imageUrl; bool approved; uint256 createdOn; } struct CreativeType { string name; uint256 width; uint256 height; /** * @dev Where to display the creative * 1 = top * 2 = right * 3 = bottom * 4 = left */ uint256 position; bool active; } mapping (bytes32 => Creative) public creatives; mapping (bytes32 => uint256) private creativeIdLookup; mapping (uint256 => CreativeType) public creativeTypes; mapping (address => uint256) public advertiserPendingWithdrawals; mapping (uint256 => bytes32[]) public pendingCreativePosition; mapping (uint256 => bytes32[]) public approvedCreativePosition; /** * @dev Log when dev add new creative type */ event LogAddCreativeType(uint256 indexed creativeTypeId, string name, uint256 width, uint256 height, uint256 position); /** * @dev Log when dev activate/deactivate creative type */ event LogSetActiveCreativeType(uint256 creativeTypeId, bool active); /** * @dev Log when dev approves creative */ event LogApproveCreative(bytes32 indexed creativeId, address indexed advertiser, uint256 indexed creativeTypeId, int256 position); /** * @dev Log when dev set contract to emergency mode */ event LogEscapeHatch(); /** * @dev Log when advertiser creates creative */ event LogCreateCreative(bytes32 indexed creativeId, address indexed advertiser, uint256 indexed creativeTypeId, string name, uint256 weiBudget, uint256 weiPerBet, int256 position); /** * @dev Log when we refund creative * creativeStatus: * 0 = pending * 1 = approved * refundStatus: * 0 = failed * 1 = success */ event LogRefundCreative(bytes32 indexed creativeId, address indexed advertiser, uint256 refundAmount, uint256 creativeStatus, uint256 refundStatus); /** * @dev Log when advertiser withdraws balance from failed transfer * * Status: * 0 = failed * 1 = success */ event LogWithdrawBalance(address indexed advertiser, uint256 withdrawAmount, uint256 status); /** * @dev Log when we increment bet counter for a creative */ event LogIncrementBetCounter(bytes32 indexed creativeId, address indexed advertiser, uint256 numBets); /** * Constructor */ constructor(address _incrementer) public { devSetMaxCountPerCreativeType(10); devSetIncrementer(_incrementer); } /** * @dev Checks if the contract is currently alive */ modifier contractIsAlive { require(contractKilled == false); _; } /** * @dev Checks if contract is active */ modifier isActive { require(paused == false); _; } /** * @dev Check if creative is valid * @param creativeTypeId The creative type ID * @param name The name of this creative * @param weiBudget The budget for this creative * @param weiPerBet Cost per bet for an ad * @param url The url of the ad that we want to redirect to * @param imageUrl The image url for this ad */ modifier creativeIsValid(uint256 creativeTypeId, string name, uint256 weiBudget, uint256 weiPerBet, string url, string imageUrl) { require (creativeTypes[creativeTypeId].active == true && bytes(name).length > 0 && weiBudget > 0 && weiPerBet > 0 && weiBudget >= weiPerBet && bytes(url).length > 0 && bytes(imageUrl).length > 0 && (pendingCreativePosition[creativeTypeId].length < maxCountPerCreativeType || (pendingCreativePosition[creativeTypeId].length == maxCountPerCreativeType && weiPerBet > creatives[pendingCreativePosition[creativeTypeId][maxCountPerCreativeType-1]].weiPerBet) ) ); _; } /** * @dev Checks is caller is from incrementer */ modifier onlyIncrementer { require (msg.sender == incrementer); _; } /******************************************/ /* DEVELOPER ONLY METHODS */ /******************************************/ /** * @dev Dev sets address that is allowed to increment ad metrics * @param _incrementer The address to be set */ function devSetIncrementer(address _incrementer) public onlyDeveloper { incrementer = _incrementer; } /** * @dev Dev get incrementer address */ function devGetIncrementer() public onlyDeveloper constant returns (address) { return incrementer; } /** * @dev Dev sets max count per creative type * @param _maxCountPerCreativeType The max number of ad for a creative type */ function devSetMaxCountPerCreativeType(uint256 _maxCountPerCreativeType) public onlyDeveloper { require (_maxCountPerCreativeType > 0); maxCountPerCreativeType = _maxCountPerCreativeType; } /** * @dev Dev add creative type * @param name The name of this creative type * @param width The width of the creative * @param height The height of the creative * @param position The position of the creative */ function devAddCreativeType(string name, uint256 width, uint256 height, uint256 position) public onlyDeveloper { require (width > 0 && height > 0 && position > 0); // Increment num creative types numCreativeTypes++; CreativeType storage _creativeType = creativeTypes[numCreativeTypes]; // Store the info about this creative type _creativeType.name = name; _creativeType.width = width; _creativeType.height = height; _creativeType.position = position; _creativeType.active = true; emit LogAddCreativeType(numCreativeTypes, _creativeType.name, _creativeType.width, _creativeType.height, _creativeType.position); } /** * @dev Dev activate/deactivate creative type * @param creativeTypeId The creative type ID to be set * @param active The bool value to be set */ function devSetActiveCreativeType(uint256 creativeTypeId, bool active) public onlyDeveloper { creativeTypes[creativeTypeId].active = active; emit LogSetActiveCreativeType(creativeTypeId, active); } /** * @dev Allows dev to approve/disapprove a creative * @param creativeId The creative ID to be approved */ function devApproveCreative(bytes32 creativeId) public onlyDeveloper { Creative storage _creative = creatives[creativeId]; require (_creative.approved == false && _creative.position > -1 && _creative.createdOn > 0); _creative.approved = true; _removePending(creativeId); _insertSortApprovedCreative(_creative.creativeTypeId, _creative.creativeId); } /** * @dev Allows dev to withdraw earned balance */ function devWithdrawEarnedBalance() public onlyDeveloper returns (bool) { require (earnedBalance > 0); require (address(this).balance >= earnedBalance); uint256 withdrawAmount = earnedBalance; earnedBalance = 0; if (!developer.send(withdrawAmount)) { earnedBalance = withdrawAmount; return false; } else { return true; } } /** * @dev Dev ends the ad * @param creativeId The creative ID to be ended */ function devEndCreative(bytes32 creativeId) public onlyDeveloper { _endCreative(creativeId); } /** * @dev Allows developer to pause the contract * @param _paused The new paused value to be set */ function devSetPaused(bool _paused) public onlyDeveloper { paused = _paused; } /** * @dev Allows developer to trigger emergency mode. */ function escapeHatch() public onlyDeveloper contractIsAlive returns (bool) { contractKilled = true; if (earnedBalance > 0) { uint256 withdrawAmount = earnedBalance; earnedBalance = 0; if (!developer.send(withdrawAmount)) { earnedBalance = withdrawAmount; } } if (numCreativeTypes > 0) { for (uint256 i=1; i <= numCreativeTypes; i++) { /* * First, we refund all the pending creatives. * Instead of sending the refund amount, we ask advertisers to withdraw the refunded amount themselves */ uint256 creativeCount = pendingCreativePosition[i].length; if (creativeCount > 0) { for (uint256 j=0; j < creativeCount; j++) { Creative memory _creative = creatives[pendingCreativePosition[i][j]]; // let advertiser withdraw via advertiserPendingWithdrawals advertiserPendingWithdrawals[_creative.advertiser] = advertiserPendingWithdrawals[_creative.advertiser].add(_creative.weiBudget); } } /* * Then, we refund all the approved creatives */ creativeCount = approvedCreativePosition[i].length; if (creativeCount > 0) { for (j=0; j < creativeCount; j++) { _creative = creatives[approvedCreativePosition[i][j]]; uint256 refundAmount = _creative.weiBudget.sub(_creative.betCounter.mul(_creative.weiPerBet)); // let advertiser withdraw via advertiserPendingWithdrawals advertiserPendingWithdrawals[_creative.advertiser] = advertiserPendingWithdrawals[_creative.advertiser].add(refundAmount); } } } } emit LogEscapeHatch(); return true; } /******************************************/ /* INCREMENT ADDRESS METHODS */ /******************************************/ function incrementBetCounter() public onlyIncrementer contractIsAlive isActive returns (bool) { if (numCreativeTypes > 0) { for (uint256 i=1; i <= numCreativeTypes; i++) { CreativeType memory _creativeType = creativeTypes[i]; uint256 creativeCount = approvedCreativePosition[i].length; if (_creativeType.active == false || creativeCount == 0) { continue; } Creative storage _creative = creatives[approvedCreativePosition[i][0]]; _creative.betCounter++; emit LogIncrementBetCounter(_creative.creativeId, _creative.advertiser, _creative.betCounter); uint256 totalSpent = _creative.weiPerBet.mul(_creative.betCounter); if (totalSpent > _creative.weiBudget) { earnedBalance = earnedBalance.add(_creative.weiBudget.sub(_creative.weiPerBet.mul(_creative.betCounter.sub(1)))); _removeApproved(_creative.creativeId); } else { earnedBalance = earnedBalance.add(_creative.weiPerBet); } } } return true; } /******************************************/ /* PUBLIC METHODS */ /******************************************/ /** * @dev Advertiser submits an ad * @param creativeTypeId The creative type ID (determines where we display it) * @param name The name of this creative * @param weiPerBet Cost per bet for an ad * @param url The url of the ad that we want to redirect to * @param imageUrl The image url for this ad */ function createCreative(uint256 creativeTypeId, string name, uint256 weiPerBet, string url, string imageUrl) public payable contractIsAlive isActive creativeIsValid(creativeTypeId, name, msg.value, weiPerBet, url, imageUrl) { // Increment num creatives numCreatives++; // Generate ID for this creative bytes32 creativeId = keccak256(abi.encodePacked(this, msg.sender, numCreatives)); Creative storage _creative = creatives[creativeId]; // Store the info about this creative _creative.creativeId = creativeId; _creative.advertiser = msg.sender; _creative.creativeTypeId = creativeTypeId; _creative.name = name; _creative.weiBudget = msg.value; _creative.weiPerBet = weiPerBet; _creative.url = url; _creative.imageUrl = imageUrl; _creative.createdOn = now; // Decide which position this creative is _insertSortPendingCreative(creativeTypeId, creativeId); } /** * @dev Advertiser ends the ad * @param creativeId The creative ID to be ended */ function endCreative(bytes32 creativeId) public contractIsAlive isActive { Creative storage _creative = creatives[creativeId]; require (_creative.advertiser == msg.sender); _endCreative(creativeId); } /** * @dev withdraws balance in case of a failed refund or failed win send */ function withdrawPendingTransactions() public { uint256 withdrawAmount = advertiserPendingWithdrawals[msg.sender]; require (withdrawAmount > 0); require (address(this).balance >= withdrawAmount); advertiserPendingWithdrawals[msg.sender] = 0; // External call to untrusted contract if (msg.sender.send(withdrawAmount)) { emit LogWithdrawBalance(msg.sender, withdrawAmount, 1); } else { /* * If send failed, revert advertiserPendingWithdrawals[msg.sender] = 0 * so that player can try to withdraw again later */ advertiserPendingWithdrawals[msg.sender] = withdrawAmount; emit LogWithdrawBalance(msg.sender, withdrawAmount, 0); } } /******************************************/ /* INTERNAL METHODS */ /******************************************/ /** * @dev Insert the newly submitted creative and sort the array to determine its position. * If the array container length is greater than max count, then we want to refund the last element * @param creativeTypeId The creative type ID of this ad * @param creativeId The creative ID of this ad */ function _insertSortPendingCreative(uint256 creativeTypeId, bytes32 creativeId) internal { pendingCreativePosition[creativeTypeId].push(creativeId); uint256 pendingCount = pendingCreativePosition[creativeTypeId].length; bytes32[] memory copyArray = new bytes32[](pendingCount); for (uint256 i=0; i<pendingCount; i++) { copyArray[i] = pendingCreativePosition[creativeTypeId][i]; } uint256 value; bytes32 key; for (i = 1; i < copyArray.length; i++) { key = copyArray[i]; value = creatives[copyArray[i]].weiPerBet; for (uint256 j=i; j > 0 && creatives[copyArray[j-1]].weiPerBet < value; j--) { copyArray[j] = copyArray[j-1]; } copyArray[j] = key; } for (i=0; i<pendingCount; i++) { pendingCreativePosition[creativeTypeId][i] = copyArray[i]; creatives[copyArray[i]].position = int(i); } Creative memory _creative = creatives[creativeId]; emit LogCreateCreative(_creative.creativeId, _creative.advertiser, _creative.creativeTypeId, _creative.name, _creative.weiBudget, _creative.weiPerBet, _creative.position); // If total count is more than max count, then we want to refund the last ad if (pendingCount > maxCountPerCreativeType) { bytes32 removeCreativeId = pendingCreativePosition[creativeTypeId][pendingCount-1]; creatives[removeCreativeId].position = -1; delete pendingCreativePosition[creativeTypeId][pendingCount-1]; pendingCreativePosition[creativeTypeId].length--; _refundPending(removeCreativeId); } } /** * @dev Refund the pending creative * @param creativeId The creative ID of this ad */ function _refundPending(bytes32 creativeId) internal { Creative memory _creative = creatives[creativeId]; require (address(this).balance >= _creative.weiBudget); require (_creative.position == -1); if (!_creative.advertiser.send(_creative.weiBudget)) { emit LogRefundCreative(_creative.creativeId, _creative.advertiser, _creative.weiBudget, 0, 0); // If send failed, let advertiser withdraw via advertiserPendingWithdrawals advertiserPendingWithdrawals[_creative.advertiser] = advertiserPendingWithdrawals[_creative.advertiser].add(_creative.weiBudget); } else { emit LogRefundCreative(_creative.creativeId, _creative.advertiser, _creative.weiBudget, 0, 1); } } /** * @dev Insert the newly approved creative and sort the array to determine its position. * If the array container length is greater than max count, then we want to refund the last element. * @param creativeTypeId The creative type ID of this ad * @param creativeId The creative ID of this ad */ function _insertSortApprovedCreative(uint256 creativeTypeId, bytes32 creativeId) internal { approvedCreativePosition[creativeTypeId].push(creativeId); uint256 approvedCount = approvedCreativePosition[creativeTypeId].length; bytes32[] memory copyArray = new bytes32[](approvedCount); for (uint256 i=0; i<approvedCount; i++) { copyArray[i] = approvedCreativePosition[creativeTypeId][i]; } uint256 value; bytes32 key; for (i = 1; i < copyArray.length; i++) { key = copyArray[i]; value = creatives[copyArray[i]].weiPerBet; for (uint256 j=i; j > 0 && creatives[copyArray[j-1]].weiPerBet < value; j--) { copyArray[j] = copyArray[j-1]; } copyArray[j] = key; } for (i=0; i<approvedCount; i++) { approvedCreativePosition[creativeTypeId][i] = copyArray[i]; creatives[copyArray[i]].position = int(i); } Creative memory _creative = creatives[creativeId]; emit LogApproveCreative(_creative.creativeId, _creative.advertiser, _creative.creativeTypeId, _creative.position); // If total count is more than max count, then we want to refund the last ad if (approvedCount > maxCountPerCreativeType) { bytes32 removeCreativeId = approvedCreativePosition[creativeTypeId][approvedCount-1]; creatives[removeCreativeId].position = -1; delete approvedCreativePosition[creativeTypeId][approvedCount-1]; approvedCreativePosition[creativeTypeId].length--; _refundApproved(removeCreativeId); } } /** * @dev Refund the approved creative * @param creativeId The creative ID of this ad */ function _refundApproved(bytes32 creativeId) internal { Creative memory _creative = creatives[creativeId]; uint256 refundAmount = _creative.weiBudget.sub(_creative.betCounter.mul(_creative.weiPerBet)); require (address(this).balance >= refundAmount); require (_creative.position == -1); if (!_creative.advertiser.send(refundAmount)) { emit LogRefundCreative(_creative.creativeId, _creative.advertiser, refundAmount, 1, 0); // If send failed, let advertiser withdraw via advertiserPendingWithdrawals advertiserPendingWithdrawals[_creative.advertiser] = advertiserPendingWithdrawals[_creative.advertiser].add(refundAmount); } else { emit LogRefundCreative(_creative.creativeId, _creative.advertiser, refundAmount, 1, 1); } } /** * @dev End creative * @param creativeId The creative ID to be removed */ function _endCreative(bytes32 creativeId) internal { Creative storage _creative = creatives[creativeId]; require (_creative.position > -1 && _creative.createdOn > 0); if (_creative.approved == false) { _removePending(creativeId); _refundPending(creativeId); } else { _removeApproved(creativeId); _refundApproved(creativeId); } } /** * @dev Remove element in pending creatives array * @param creativeId The creative ID to be removed */ function _removePending(bytes32 creativeId) internal { Creative storage _creative = creatives[creativeId]; uint256 pendingCount = pendingCreativePosition[_creative.creativeTypeId].length; if (_creative.position >= int256(pendingCount)) return; for (uint256 i = uint256(_creative.position); i < pendingCount-1; i++){ pendingCreativePosition[_creative.creativeTypeId][i] = pendingCreativePosition[_creative.creativeTypeId][i+1]; creatives[pendingCreativePosition[_creative.creativeTypeId][i]].position = int256(i); } _creative.position = -1; delete pendingCreativePosition[_creative.creativeTypeId][pendingCount-1]; pendingCreativePosition[_creative.creativeTypeId].length--; } /** * @dev Remove element in approved creatives array * @param creativeId The creative ID to be removed */ function _removeApproved(bytes32 creativeId) internal { Creative storage _creative = creatives[creativeId]; uint256 approvedCount = approvedCreativePosition[_creative.creativeTypeId].length; if (_creative.position >= int256(approvedCount)) return; for (uint256 i = uint256(_creative.position); i < approvedCount-1; i++){ approvedCreativePosition[_creative.creativeTypeId][i] = approvedCreativePosition[_creative.creativeTypeId][i+1]; creatives[approvedCreativePosition[_creative.creativeTypeId][i]].position = int256(i); } _creative.position = -1; delete approvedCreativePosition[_creative.creativeTypeId][approvedCount-1]; approvedCreativePosition[_creative.creativeTypeId].length--; } }
Dev sets max count per creative type _maxCountPerCreativeType The max number of ad for a creative type/
function devSetMaxCountPerCreativeType(uint256 _maxCountPerCreativeType) public onlyDeveloper { require (_maxCountPerCreativeType > 0); maxCountPerCreativeType = _maxCountPerCreativeType; }
12,874,089
pragma solidity 0.8.6; import "./IBondingCurve.sol"; contract BuySell { constructor( IErc20BondingCurve _usdc20BondingCurve, IETHBondingCurve _ethBondingCurve ) { usdc20BondingCurve = _usdc20BondingCurve; ethBondingCurve = _ethBondingCurve; } IErc20BondingCurve usdc20BondingCurve; IETHBondingCurve ethBondingCurve; function buysellInOneTxnETH(uint256 tokenAmount) public payable { ethBondingCurve.buy{value:msg.value}(tokenAmount); ethBondingCurve.sell(tokenAmount); } function buysellInOneTxnUSDC(uint256 tokenAmount) public { usdc20BondingCurve.buy(tokenAmount); usdc20BondingCurve.sell(tokenAmount); } } pragma solidity 0.8.6; interface IETHBondingCurve { function buy(uint256 tokenAmount) external payable; function sell(uint256 tokenAmount) external; } interface IErc20BondingCurve { function buy(uint256 tokenAmount) external; function sell(uint256 tokenAmount) external; } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./Linear.sol"; import "./IBondingCurve.sol"; contract ETHBondingCurve is LinearBondingCurve, IETHBondingCurve { using SafeERC20 for IERC20; IERC20 public immutable token; uint256 public soldAmount; uint256 public comissionShare = 20; address payable public hegicDevelopmentFund; event Bought(address indexed account, uint256 amount, uint256 ethAmount); event Sold( address indexed account, uint256 amount, uint256 ethAmount, uint256 comission ); constructor( IERC20 _token, uint256 k, uint256 startPrice ) LinearBondingCurve(k, startPrice) { token = _token; hegicDevelopmentFund = payable(msg.sender); _setupRole(LBC_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } function buy(uint256 tokenAmount) external payable override { uint256 nextSold = soldAmount + tokenAmount; uint256 ethAmount = s(soldAmount, nextSold); soldAmount = nextSold; require(msg.value >= ethAmount, "Value is too small"); token.safeTransfer(msg.sender, tokenAmount); if (msg.value > ethAmount) payable(msg.sender).transfer(msg.value - ethAmount); emit Bought(msg.sender, tokenAmount, ethAmount); } function sell(uint256 tokenAmount) external override { uint256 nextSold = soldAmount - tokenAmount; uint256 ethAmount = s(nextSold, soldAmount); uint256 comission = (ethAmount * comissionShare) / 100; uint256 refund = ethAmount - comission; require(comission > 0, "Amount is too small"); soldAmount = nextSold; token.safeTransferFrom(msg.sender, address(this), tokenAmount); hegicDevelopmentFund.transfer(comission); payable(msg.sender).transfer(refund); emit Sold(msg.sender, tokenAmount, refund, comission); } function setHDF(address payable value) external onlyRole(DEFAULT_ADMIN_ROLE) { hegicDevelopmentFund = value; } function setCommissionShare(uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) { comissionShare = value; } function destruct() external onlyRole(DEFAULT_ADMIN_ROLE) { selfdestruct(hegicDevelopmentFund); } function withdawERC20(IERC20 token) external onlyRole(DEFAULT_ADMIN_ROLE) { token.transfer(hegicDevelopmentFund, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2020 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import "@openzeppelin/contracts/access/AccessControl.sol"; contract LinearBondingCurve is AccessControl { uint256 public K; // Inf uint256 public START_PRICE; // 0.000018e8 bytes32 public constant LBC_ADMIN_ROLE = keccak256("LBC_ADMIN_ROLE"); constructor(uint256 k, uint256 startPrice) public { K = k; START_PRICE = startPrice; } function s(uint256 x0, uint256 x1) public view returns (uint256) { require(x1 > x0, "Hegic Amount need higher then 0"); return (((x1 + x0) * (x1 - x0)) / 2 / K + START_PRICE * (x1 - x0)) / 1e18; } function setParams(uint256 _K, uint256 _START_PRICE) external onlyRole(LBC_ADMIN_ROLE) { K = _K; START_PRICE = _START_PRICE; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @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()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ pragma solidity ^0.8.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "../Interfaces/Interfaces.sol"; import "hardhat/console.sol"; contract HegicCouponPool is AccessControl, IERC721Receiver { using SafeERC20 for IERC20; IERC20 immutable USDC; uint256 constant AUCTION_DURATION = 3 days; uint256 constant SUBSCRIPTION_DURATION = 30 days; address public undistributedCouponRecipient; Coupon[] public coupons; address[] public poolsAvailable; mapping(IHegicPool => bool) isHegicPool; event Provided( uint256 indexed couponID, address indexed account, uint256 amount ); event SubscriptionClosed(uint256 indexed couponID); event Claimed( uint256 indexed couponID, address indexed liquidityProvider, uint256 amount ); event Withdrawn( uint256 indexed couponID, address indexed liquidityProvider, uint128 amount, uint128 coupon ); enum CouponState {Invalid, LiveAuction, Close} struct ProvidedLiquidity { uint248 amount; bool hasUnclaimedCoupon; } struct Coupon { CouponState state; uint256 start; uint256 amount; uint256 coupon; uint256 deposited; mapping(address => ProvidedLiquidity) provided; } constructor(IERC20 USDC_, IHegicPool[] memory hegicPools) { USDC = USDC_; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); undistributedCouponRecipient = msg.sender; for (uint8 i; i < hegicPools.length; i++) isHegicPool[hegicPools[i]] = true; } function initNewCoupon( uint256 start, uint256 amount, uint256 coupon ) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 couponID = coupons.length; coupons.push(); coupons[couponID].state = CouponState.LiveAuction; coupons[couponID].start = start; coupons[couponID].amount = amount; coupons[couponID].coupon = coupon; USDC.safeTransferFrom(msg.sender, address(this), coupon); } function _closeSubscription(uint256 couponID) internal { Coupon storage c = coupons[couponID]; require( c.state == CouponState.LiveAuction, "Error: Coupon auction isn't live" ); c.state = CouponState.Close; uint256 auctionStart = c.start - AUCTION_DURATION; uint256 duration = block.timestamp - auctionStart; if (duration > AUCTION_DURATION) duration = AUCTION_DURATION; uint256 needCoupon = (c.coupon * duration * c.deposited) / AUCTION_DURATION / c.amount; if (c.coupon > needCoupon) { USDC.safeTransfer( undistributedCouponRecipient, c.coupon - needCoupon ); c.coupon = needCoupon; } emit SubscriptionClosed(couponID); } function _sendCoupon(uint256 couponID, address liquidityProvider) internal { Coupon storage c = coupons[couponID]; require(c.start < block.timestamp, "Error: Coupon auction isn't live"); require( c.provided[liquidityProvider].hasUnclaimedCoupon, "Error: Haven't participated in the coupon auction" ); c.provided[liquidityProvider].hasUnclaimedCoupon = false; uint256 amount = c.provided[liquidityProvider].amount; uint256 couponShare = (c.coupon * amount) / c.deposited; USDC.transfer(liquidityProvider, couponShare); emit Claimed(couponID, liquidityProvider, couponShare); } function provideLiquidity(uint256 couponID, uint248 amount) external { Coupon storage c = coupons[couponID]; require(block.timestamp < c.start, "Error: Coupon auction isn't live"); require( c.state == CouponState.LiveAuction, "Error: Coupon auction isn't live" ); require(c.amount - c.deposited >= amount, "Error: Incorrect amount"); c.provided[msg.sender].amount += amount; c.provided[msg.sender].hasUnclaimedCoupon = true; c.deposited += amount; USDC.safeTransferFrom(msg.sender, address(this), amount); if (c.deposited == c.amount) _closeSubscription(couponID); emit Provided(couponID, msg.sender, amount); } function withdrawLiquidity(uint256 couponID, address liquidityProvider) external { Coupon storage c = coupons[couponID]; uint256 amount = c.provided[liquidityProvider].amount; require( c.start + SUBSCRIPTION_DURATION < block.timestamp, "Error: Coupon auction isn't live" ); require(amount != 0, "Error: Incorrect amount"); uint256 couponShare = 0; if (c.provided[liquidityProvider].hasUnclaimedCoupon) couponShare = (c.coupon * amount) / c.deposited; delete c.provided[liquidityProvider]; USDC.safeTransfer(liquidityProvider, amount + couponShare); emit Withdrawn( couponID, liquidityProvider, uint128(amount), uint128(couponShare) ); } function sendLiquidityToPool(IHegicPool pool, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { if (USDC.allowance(address(this), address(pool)) < amount) USDC.approve(address(pool), type(uint256).max); pool.provideFrom(address(this), amount, false, 0); } function closeTranche(IHegicPool pool, uint256 trancheID) external onlyRole(DEFAULT_ADMIN_ROLE) { (, , uint256 provided, , ) = pool.tranches(trancheID); uint256 withdrawn = pool.withdraw(trancheID); if (withdrawn > provided) USDC.safeTransfer( undistributedCouponRecipient, withdrawn - provided ); if (withdrawn < provided) USDC.safeTransferFrom( msg.sender, address(this), provided - withdrawn ); } function closeSubscription(uint256 couponID) external { Coupon storage c = coupons[couponID]; require(c.start < block.timestamp, "Error: 7..."); _closeSubscription(couponID); } function buyoutTranche(IHegicPool pool, uint256 trancheID) external onlyRole(DEFAULT_ADMIN_ROLE) { (, , uint256 provided, , ) = pool.tranches(trancheID); pool.safeTransferFrom(address(this), msg.sender, trancheID); USDC.safeTransferFrom(msg.sender, address(this), provided); } function claim(uint256 couponID, address liquidityProvider) external { _sendCoupon(couponID, liquidityProvider); } function provided(uint256 couponID, address liquidityProvider) external view returns (uint256 provided, bool hasCoupon) { provided = coupons[couponID].provided[liquidityProvider].amount; hasCoupon = coupons[couponID].provided[liquidityProvider] .hasUnclaimedCoupon; } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external override returns (bytes4) { return IERC721Receiver.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; // /** // * @author 0mllwntrmt3 // * @title Hegic Protocol V8888 Interface // * @notice The interface for the price calculator, // * options, pools and staking contracts. // **/ /** * @notice The interface fot the contract that calculates * the options prices (the premiums) that are adjusted * through balancing the `ImpliedVolRate` parameter. **/ interface IPriceCalculator { /** * @param period The option period * @param amount The option size * @param strike The option strike **/ function calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) external view returns (uint256 settlementFee, uint256 premium); } /** * @notice The interface for the contract that manages pools and the options parameters, * accumulates the funds from the liquidity providers and makes the withdrawals for them, * sells the options contracts to the options buyers and collateralizes them, * exercises the ITM (in-the-money) options with the unrealized P&L and settles them, * unlocks the expired options and distributes the premiums among the liquidity providers. **/ interface IHegicPool is IERC721, IPriceCalculator { enum OptionState {Invalid, Active, Exercised, Expired} enum TrancheState {Invalid, Open, Closed} /** * @param state The state of the option: Invalid, Active, Exercised, Expired * @param strike The option strike * @param amount The option size * @param lockedAmount The option collateral size locked * @param expired The option expiration timestamp * @param hedgePremium The share of the premium paid for hedging from the losses * @param unhedgePremium The share of the premium paid to the hedged liquidity provider **/ struct Option { OptionState state; uint256 strike; uint256 amount; uint256 lockedAmount; uint256 expired; uint256 hedgePremium; uint256 unhedgePremium; } /** * @param state The state of the liquidity tranche: Invalid, Open, Closed * @param share The liquidity provider's share in the pool * @param amount The size of liquidity provided * @param creationTimestamp The liquidity deposit timestamp * @param hedged The liquidity tranche type: hedged or unhedged (classic) **/ struct Tranche { TrancheState state; uint256 share; uint256 amount; uint256 creationTimestamp; bool hedged; } /** * @param id The ERC721 token ID linked to the option * @param settlementFee The part of the premium that * is distributed among the HEGIC staking participants * @param premium The part of the premium that * is distributed among the liquidity providers **/ event Acquired(uint256 indexed id, uint256 settlementFee, uint256 premium); /** * @param id The ERC721 token ID linked to the option * @param profit The profits of the option if exercised **/ event Exercised(uint256 indexed id, uint256 profit); /** * @param id The ERC721 token ID linked to the option **/ event Expired(uint256 indexed id); /** * @param account The liquidity provider's address * @param trancheID The liquidity tranche ID **/ event Withdrawn( address indexed account, uint256 indexed trancheID, uint256 amount ); /** * @param id The ERC721 token ID linked to the option **/ function unlock(uint256 id) external; /** * @param id The ERC721 token ID linked to the option **/ function exercise(uint256 id) external; function setLockupPeriod(uint256, uint256) external; /** * @param value The hedging pool address **/ function setHedgePool(address value) external; /** * @param trancheID The liquidity tranche ID * @return amount The liquidity to be received with * the positive or negative P&L earned or lost during * the period of holding the liquidity tranche considered **/ function withdraw(uint256 trancheID) external returns (uint256 amount); function pricer() external view returns (IPriceCalculator); /** * @return amount The unhedged liquidity size * (unprotected from the losses on selling the options) **/ function unhedgedBalance() external view returns (uint256 amount); /** * @return amount The hedged liquidity size * (protected from the losses on selling the options) **/ function hedgedBalance() external view returns (uint256 amount); /** * @param account The liquidity provider's address * @param amount The size of the liquidity tranche * @param hedged The type of the liquidity tranche * @param minShare The minimum share in the pool of the user **/ function provideFrom( address account, uint256 amount, bool hedged, uint256 minShare ) external returns (uint256 share); /** * @param holder The option buyer address * @param period The option period * @param amount The option size * @param strike The option strike **/ function sellOption( address holder, uint256 period, uint256 amount, uint256 strike ) external returns (uint256 id); /** * @param trancheID The liquidity tranche ID * @return amount The amount to be received after the withdrawal **/ function withdrawWithoutHedge(uint256 trancheID) external returns (uint256 amount); /** * @return amount The total liquidity provided into the pool **/ function totalBalance() external view returns (uint256 amount); /** * @return amount The total liquidity locked in the pool **/ function lockedAmount() external view returns (uint256 amount); function token() external view returns (IERC20); /** * @return state The state of the option: Invalid, Active, Exercised, Expired * @return strike The option strike * @return amount The option size * @return lockedAmount The option collateral size locked * @return expired The option expiration timestamp * @return hedgePremium The share of the premium paid for hedging from the losses * @return unhedgePremium The share of the premium paid to the hedged liquidity provider **/ function options(uint256 id) external view returns ( OptionState state, uint256 strike, uint256 amount, uint256 lockedAmount, uint256 expired, uint256 hedgePremium, uint256 unhedgePremium ); /** * @return state The state of the liquidity tranche: Invalid, Open, Closed * @return share The liquidity provider's share in the pool * @return amount The size of liquidity provided * @return creationTimestamp The liquidity deposit timestamp * @return hedged The liquidity tranche type: hedged or unhedged (classic) **/ function tranches(uint256 id) external view returns ( TrancheState state, uint256 share, uint256 amount, uint256 creationTimestamp, bool hedged ); } interface ISettlementFeeRecipient { function distributeUnrealizedRewards() external; } /** * @notice The interface for the contract that stakes HEGIC tokens * through buying microlots (any amount of HEGIC tokens per microlot) * and staking lots (888,000 HEGIC per lot), accumulates the staking * rewards (settlement fees) and distributes the staking rewards among * the microlots and staking lots holders (should be claimed manually). **/ interface IHegicStaking is ISettlementFeeRecipient { event Claim(address indexed account, uint256 amount); event Profit(uint256 amount); event MicroLotsAcquired(address indexed account, uint256 amount); event MicroLotsSold(address indexed account, uint256 amount); function claimProfits(address account) external returns (uint256 profit); function buyStakingLot(uint256 amount) external; function sellStakingLot(uint256 amount) external; function profitOf(address account) external view returns (uint256); } interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 value) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // 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.7.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 ); } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @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); } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/Interfaces.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract SettlementFeeDistributor is ISettlementFeeRecipient, Ownable { using SafeERC20 for IERC20; ISettlementFeeRecipient public immutable staking; IERC20 public immutable token; address public immutable HLTPs; uint128 public totalShare = 24; uint128 public stakingShare = 19; constructor( ISettlementFeeRecipient staking_, IERC20 token_, address HLTPs_ ) { staking = staking_; token = token_; HLTPs = HLTPs_; } function setShares(uint128 stakingShare_, uint128 totalShare_) external onlyOwner { require( totalShare_ != 0, "SettlementFeeDistributor: totalShare is zero" ); require( stakingShare_ <= totalShare, "SettlementFeeDistributor: stakingShare is too large" ); totalShare = totalShare_; stakingShare = stakingShare_; } function distributeUnrealizedRewards() external override { uint256 amount = token.balanceOf(address(this)); require(amount > 0, "SettlementFeeDistributor: Amount is zero"); uint256 stakingAmount = (amount * stakingShare) / totalShare; token.safeTransfer(HLTPs, amount - stakingAmount); token.safeTransfer(address(staking), stakingAmount); staking.distributeUnrealizedRewards(); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../Interfaces/Interfaces.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Staking Contract * @notice The contract that stakes the HEGIC tokens through * buying the microlots (any amount of HEGIC tokens per microlot) * and the staking lots (888,000 HEGIC per lot), accumulates the staking * rewards (settlement fees) and distributes the staking rewards among * the microlots and staking lots holders (should be claimed manually). **/ contract HegicStaking is ERC20, IHegicStaking { using SafeERC20 for IERC20; IERC20 public immutable HEGIC; IERC20 public immutable token; uint256 public constant STAKING_LOT_PRICE = 888_000e18; uint256 internal constant ACCURACY = 1e30; uint256 internal realisedBalance; uint256 public microLotsTotal = 0; mapping(address => uint256) public microBalance; uint256 public totalProfit = 0; mapping(address => uint256) internal lastProfit; uint256 public microLotsProfits = 0; mapping(address => uint256) internal lastMicroLotProfits; mapping(address => uint256) internal savedProfit; uint256 public classicLockupPeriod = 1 days; uint256 public microLockupPeriod = 1 days; mapping(address => uint256) public lastBoughtTimestamp; mapping(address => uint256) public lastMicroBoughtTimestamp; mapping(address => bool) public _revertTransfersInLockUpPeriod; constructor( ERC20 _hegic, ERC20 _token, string memory name, string memory short ) ERC20(name, short) { HEGIC = _hegic; token = _token; } function decimals() public pure override returns (uint8) { return 0; } /** * @notice Used by the HEGIC microlots holders * or staking lots holders for claiming * the accumulated staking rewards. **/ function claimProfits(address account) external override returns (uint256 profit) { saveProfits(account); profit = savedProfit[account]; require(profit > 0, "Zero profit"); savedProfit[account] = 0; realisedBalance -= profit; token.safeTransfer(account, profit); emit Claim(account, profit); } /** * @notice Used for staking any amount of the HEGIC tokens * higher than zero in the form of buying the microlot * for receiving a pro rata share of 20% of the total staking * rewards (settlement fees) generated by the protocol. **/ function buyMicroLot(uint256 amount) external { require(amount > 0, "Amount is zero"); saveProfits(msg.sender); lastMicroBoughtTimestamp[msg.sender] = block.timestamp; microLotsTotal += amount; microBalance[msg.sender] += amount; HEGIC.safeTransferFrom(msg.sender, address(this), amount); emit MicroLotsAcquired(msg.sender, amount); } /** * @notice Used for unstaking the HEGIC tokens * in the form of selling the microlot. **/ function sellMicroLot(uint256 amount) external { require(amount > 0, "Amount is zero"); require( lastMicroBoughtTimestamp[msg.sender] + microLockupPeriod < block.timestamp, "The action is suspended due to the lockup" ); saveProfits(msg.sender); microLotsTotal -= amount; microBalance[msg.sender] -= amount; HEGIC.safeTransfer(msg.sender, amount); emit MicroLotsSold(msg.sender, amount); } /** * @notice Used for staking the fixed amount of 888,000 HEGIC * tokens in the form of buying the staking lot (transferrable) * for receiving a pro rata share of 80% of the total staking * rewards (settlement fees) generated by the protocol. **/ function buyStakingLot(uint256 amount) external override { lastBoughtTimestamp[msg.sender] = block.timestamp; require(amount > 0, "Amount is zero"); _mint(msg.sender, amount); HEGIC.safeTransferFrom( msg.sender, address(this), amount * STAKING_LOT_PRICE ); } /** * @notice Used for unstaking 888,000 HEGIC * tokens in the form of selling the staking lot. **/ function sellStakingLot(uint256 amount) external override lockupFree { _burn(msg.sender, amount); HEGIC.safeTransfer(msg.sender, amount * STAKING_LOT_PRICE); } function revertTransfersInLockUpPeriod(bool value) external { _revertTransfersInLockUpPeriod[msg.sender] = value; } /** * @notice Returns the amount of unclaimed staking rewards. **/ function profitOf(address account) external view override returns (uint256) { (uint256 profit, uint256 micro) = getUnsavedProfits(account); return savedProfit[account] + profit + micro; } /** * @notice Used for calculating the amount of accumulated * staking rewards before the share of the staking participant * changes higher (buying more microlots or staking lots) * or lower (selling more microlots or staking lots). **/ function getUnsavedProfits(address account) internal view returns (uint256 total, uint256 micro) { total = ((totalProfit - lastProfit[account]) * balanceOf(account)) / ACCURACY; micro = ((microLotsProfits - lastMicroLotProfits[account]) * microBalance[account]) / ACCURACY; } /** * @notice Used for saving the amount of accumulated * staking rewards before the staking participant's share * changes higher (buying more microlots or staking lots) * or lower (selling more microlots or staking lots). **/ function saveProfits(address account) internal { (uint256 unsaved, uint256 micro) = getUnsavedProfits(account); lastProfit[account] = totalProfit; lastMicroLotProfits[account] = microLotsProfits; savedProfit[account] += unsaved; savedProfit[account] += micro; } function _beforeTokenTransfer( address from, address to, uint256 ) internal override { if (from != address(0)) saveProfits(from); if (to != address(0)) saveProfits(to); if ( lastBoughtTimestamp[from] + classicLockupPeriod > block.timestamp && lastBoughtTimestamp[from] > lastBoughtTimestamp[to] ) { require( !_revertTransfersInLockUpPeriod[to], "The recipient does not agree to accept the locked funds" ); lastBoughtTimestamp[to] = lastBoughtTimestamp[from]; } } /** * @notice Used for distributing the staking rewards * among the microlots and staking lots holders. **/ function distributeUnrealizedRewards() external override { uint256 amount = token.balanceOf(address(this)) - realisedBalance; realisedBalance += amount; uint256 _totalSupply = totalSupply(); if (microLotsTotal + _totalSupply > 0) { if (microLotsTotal == 0) { totalProfit += (amount * ACCURACY) / _totalSupply; } else if (_totalSupply == 0) { microLotsProfits += (amount * ACCURACY) / microLotsTotal; } else { uint256 microAmount = amount / 5; uint256 baseAmount = amount - microAmount; microLotsProfits += (microAmount * ACCURACY) / microLotsTotal; totalProfit += (baseAmount * ACCURACY) / _totalSupply; } emit Profit(amount); } } modifier lockupFree { require( lastBoughtTimestamp[msg.sender] + classicLockupPeriod <= block.timestamp, "The action is suspended due to the lockup" ); _; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC20Mock is ERC20 { uint8 private immutable _decimals; constructor( string memory name, string memory symbol, uint8 __decimals ) ERC20(name, symbol) { _decimals = __decimals; } function decimals() public view override returns (uint8) { return _decimals; } function mintTo(address account, uint256 amount) public { _mint(account, amount); } function mint(uint256 amount) public { _mint(msg.sender, amount); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "./ERC20Mock.sol"; contract WETHMock is ERC20Mock("WETH", "Wrapped Ether", 18) { function deposit() external payable { _mint(msg.sender, msg.value); } function withdraw(uint256 amount) external { _burn(msg.sender, amount); payable(msg.sender).transfer(amount); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "./ERC20Mock.sol"; import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol"; contract UniswapRouterMock { ERC20Mock public immutable WBTC; ERC20Mock public immutable USDC; AggregatorV3Interface public immutable WBTCPriceProvider; AggregatorV3Interface public immutable ETHPriceProvider; constructor( ERC20Mock _wbtc, ERC20Mock _usdc, AggregatorV3Interface wpp, AggregatorV3Interface epp ) { WBTC = _wbtc; USDC = _usdc; WBTCPriceProvider = wpp; ETHPriceProvider = epp; } function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 /*deadline*/ ) external payable returns (uint256[] memory amounts) { require(path.length == 2, "UniswapMock: wrong path"); require( path[1] == address(USDC) || path[1] == address(WBTC), "UniswapMock: too small value" ); amounts = getAmountsIn(amountOut, path); require(msg.value >= amounts[0], "UniswapMock: too small value"); if (msg.value > amounts[0]) payable(msg.sender).transfer(msg.value - amounts[0]); ERC20Mock(path[1]).mintTo(to, amountOut); } function getAmountsIn(uint256 amountOut, address[] calldata path) public view returns (uint256[] memory amounts) { require(path.length == 2, "UniswapMock: wrong path"); uint256 amount; if (path[1] == address(USDC)) { (, int256 ethPrice, , , ) = ETHPriceProvider.latestRoundData(); amount = (amountOut * 1e8) / uint256(ethPrice); } else if (path[1] == address(WBTC)) { (, int256 ethPrice, , , ) = ETHPriceProvider.latestRoundData(); (, int256 wbtcPrice, , , ) = WBTCPriceProvider.latestRoundData(); amount = (amountOut * uint256(wbtcPrice)) / uint256(ethPrice); } else { revert("UniswapMock: wrong path"); } amounts = new uint256[](2); amounts[0] = (amount * 103) / 100; amounts[1] = amountOut; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/IOptionsManager.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Options Manager Contract * @notice The contract that buys the options contracts for the options holders * as well as checks whether the contract that is used for buying/exercising * options has been been granted with the permission to do it on the user's behalf. **/ contract OptionsManager is IOptionsManager, ERC721("Hegic V8888 Options (Tokenized)", "HOT8888"), AccessControl { bytes32 public constant HEGIC_POOL_ROLE = keccak256("HEGIC_POOL_ROLE"); uint256 public nextTokenId = 0; mapping(uint256 => address) public override tokenPool; constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @dev See EIP-165: ERC-165 Standard Interface Detection * https://eips.ethereum.org/EIPS/eip-165 **/ function createOptionFor(address holder) public override onlyRole(HEGIC_POOL_ROLE) returns (uint256 id) { id = nextTokenId++; tokenPool[id] = msg.sender; _safeMint(holder, id); } /** * @dev See EIP-165: ERC-165 Standard Interface Detection * https://eips.ethereum.org/EIPS/eip-165 **/ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl, IERC165) returns (bool) { return interfaceId == type(IOptionsManager).interfaceId || AccessControl.supportsInterface(interfaceId) || ERC721.supportsInterface(interfaceId); } /** * @notice Used for checking whether the user has approved * the contract to buy/exercise the options on her behalf. * @param spender The address of the contract * that is used for exercising the options * @param tokenId The ERC721 token ID that is linked to the option **/ function isApprovedOrOwner(address spender, uint256 tokenId) external view virtual override returns (bool) { address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @notice The interface for the contract * that tokenizes options as ERC721. **/ interface IOptionsManager is IERC721 { /** * @param holder The option buyer address **/ function createOptionFor(address holder) external returns (uint256); /** * @param tokenId The ERC721 token ID linked to the option **/ function tokenPool(uint256 tokenId) external returns (address pool); /** * @param spender The option buyer address or another address * with the granted permission to buy/exercise options on the user's behalf * @param tokenId The ERC721 token ID linked to the option **/ function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/Interfaces.sol"; import "../Interfaces/IOptionsManager.sol"; import "../Interfaces/Interfaces.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Main Pool Contract * @notice One of the main contracts that manages the pools and the options parameters, * accumulates the funds from the liquidity providers and makes the withdrawals for them, * sells the options contracts to the options buyers and collateralizes them, * exercises the ITM (in-the-money) options with the unrealized P&L and settles them, * unlocks the expired options and distributes the premiums among the liquidity providers. **/ abstract contract HegicPool is IHegicPool, ERC721, AccessControl, ReentrancyGuard { using SafeERC20 for IERC20; uint256 public constant INITIAL_RATE = 1e20; IOptionsManager public immutable optionsManager; AggregatorV3Interface public immutable priceProvider; IPriceCalculator public override pricer; uint256 public lockupPeriodForHedgedTranches = 60 days; uint256 public lockupPeriodForUnhedgedTranches = 30 days; uint256 public hedgeFeeRate = 80; uint256 public maxUtilizationRate = 80; uint256 public collateralizationRatio = 50; uint256 public override lockedAmount; uint256 public maxDepositAmount = type(uint256).max; uint256 public maxHedgedDepositAmount = type(uint256).max; uint256 public unhedgedShare = 0; uint256 public hedgedShare = 0; uint256 public override unhedgedBalance = 0; uint256 public override hedgedBalance = 0; ISettlementFeeRecipient public settlementFeeRecipient; address public hedgePool; Tranche[] public override tranches; mapping(uint256 => Option) public override options; IERC20 public override token; constructor( IERC20 _token, string memory name, string memory symbol, IOptionsManager manager, IPriceCalculator _pricer, ISettlementFeeRecipient _settlementFeeRecipient, AggregatorV3Interface _priceProvider ) ERC721(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); priceProvider = _priceProvider; settlementFeeRecipient = _settlementFeeRecipient; pricer = _pricer; token = _token; hedgePool = _msgSender(); optionsManager = manager; } /** * @notice Used for setting the liquidity lock-up periods during which * the liquidity providers who deposited the funds into the pools contracts * won't be able to withdraw them. Note that different lock-ups could * be set for the hedged and unhedged — classic — liquidity tranches. * @param hedgedValue Hedged liquidity tranches lock-up in seconds * @param unhedgedValue Unhedged (classic) liquidity tranches lock-up in seconds **/ function setLockupPeriod(uint256 hedgedValue, uint256 unhedgedValue) external override onlyRole(DEFAULT_ADMIN_ROLE) { require( hedgedValue <= 60 days, "The lockup period for hedged tranches is too long" ); require( unhedgedValue <= 30 days, "The lockup period for unhedged tranches is too long" ); lockupPeriodForHedgedTranches = hedgedValue; lockupPeriodForUnhedgedTranches = unhedgedValue; } /** * @notice Used for setting the total maximum amount * that could be deposited into the pools contracts. * Note that different total maximum amounts could be set * for the hedged and unhedged — classic — liquidity tranches. * @param total Maximum amount of assets in the pool * in hedged and unhedged (classic) liquidity tranches combined * @param hedged Maximum amount of assets in the pool * in hedged liquidity tranches only **/ function setMaxDepositAmount(uint256 total, uint256 hedged) external onlyRole(DEFAULT_ADMIN_ROLE) { require( total >= hedged, "Pool Error: The total amount shouldn't be lower than the hedged amount" ); maxDepositAmount = total; maxHedgedDepositAmount = hedged; } /** * @notice Used for setting the maximum share of the pool * size that could be utilized as a collateral in the options. * * Example: if `MaxUtilizationRate` = 50, then only 50% * of liquidity on the pools contracts would be used for * collateralizing options while 50% will be sitting idle * available for withdrawals by the liquidity providers. * @param value The utilization ratio in a range of 50% — 100% **/ function setMaxUtilizationRate(uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) { require( 50 <= value && value <= 100, "Pool error: Wrong utilization rate limitation value" ); maxUtilizationRate = value; } /** * @notice Used for setting the collateralization ratio for the option * collateral size that will be locked at the moment of buying them. * * Example: if `CollateralizationRatio` = 50, then 50% of an option's * notional size will be locked in the pools at the moment of buying it: * say, 1 ETH call option will be collateralized with 0.5 ETH (50%). * Note that if an option holder's net P&L USD value (as options * are cash-settled) will exceed the amount of the collateral locked * in the option, she will receive the required amount at the moment * of exercising the option using the pool's unutilized (unlocked) funds. * @param value The collateralization ratio in a range of 30% — 100% **/ function setCollateralizationRatio(uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) { require( 30 <= value && value <= 100, "Pool Error: Wrong collateralization ratio value" ); collateralizationRatio = value; } /** * @dev See EIP-165: ERC-165 Standard Interface Detection * https://eips.ethereum.org/EIPS/eip-165. **/ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl, IERC165) returns (bool) { return interfaceId == type(IHegicPool).interfaceId || AccessControl.supportsInterface(interfaceId) || ERC721.supportsInterface(interfaceId); } /** * @notice Used for changing the hedging pool address * that will be accumulating the hedging premiums paid * as a share of the total premium redirected to this address. * @param value The address for receiving hedging premiums **/ function setHedgePool(address value) external override onlyRole(DEFAULT_ADMIN_ROLE) { require(value != address(0)); hedgePool = value; } /** * @notice Used for selling the options contracts * with the parameters chosen by the option buyer * such as the period of holding, option size (amount), * strike price and the premium to be paid for the option. * @param holder The option buyer address * @param period The option period * @param amount The option size * @param strike The option strike * @return id ID of ERC721 token linked to the option **/ function sellOption( address holder, uint256 period, uint256 amount, uint256 strike ) external override returns (uint256 id) { if (strike == 0) strike = _currentPrice(); uint256 balance = totalBalance(); uint256 amountToBeLocked = _calculateLockedAmount(amount); require(period >= 1 days, "Pool Error: The period is too short"); require(period <= 90 days, "Pool Error: The period is too long"); require( (lockedAmount + amountToBeLocked) * 100 <= balance * maxUtilizationRate, "Pool Error: The amount is too large" ); (uint256 settlementFee, uint256 premium) = _calculateTotalPremium(period, amount, strike); uint256 hedgedPremiumTotal = (premium * hedgedBalance) / balance; uint256 hedgeFee = (hedgedPremiumTotal * hedgeFeeRate) / 100; uint256 hedgePremium = hedgedPremiumTotal - hedgeFee; uint256 unhedgePremium = premium - hedgedPremiumTotal; lockedAmount += amountToBeLocked; id = optionsManager.createOptionFor(holder); options[id] = Option( OptionState.Active, strike, amount, amountToBeLocked, block.timestamp + period, hedgePremium, unhedgePremium ); token.safeTransferFrom( _msgSender(), address(this), premium + settlementFee ); token.safeTransfer(address(settlementFeeRecipient), settlementFee); settlementFeeRecipient.distributeUnrealizedRewards(); if (hedgeFee > 0) token.safeTransfer(hedgePool, hedgeFee); emit Acquired(id, settlementFee, premium); } /** * @notice Used for setting the price calculator * contract that will be used for pricing the options. * @param pc A new price calculator contract address **/ function setPriceCalculator(IPriceCalculator pc) public onlyRole(DEFAULT_ADMIN_ROLE) { pricer = pc; } /** * @notice Used for exercising the ITM (in-the-money) * options contracts in case of having the unrealized profits * accrued during the period of holding the option contract. * @param id ID of ERC721 token linked to the option **/ function exercise(uint256 id) external override { Option storage option = options[id]; uint256 profit = _profitOf(option); require( optionsManager.isApprovedOrOwner(_msgSender(), id), "Pool Error: msg.sender can't exercise this option" ); require( option.expired > block.timestamp, "Pool Error: The option has already expired" ); require( profit > 0, "Pool Error: There are no unrealized profits for this option" ); _unlock(option); option.state = OptionState.Exercised; _send(optionsManager.ownerOf(id), profit); emit Exercised(id, profit); } function _send(address to, uint256 transferAmount) private { require(to != address(0)); uint256 hedgeLoss = (transferAmount * hedgedBalance) / totalBalance(); uint256 unhedgeLoss = transferAmount - hedgeLoss; hedgedBalance -= hedgeLoss; unhedgedBalance -= unhedgeLoss; token.safeTransfer(to, transferAmount); } /** * @notice Used for unlocking the expired OTM (out-of-the-money) * options contracts in case if there was no unrealized P&L * accrued during the period of holding a particular option. * Note that the `unlock` function releases the liquidity that * was locked in the option when it was active and the premiums * that are distributed pro rata among the liquidity providers. * @param id ID of ERC721 token linked to the option **/ function unlock(uint256 id) external override { Option storage option = options[id]; require( option.expired < block.timestamp, "Pool Error: The option has not expired yet" ); _unlock(option); option.state = OptionState.Expired; emit Expired(id); } function _unlock(Option storage option) internal { require( option.state == OptionState.Active, "Pool Error: The option with such an ID has already been exercised or expired" ); lockedAmount -= option.lockedAmount; hedgedBalance += option.hedgePremium; unhedgedBalance += option.unhedgePremium; } function _calculateLockedAmount(uint256 amount) internal virtual returns (uint256) { return (amount * collateralizationRatio) / 100; } /** * @notice Used for depositing the funds into the pool * and minting the liquidity tranche ERC721 token * which represents the liquidity provider's share * in the pool and her unrealized P&L for this tranche. * @param account The liquidity provider's address * @param amount The size of the liquidity tranche * @param hedged The type of the liquidity tranche * @param minShare The minimum share in the pool for the user **/ function provideFrom( address account, uint256 amount, bool hedged, uint256 minShare ) external override nonReentrant returns (uint256 share) { uint256 totalShare = hedged ? hedgedShare : unhedgedShare; uint256 balance = hedged ? hedgedBalance : unhedgedBalance; share = totalShare > 0 && balance > 0 ? (amount * totalShare) / balance : amount * INITIAL_RATE; uint256 limit = hedged ? maxHedgedDepositAmount - hedgedBalance : maxDepositAmount - hedgedBalance - unhedgedBalance; require(share >= minShare, "Pool Error: The mint limit is too large"); require(share > 0, "Pool Error: The amount is too small"); require( amount <= limit, "Pool Error: Depositing into the pool is not available" ); if (hedged) { hedgedShare += share; hedgedBalance += amount; } else { unhedgedShare += share; unhedgedBalance += amount; } uint256 trancheID = tranches.length; tranches.push( Tranche(TrancheState.Open, share, amount, block.timestamp, hedged) ); _safeMint(account, trancheID); token.safeTransferFrom(_msgSender(), address(this), amount); } /** * @notice Used for withdrawing the funds from the pool * plus the net positive P&L earned or * minus the net negative P&L lost on * providing liquidity and selling options. * @param trancheID The liquidity tranche ID * @return amount The amount received after the withdrawal **/ function withdraw(uint256 trancheID) external override nonReentrant returns (uint256 amount) { address owner = ownerOf(trancheID); Tranche memory t = tranches[trancheID]; amount = _withdraw(owner, trancheID); if (t.hedged && amount < t.amount) { token.safeTransferFrom(hedgePool, owner, t.amount - amount); amount = t.amount; } emit Withdrawn(owner, trancheID, amount); } /** * @notice Used for withdrawing the funds from the pool * by the hedged liquidity tranches providers * in case of an urgent need to withdraw the liquidity * without receiving the loss compensation from * the hedging pool: the net difference between * the amount deposited and the withdrawal amount. * @param trancheID ID of liquidity tranche * @return amount The amount received after the withdrawal **/ function withdrawWithoutHedge(uint256 trancheID) external override nonReentrant returns (uint256 amount) { address owner = ownerOf(trancheID); amount = _withdraw(owner, trancheID); emit Withdrawn(owner, trancheID, amount); } function _withdraw(address owner, uint256 trancheID) internal returns (uint256 amount) { Tranche storage t = tranches[trancheID]; uint256 lockupPeriod = t.hedged ? lockupPeriodForHedgedTranches : lockupPeriodForUnhedgedTranches; require(t.state == TrancheState.Open); require(_isApprovedOrOwner(_msgSender(), trancheID)); require( block.timestamp > t.creationTimestamp + lockupPeriod, "Pool Error: The withdrawal is locked up" ); t.state = TrancheState.Closed; if (t.hedged) { amount = (t.share * hedgedBalance) / hedgedShare; hedgedShare -= t.share; hedgedBalance -= amount; } else { amount = (t.share * unhedgedBalance) / unhedgedShare; unhedgedShare -= t.share; unhedgedBalance -= amount; } token.safeTransfer(owner, amount); } /** * @return balance Returns the amount of liquidity available for withdrawing **/ function availableBalance() public view returns (uint256 balance) { return totalBalance() - lockedAmount; } /** * @return balance Returns the total balance of liquidity provided to the pool **/ function totalBalance() public view override returns (uint256 balance) { return hedgedBalance + unhedgedBalance; } function _beforeTokenTransfer( address, address, uint256 id ) internal view override { require( tranches[id].state == TrancheState.Open, "Pool Error: The closed tranches can not be transferred" ); } /** * @notice Returns the amount of unrealized P&L of the option * that could be received by the option holder in case * if she exercises it as an ITM (in-the-money) option. * @param id ID of ERC721 token linked to the option **/ function profitOf(uint256 id) external view returns (uint256) { return _profitOf(options[id]); } function _profitOf(Option memory option) internal view virtual returns (uint256 amount); /** * @notice Used for calculating the `TotalPremium` * for the particular option with regards to * the parameters chosen by the option buyer * such as the period of holding, size (amount) * and strike price. * @param period The period of holding the option * @param period The size of the option **/ function calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) external view override returns (uint256 settlementFee, uint256 premium) { return _calculateTotalPremium(period, amount, strike); } function _calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) internal view virtual returns (uint256 settlementFee, uint256 premium) { (settlementFee, premium) = pricer.calculateTotalPremium( period, amount, strike ); require( settlementFee + premium > amount / 1000, "HegicPool: The option's price is too low" ); } /** * @notice Used for changing the `settlementFeeRecipient` * contract address for distributing the settlement fees * (staking rewards) among the staking participants. * @param recipient New staking contract address **/ function setSettlementFeeRecipient(IHegicStaking recipient) external onlyRole(DEFAULT_ADMIN_ROLE) { require(address(recipient) != address(0)); settlementFeeRecipient = recipient; } function _currentPrice() internal view returns (uint256 price) { (, int256 latestPrice, , , ) = priceProvider.latestRoundData(); price = uint256(latestPrice); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "./HegicPool.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Put Liquidity Pool Contract * @notice The Put Liquidity Pool Contract **/ contract HegicPUT is HegicPool { uint256 private immutable SpotDecimals; // 1e18 uint256 private constant TokenDecimals = 1e6; // 1e6 /** * @param name The pool contract name * @param symbol The pool ticker for the ERC721 options **/ constructor( IERC20 _token, string memory name, string memory symbol, IOptionsManager manager, IPriceCalculator _pricer, IHegicStaking _settlementFeeRecipient, AggregatorV3Interface _priceProvider, uint8 spotDecimals ) HegicPool( _token, name, symbol, manager, _pricer, _settlementFeeRecipient, _priceProvider ) { SpotDecimals = 10**spotDecimals; } function _profitOf(Option memory option) internal view override returns (uint256 amount) { uint256 currentPrice = _currentPrice(); if (currentPrice > option.strike) return 0; return ((option.strike - currentPrice) * option.amount * TokenDecimals) / SpotDecimals / 1e8; } function _calculateLockedAmount(uint256 amount) internal view override returns (uint256) { return (amount * collateralizationRatio * _currentPrice() * TokenDecimals) / SpotDecimals / 1e8 / 100; } function _calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) internal view override returns (uint256 settlementFee, uint256 premium) { uint256 currentPrice = _currentPrice(); (settlementFee, premium) = pricer.calculateTotalPremium( period, amount, strike ); settlementFee = (settlementFee * currentPrice * TokenDecimals) / 1e8 / SpotDecimals; premium = (premium * currentPrice * TokenDecimals) / 1e8 / SpotDecimals; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "./HegicPool.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Call Liquidity Pool Contract * @notice The Call Liquidity Pool Contract **/ contract HegicCALL is HegicPool { /** * @param name The pool contract name * @param symbol The pool ticker for the ERC721 options **/ constructor( IERC20 _token, string memory name, string memory symbol, IOptionsManager manager, IPriceCalculator _pricer, IHegicStaking _settlementFeeRecipient, AggregatorV3Interface _priceProvider ) HegicPool( _token, name, symbol, manager, _pricer, _settlementFeeRecipient, _priceProvider ) {} function _profitOf(Option memory option) internal view override returns (uint256 amount) { uint256 currentPrice = _currentPrice(); if (currentPrice < option.strike) return 0; return ((currentPrice - option.strike) * option.amount) / currentPrice; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/Interfaces.sol"; import "../Interfaces/IOptionsManager.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Facade Contract * @notice The contract that calculates the options prices, * conducts the process of buying options, converts the premiums * into the token that the pool is denominated in and grants * permissions to the contracts such as GSN (Gas Station Network). **/ contract Facade is Ownable { using SafeERC20 for IERC20; IWETH public immutable WETH; IUniswapV2Router01 public immutable exchange; IOptionsManager public immutable optionsManager; address public _trustedForwarder; constructor( IWETH weth, IUniswapV2Router01 router, IOptionsManager manager, address trustedForwarder ) { WETH = weth; exchange = router; _trustedForwarder = trustedForwarder; optionsManager = manager; } /** * @notice Used for calculating the option price (the premium) and using * the swap router (if needed) to convert the tokens with which the user * pays the premium into the token in which the pool is denominated. * @param period The option period * @param amount The option size * @param strike The option strike * @param total The total premium * @param baseTotal The part of the premium that * is distributed among the liquidity providers * @param settlementFee The part of the premium that * is distributed among the HEGIC staking participants **/ function getOptionPrice( IHegicPool pool, uint256 period, uint256 amount, uint256 strike, address[] calldata swappath ) public view returns ( uint256 total, uint256 baseTotal, uint256 settlementFee, uint256 premium ) { (uint256 _baseTotal, uint256 baseSettlementFee, uint256 basePremium) = getBaseOptionCost(pool, period, amount, strike); if (swappath.length > 1) total = exchange.getAmountsIn(_baseTotal, swappath)[0]; else total = _baseTotal; baseTotal = _baseTotal; settlementFee = (total * baseSettlementFee) / baseTotal; premium = (total * basePremium) / baseTotal; } /** * @notice Used for calculating the option price (the premium) * in the token in which the pool is denominated. * @param period The option period * @param amount The option size * @param strike The option strike **/ function getBaseOptionCost( IHegicPool pool, uint256 period, uint256 amount, uint256 strike ) public view returns ( uint256 total, uint256 settlementFee, uint256 premium ) { (settlementFee, premium) = pool.calculateTotalPremium( period, amount, strike ); total = premium + settlementFee; } /** * @notice Used for approving the pools contracts addresses. **/ function poolApprove(IHegicPool pool) external { pool.token().safeApprove(address(pool), 0); pool.token().safeApprove(address(pool), type(uint256).max); } /** * @notice Used for buying the option contract and converting * the buyer's tokens (the total premium) into the token * in which the pool is denominated. * @param period The option period * @param amount The option size * @param strike The option strike * @param acceptablePrice The highest acceptable price **/ function createOption( IHegicPool pool, uint256 period, uint256 amount, uint256 strike, address[] calldata swappath, uint256 acceptablePrice ) external { address buyer = _msgSender(); (uint256 optionPrice, uint256 rawOptionPrice, , ) = getOptionPrice(pool, period, amount, strike, swappath); require( optionPrice <= acceptablePrice, "Facade Error: The option price is too high" ); IERC20 paymentToken = IERC20(swappath[0]); paymentToken.safeTransferFrom(buyer, address(this), optionPrice); if (swappath.length > 1) { if ( paymentToken.allowance(address(this), address(exchange)) < optionPrice ) { paymentToken.safeApprove(address(exchange), 0); paymentToken.safeApprove(address(exchange), type(uint256).max); } exchange.swapTokensForExactTokens( rawOptionPrice, optionPrice, swappath, address(this), block.timestamp ); } pool.sellOption(buyer, period, amount, strike); } /** * @notice Used for converting the liquidity provider's Ether (ETH) * into Wrapped Ether (WETH) and providing the funds into the pool. * @param hedged The liquidity tranche type: hedged or unhedged (classic) **/ function provideEthToPool( IHegicPool pool, bool hedged, uint256 minShare ) external payable returns (uint256) { WETH.deposit{value: msg.value}(); if (WETH.allowance(address(this), address(pool)) < msg.value) WETH.approve(address(pool), type(uint256).max); return pool.provideFrom(msg.sender, msg.value, hedged, minShare); } /** * @notice Unlocks the array of options. * @param optionIDs The array of options **/ function unlockAll(IHegicPool pool, uint256[] calldata optionIDs) external { uint256 arrayLength = optionIDs.length; for (uint256 i = 0; i < arrayLength; i++) { pool.unlock(optionIDs[i]); } } /** * @notice Used for granting the GSN (Gas Station Network) contract * the permission to pay the gas (transaction) fees for the users. * @param forwarder GSN (Gas Station Network) contract address **/ function isTrustedForwarder(address forwarder) public view returns (bool) { return forwarder == _trustedForwarder; } function claimAllStakingProfits( IHegicStaking[] calldata stakings, address account ) external { uint256 arrayLength = stakings.length; for (uint256 i = 0; i < arrayLength; i++) { IHegicStaking s = stakings[i]; if (s.profitOf(account) > 0) s.claimProfits(account); } } function _msgSender() internal view override returns (address signer) { signer = msg.sender; if (msg.data.length >= 20 && isTrustedForwarder(signer)) { assembly { signer := shr(96, calldataload(sub(calldatasize(), 20))) } } } function exercise(uint256 optionId) external { require( optionsManager.isApprovedOrOwner(_msgSender(), optionId), "Facade Error: _msgSender is not eligible to exercise the option" ); IHegicPool(optionsManager.tokenPool(optionId)).exercise(optionId); } function versionRecipient() external pure returns (string memory) { return "2.2.2"; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "./Interfaces/IOptionsManager.sol"; import "./Interfaces/Interfaces.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Exerciser Contract * @notice The contract that allows to automatically exercise options half an hour before expiration **/ contract Exerciser { IOptionsManager immutable optionsManager; constructor(IOptionsManager manager) { optionsManager = manager; } function exercise(uint256 optionId) external { IHegicPool pool = IHegicPool(optionsManager.tokenPool(optionId)); (, , , , uint256 expired, , ) = pool.options(optionId); require( block.timestamp > expired - 30 minutes, "Facade Error: Automatically exercise for this option is not available yet" ); pool.exercise(optionId); } } /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @dev A contract that allows to lock-up the rewards in * the Hegic Long-Term Pools during a certain period of time. */ contract HLTPs { using SafeERC20 for IERC20; // The beneficiary of rewards after they are released address private immutable _beneficiary; // The timestamp when the rewards release will be enabled uint256 private immutable _releaseTime; constructor(uint256 releaseTime_) { _beneficiary = msg.sender; _releaseTime = releaseTime_; } /** * @return The beneficiary address that will distribute the rewards. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return The point of time when the rewards will be released. */ function releaseTime() public view returns (uint256) { return _releaseTime; } /** * @notice Transfers tokens locked by timelock to beneficiary. */ function release(IERC20 token) public { require( block.timestamp >= releaseTime(), "HLTPs: Current time is earlier than the release time" ); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "HLTPs: No rewards to be released"); token.safeTransfer(beneficiary(), amount); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./Linear.sol"; import "./IBondingCurve.sol"; contract Erc20BondingCurve is LinearBondingCurve { using SafeERC20 for IERC20; IERC20 public immutable saleToken; IERC20 public immutable purchaseToken; uint256 public soldAmount; uint256 public comissionShare = 20; address payable public hegicDevelopmentFund; event Bought(address indexed account, uint256 amount, uint256 ethAmount); event Sold( address indexed account, uint256 amount, uint256 ethAmount, uint256 comission ); constructor( IERC20 _saleToken, IERC20 _purchaseToken, uint256 k, uint256 startPrice ) LinearBondingCurve(k, startPrice) { saleToken = _saleToken; purchaseToken = _purchaseToken; hegicDevelopmentFund = payable(msg.sender); _setupRole(LBC_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } function buy(uint256 tokenAmount) external { uint256 nextSold = soldAmount + tokenAmount; uint256 purchaseAmount = s(soldAmount, nextSold); soldAmount = nextSold; purchaseToken.safeTransferFrom( msg.sender, address(this), purchaseAmount ); saleToken.safeTransfer(msg.sender, tokenAmount); emit Bought(msg.sender, tokenAmount, purchaseAmount); } function sell(uint256 tokenAmount) external { uint256 nextSold = soldAmount - tokenAmount; uint256 saleAmount = s(nextSold, soldAmount); uint256 comission = (saleAmount * comissionShare) / 100; uint256 refund = saleAmount - comission; require(comission > 0, "Amount is too small"); soldAmount = nextSold; saleToken.safeTransferFrom(msg.sender, address(this), tokenAmount); purchaseToken.safeTransfer(hegicDevelopmentFund, comission); purchaseToken.safeTransfer(msg.sender, refund); emit Sold(msg.sender, tokenAmount, refund, comission); } function setHDF(address payable value) external onlyRole(DEFAULT_ADMIN_ROLE) { hegicDevelopmentFund = value; } function setCommissionShare(uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) { comissionShare = value; } function destruct() external onlyRole(DEFAULT_ADMIN_ROLE) { selfdestruct(hegicDevelopmentFund); } function withdawERC20(IERC20 token) external onlyRole(DEFAULT_ADMIN_ROLE) { token.transfer(hegicDevelopmentFund, token.balanceOf(address(this))); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/Interfaces.sol"; import "../utils/Math.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Price Calculator Contract * @notice The contract that calculates the options prices (the premiums) * that are adjusted through the `ImpliedVolRate` parameter. **/ contract PriceCalculator is IPriceCalculator, Ownable { using HegicMath for uint256; uint256 public impliedVolRate; uint256 internal constant PRICE_DECIMALS = 1e8; uint256 internal constant PRICE_MODIFIER_DECIMALS = 1e8; uint256 public settlementFeeShare = 24; uint256 public maxPeriod = 30 days; AggregatorV3Interface public priceProvider; constructor(uint256 initialRate, AggregatorV3Interface _priceProvider) { priceProvider = _priceProvider; impliedVolRate = initialRate; } /** * @notice Used for adjusting the options prices (the premiums) * while balancing the asset's implied volatility rate. * @param value New IVRate value **/ function setImpliedVolRate(uint256 value) external onlyOwner { impliedVolRate = value; } /** * @notice Used for adjusting the options prices (the premiums) * while balancing the asset's implied volatility rate. * @param value New settlementFeeShare value **/ function setSettlementFeeShare(uint256 value) external onlyOwner { require(value <= 100, "The value is too large"); settlementFeeShare = value; } function setMaxPeriod(uint256 value) external onlyOwner { maxPeriod = value; } /** * @notice Used for calculating the options prices * @param period The option period in seconds (1 days <= period <= 90 days) * @param amount The option size * @param strike The option strike * @return settlementFee The part of the premium that * is distributed among the HEGIC staking participants * @return premium The part of the premium that * is distributed among the liquidity providers **/ function calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) public view override returns (uint256 settlementFee, uint256 premium) { uint256 currentPrice = _currentPrice(); if (strike == 0) strike = currentPrice; require(period <= maxPeriod, "PriceCalculator: Period is too long"); require( strike == currentPrice, "Only ATM options are currently available" ); uint256 total = _calculatePeriodFee(amount, period); settlementFee = (total * settlementFeeShare) / 100; premium = total - settlementFee; } /** * @notice Calculates and prices in the time value of the option * @param amount Option size * @param period The option period in seconds (1 days <= period <= 90 days) * @return fee The premium size to be paid **/ function _calculatePeriodFee(uint256 amount, uint256 period) internal view returns (uint256 fee) { return (amount * impliedVolRate * period.sqrt()) / PRICE_DECIMALS / PRICE_MODIFIER_DECIMALS; } /** * @notice Used for requesting the current price of the asset * using the ChainLink data feeds contracts. * See https://feeds.chain.link/ * @return price Price **/ function _currentPrice() internal view returns (uint256 price) { (, int256 latestPrice, , , ) = priceProvider.latestRoundData(); price = uint256(latestPrice); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ library HegicMath { /** * @dev Calculates a square root of the number. * Responds with an "invalid opcode" at uint(-1). **/ function sqrt(uint256 x) internal pure returns (uint256 result) { result = x; uint256 k = (x >> 1) + 1; while (k < result) (result, k) = (k, (x / k + k) >> 1); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/Interfaces.sol"; import "../utils/Math.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Price Calculator Contract * @notice The contract that calculates the options prices (the premiums) * that are adjusted through the `ImpliedVolRate` parameter. **/ contract PriceCalculatorUtilization is IPriceCalculator, Ownable { using HegicMath for uint256; uint256 public impliedVolRate; uint256 internal constant PRICE_DECIMALS = 1e8; uint256 internal constant PRICE_MODIFIER_DECIMALS = 1e8; uint256 public utilizationRate = 0; uint256 public settlementFeeShare = 24; AggregatorV3Interface public priceProvider; IHegicPool pool; constructor( uint256 initialRate, AggregatorV3Interface _priceProvider, IHegicPool _pool ) { pool = _pool; priceProvider = _priceProvider; impliedVolRate = initialRate; } /** * @notice Used for adjusting the options prices (the premiums) * while balancing the asset's implied volatility rate. * @param value New IVRate value **/ function setImpliedVolRate(uint256 value) external onlyOwner { impliedVolRate = value; } /** * @notice Used for adjusting the options prices (the premiums) * while balancing the asset's implied volatility rate. * @param value New IVRate value **/ function setSettlementFeeShare(uint256 value) external onlyOwner { require(value <= 100, "The value is too large"); settlementFeeShare = value; } /** * @notice Used for updating utilizationRate value * @param value New utilizationRate value **/ function setUtilizationRate(uint256 value) external onlyOwner { utilizationRate = value; } /** * @notice Used for calculating the options prices * @param period The option period in seconds (1 days <= period <= 90 days) * @param amount The option size * @param strike The option strike * @return settlementFee The part of the premium that * is distributed among the HEGIC staking participants * @return premium The part of the premium that * is distributed among the liquidity providers **/ function calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) public view override returns (uint256 settlementFee, uint256 premium) { uint256 currentPrice = _currentPrice(); if (strike == 0) strike = currentPrice; require( strike == currentPrice, "Only ATM options are currently available" ); uint256 total = _calculatePeriodFee(amount, period); settlementFee = (total * settlementFeeShare) / 100; premium = total - settlementFee; } /** * @notice Calculates and prices in the time value of the option * @param amount Option size * @param period The option period in seconds (1 days <= period <= 90 days) * @return fee The premium size to be paid **/ function _calculatePeriodFee(uint256 amount, uint256 period) internal view returns (uint256 fee) { return (amount * _priceModifier(amount, period, pool)) / PRICE_DECIMALS / PRICE_MODIFIER_DECIMALS; } /** * @notice Calculates `periodFee` of the option * @param amount The option size * @param period The option period in seconds (1 days <= period <= 90 days) **/ function _priceModifier( uint256 amount, uint256 period, IHegicPool pool ) internal view returns (uint256 iv) { uint256 poolBalance = pool.totalBalance(); require(poolBalance > 0, "Pool Error: The pool is empty"); iv = impliedVolRate * period.sqrt(); uint256 lockedAmount = pool.lockedAmount() + amount; uint256 utilization = (lockedAmount * 100e8) / poolBalance; if (utilization > 40e8) { iv += (iv * (utilization - 40e8) * utilizationRate) / 40e16; } } /** * @notice Used for requesting the current price of the asset * using the ChainLink data feeds contracts. * See https://feeds.chain.link/ * @return price Price **/ function _currentPrice() internal view returns (uint256 price) { (, int256 latestPrice, , , ) = priceProvider.latestRoundData(); price = uint256(latestPrice); } } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } pragma solidity >=0.5.0; interface IUniswapV2ERC20 { 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; } pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
Used for unstaking the HEGIC tokens in the form of selling the microlot./
function sellMicroLot(uint256 amount) external { require(amount > 0, "Amount is zero"); require( lastMicroBoughtTimestamp[msg.sender] + microLockupPeriod < block.timestamp, "The action is suspended due to the lockup" ); saveProfits(msg.sender); microLotsTotal -= amount; microBalance[msg.sender] -= amount; HEGIC.safeTransfer(msg.sender, amount); emit MicroLotsSold(msg.sender, amount); }
31,843
./partial_match/3/0x1B0eD927c605f4CBc9065ac330dC0E009070Ce7D/sources/StakingRewardsStore.sol
adds a program poolToken the pool token representing the rewards pool reserveTokens the reserve tokens representing the liquidity in the pool rewardShares reserve reward shares endTime the ending time of the program rewardRate the program's rewards rate per-second/
function addPoolProgram( IDSToken poolToken, IERC20Token[2] calldata reserveTokens, uint32[2] calldata rewardShares, uint256 endTime, uint256 rewardRate ) external override onlyOwner validAddress(address(poolToken)) { uint256 currentTime = time(); addPoolProgram(poolToken, reserveTokens, rewardShares, currentTime, endTime, rewardRate); emit PoolProgramAdded(poolToken, currentTime, endTime, rewardRate); }
5,325,927
pragma solidity ^0.4.19; /* Adapted from strings.sol created by Nick Johnson <arachnid@notdot.net> * Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <arachnid@notdot.net> */ library strings { struct slice { uint _len; uint _ptr; } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function concat(slice self, slice other) internal returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal pure returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } } /* Helper String Functions for Game Manager Contract * @title String Healpers * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract StringHelpers { using strings for *; function stringToBytes32(string memory source) internal returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function bytes32ToString(bytes32 x) constant internal returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete) contract ERC721 { // Required methods function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _assetId) public view returns (address owner); function approve(address _to, uint256 _assetId) public; function transfer(address _to, uint256 _assetId) public; function transferFrom(address _from, address _to, uint256 _assetId) public; function implementsERC721() public pure returns (bool); function takeOwnership(uint256 _assetId) public; function totalSupply() public view returns (uint256 total); event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } /* Controls game play state and access rights for game functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Game Managers (Primary/Secondary): Has universal control of all game elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public gameManagerPrimary; address public gameManagerSecondary; address public bankManager; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyGameManager() { require(msg.sender == gameManagerPrimary || msg.sender == gameManagerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier anyOperator() { require( msg.sender == gameManagerPrimary || msg.sender == gameManagerSecondary || msg.sender == bankManager ); _; } /// @dev Assigns a new address to act as the GM. function setPrimaryGameManager(address _newGM) external onlyGameManager { require(_newGM != address(0)); gameManagerPrimary = _newGM; } /// @dev Assigns a new address to act as the GM. function setSecondaryGameManager(address _newGM) external onlyGameManager { require(_newGM != address(0)); gameManagerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyGameManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyGameManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyGameManager whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyGameManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyGameManager whenPaused { error = false; } } contract CSCCollectibleBase is ERC721, OperationalControl, StringHelpers { /*** EVENTS ***/ /// @dev The Created event is fired whenever a new collectible comes into existence. event CollectibleCreated(address owner, uint256 globalId, uint256 collectibleType, uint256 collectibleClass, uint256 sequenceId, bytes32 collectibleName, bool isRedeemed); event Transfer(address from, address to, uint256 shipId); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CSCPreSaleShip"; string public constant SYMBOL = "CSC"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @dev CSC Pre Sale Struct, having details of the ship struct CSCPreSaleItem { /// @dev asset ID i..e Local Index uint256 assetId; /// @dev name of the collectible stored in bytes bytes32 collectibleName; /// @dev Timestamp when bought uint256 boughtTimestamp; /// @dev Collectible Types (Voucher/Ship) /// can be 0 - Voucher, 1 - Ship uint256 collectibleType; /// @dev Collectible Class (1 - Prometheus, 2 - Crosair, 3 - Intrepid) uint256 collectibleClass; // @dev owner address address owner; // @dev redeeme flag (to help whether it got redeemed or not) bool isRedeemed; } // @dev Mapping containing the reference to all CSC PreSaleItem //mapping (uint256 => CSCPreSaleItem[]) public indexToPreSaleItem; // @dev array of CSCPreSaleItem type holding information on the Ships CSCPreSaleItem[] allPreSaleItems; // Max Count for Voucher(s), Prometheus, Crosair & Intrepid Ships uint256 public constant PROMETHEUS_SHIP_LIMIT = 300; uint256 public constant INTREPID_SHIP_LIMIT = 1500; uint256 public constant CROSAIR_SHIP_LIMIT = 600; uint256 public constant PROMETHEUS_VOUCHER_LIMIT = 100; uint256 public constant INTREPID_VOUCHER_LIMIT = 300; uint256 public constant CROSAIR_VOUCHER_LIMIT = 200; // Variable to keep a count of Prometheus/Intrepid/Crosair Minted uint256 public prometheusShipMinted; uint256 public intrepidShipMinted; uint256 public crosairShipMinted; uint256 public prometheusVouchersMinted; uint256 public intrepidVouchersMinted; uint256 public crosairVouchersMinted; // @dev mapping which holds all the possible addresses which are allowed to interact with the contract mapping (address => bool) approvedAddressList; // @dev mapping holds the preSaleItem -> owner details mapping (uint256 => address) public preSaleItemIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from preSaleItem to an address that has been approved to call /// transferFrom(). Each Ship can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public preSaleItemIndexToApproved; /// @dev A mapping of preSaleItem Type to Type Sequence Number to Collectible /// 0 - Voucher /// 1 - Prometheus /// 2 - Crosair /// 3 - Intrepid mapping (uint256 => mapping (uint256 => mapping ( uint256 => uint256 ) ) ) public preSaleItemTypeToSequenceIdToCollectible; /// @dev A mapping from Pre Sale Item Type IDs to the Sequqence Number . /// 0 - Voucher /// 1 - Prometheus /// 2 - Crosair /// 3 - Intrepid mapping (uint256 => mapping ( uint256 => uint256 ) ) public preSaleItemTypeToCollectibleCount; /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } function getCollectibleDetails(uint256 _assetId) external view returns(uint256 assetId, uint256 sequenceId, uint256 collectibleType, uint256 collectibleClass, bool isRedeemed, address owner) { CSCPreSaleItem memory _Obj = allPreSaleItems[_assetId]; assetId = _assetId; sequenceId = _Obj.assetId; collectibleType = _Obj.collectibleType; collectibleClass = _Obj.collectibleClass; owner = _Obj.owner; isRedeemed = _Obj.isRedeemed; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _assetId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _assetId) public { // Caller must own token. require(_owns(msg.sender, _assetId)); preSaleItemIndexToApproved[_assetId] = _to; Approval(msg.sender, _to, _assetId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } function implementsERC721() public pure returns (bool) { return true; } /// For querying owner of token /// @param _assetId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _assetId) public view returns (address owner) { owner = preSaleItemIndexToOwner[_assetId]; require(owner != address(0)); } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _assetId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _assetId) public { address newOwner = msg.sender; address oldOwner = preSaleItemIndexToOwner[_assetId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _assetId)); _transfer(oldOwner, newOwner, _assetId); } /// @param _owner The owner whose ships tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire CSCShips array looking for emojis belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalShips = totalSupply() + 1; uint256 resultIndex = 0; // We count on the fact that all CSC Ship Collectible have IDs starting at 0 and increasing // sequentially up to the total count. uint256 _assetId; for (_assetId = 0; _assetId < totalShips; _assetId++) { if (preSaleItemIndexToOwner[_assetId] == _owner) { result[resultIndex] = _assetId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return allPreSaleItems.length - 1; //Removed 0 index } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _assetId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _assetId) public { require(_addressNotNull(_to)); require(_owns(msg.sender, _assetId)); _transfer(msg.sender, _to, _assetId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _assetId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _assetId) public { require(_owns(_from, _assetId)); require(_approved(_to, _assetId)); require(_addressNotNull(_to)); _transfer(_from, _to, _assetId); } /*** PRIVATE FUNCTIONS ***/ /// @dev Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) internal pure returns (bool) { return _to != address(0); } /// @dev For checking approval of transfer for address _to function _approved(address _to, uint256 _assetId) internal view returns (bool) { return preSaleItemIndexToApproved[_assetId] == _to; } /// @dev For creating CSC Collectible function _createCollectible(bytes32 _collectibleName, uint256 _collectibleType, uint256 _collectibleClass) internal returns(uint256) { uint256 _sequenceId = uint256(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass]) + 1; // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. require(_sequenceId == uint256(uint32(_sequenceId))); CSCPreSaleItem memory _collectibleObj = CSCPreSaleItem( _sequenceId, _collectibleName, 0, _collectibleType, _collectibleClass, address(0), false ); uint256 newCollectibleId = allPreSaleItems.push(_collectibleObj) - 1; preSaleItemTypeToSequenceIdToCollectible[_collectibleType][_collectibleClass][_sequenceId] = newCollectibleId; preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] = _sequenceId; // emit Created event // CollectibleCreated(address owner, uint256 globalId, uint256 collectibleType, uint256 collectibleClass, uint256 sequenceId, bytes32[6] attributes, bool isRedeemed); CollectibleCreated(address(this), newCollectibleId, _collectibleType, _collectibleClass, _sequenceId, _collectibleObj.collectibleName, false); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), address(this), newCollectibleId); return newCollectibleId; } /// Check for token ownership function _owns(address claimant, uint256 _assetId) internal view returns (bool) { return claimant == preSaleItemIndexToOwner[_assetId]; } /// @dev Assigns ownership of a specific Emoji to an address. function _transfer(address _from, address _to, uint256 _assetId) internal { // Updating the owner details of the ship CSCPreSaleItem memory _shipObj = allPreSaleItems[_assetId]; _shipObj.owner = _to; allPreSaleItems[_assetId] = _shipObj; // Since the number of emojis is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership preSaleItemIndexToOwner[_assetId] = _to; // When creating new emojis _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete preSaleItemIndexToApproved[_assetId]; } // Emit the transfer event. Transfer(_from, _to, _assetId); } /// @dev Checks if a given address currently has transferApproval for a particular CSCPreSaleItem. /// 0 is a valid value as it will be the starter function _approvedFor(address _claimant, uint256 _assetId) internal view returns (bool) { return preSaleItemIndexToApproved[_assetId] == _claimant; } function _getCollectibleDetails (uint256 _assetId) internal view returns(CSCPreSaleItem) { CSCPreSaleItem storage _Obj = allPreSaleItems[_assetId]; return _Obj; } /// @dev Helps in fetching the attributes of the ship depending on the ship /// assetId : The actual ERC721 Asset ID /// sequenceId : Index w.r.t Ship type function getShipDetails(uint256 _sequenceId, uint256 _shipClass) external view returns ( uint256 assetId, uint256 sequenceId, string shipName, uint256 collectibleClass, uint256 boughtTimestamp, address owner ) { uint256 _assetId = preSaleItemTypeToSequenceIdToCollectible[1][_shipClass][_sequenceId]; CSCPreSaleItem storage _collectibleObj = allPreSaleItems[_assetId]; require(_collectibleObj.collectibleType == 1); assetId = _assetId; sequenceId = _sequenceId; shipName = bytes32ToString(_collectibleObj.collectibleName); collectibleClass = _collectibleObj.collectibleClass; boughtTimestamp = _collectibleObj.boughtTimestamp; owner = _collectibleObj.owner; } /// @dev Helps in fetching information regarding a Voucher /// assetId : The actual ERC721 Asset ID /// sequenceId : Index w.r.t Voucher Type function getVoucherDetails(uint256 _sequenceId, uint256 _voucherClass) external view returns ( uint256 assetId, uint256 sequenceId, uint256 boughtTimestamp, uint256 voucherClass, address owner ) { uint256 _assetId = preSaleItemTypeToSequenceIdToCollectible[0][_voucherClass][_sequenceId]; CSCPreSaleItem storage _collectibleObj = allPreSaleItems[_assetId]; require(_collectibleObj.collectibleType == 0); assetId = _assetId; sequenceId = _sequenceId; boughtTimestamp = _collectibleObj.boughtTimestamp; voucherClass = _collectibleObj.collectibleClass; owner = _collectibleObj.owner; } function _isActive(uint256 _assetId) internal returns(bool) { CSCPreSaleItem memory _Obj = allPreSaleItems[_assetId]; return (_Obj.boughtTimestamp == 0); } } /* Lucid Sight, Inc. ERC-721 CSC Collectilbe Sale Contract. * @title CSCCollectibleSale * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract CSCCollectibleSale is CSCCollectibleBase { event CollectibleBought (uint256 _assetId, address owner); event PriceUpdated (uint256 collectibleClass, uint256 newPrice, uint256 oldPrice); // SHIP DATATYPES & CONSTANTS // @dev ship Prices & price cap uint256 public PROMETHEUS_SHIP_PRICE = 0.25 ether; uint256 public INTREPID_SHIP_PRICE = 0.005 ether; uint256 public CROSAIR_SHIP_PRICE = 0.1 ether; uint256 public constant PROMETHEUS_MAX_PRICE = 0.85 ether; uint256 public constant INTREPID_MAX_PRICE = 0.25 ether; uint256 public constant CROSAIR_MAX_PRICE = 0.5 ether; uint256 public constant PROMETHEUS_PRICE_INCREMENT = 0.05 ether; uint256 public constant INTREPID_PRICE_INCREMENT = 0.002 ether; uint256 public constant CROSAIR_PRICE_INCREMENT = 0.01 ether; uint256 public constant PROMETHEUS_PRICE_THRESHOLD = 0.85 ether; uint256 public constant INTREPID_PRICE_THRESHOLD = 0.25 ether; uint256 public constant CROSAIR_PRICE_THRESHOLD = 0.5 ether; uint256 public prometheusSoldCount; uint256 public intrepidSoldCount; uint256 public crosairSoldCount; // VOUCHER DATATYPES & CONSTANTS uint256 public PROMETHEUS_VOUCHER_PRICE = 0.75 ether; uint256 public INTREPID_VOUCHER_PRICE = 0.2 ether; uint256 public CROSAIR_VOUCHER_PRICE = 0.35 ether; uint256 public prometheusVoucherSoldCount; uint256 public crosairVoucherSoldCount; uint256 public intrepidVoucherSoldCount; /// @dev Mapping created store the amount of value a wallet address used to buy assets mapping(address => uint256) addressToValue; /// @dev Mapping to holde the balance of each address, i.e. addrs -> collectibleType -> collectibleClass -> balance mapping(address => mapping(uint256 => mapping (uint256 => uint256))) addressToCollectibleTypeBalance; function _bid(uint256 _assetId, uint256 _price,uint256 _collectibleType,uint256 _collectibleClass, address _buyer) internal { CSCPreSaleItem memory _Obj = allPreSaleItems[_assetId]; if(_collectibleType == 1 && _collectibleClass == 1) { require(_price == PROMETHEUS_SHIP_PRICE); _Obj.owner = _buyer; _Obj.boughtTimestamp = now; addressToValue[_buyer] += _price; prometheusSoldCount++; if(prometheusSoldCount % 10 == 0){ if(PROMETHEUS_SHIP_PRICE < PROMETHEUS_PRICE_THRESHOLD){ PROMETHEUS_SHIP_PRICE += PROMETHEUS_PRICE_INCREMENT; } } } if(_collectibleType == 1 && _collectibleClass == 2) { require(_price == CROSAIR_SHIP_PRICE); _Obj.owner = _buyer; _Obj.boughtTimestamp = now; addressToValue[_buyer] += _price; crosairSoldCount++; if(crosairSoldCount % 10 == 0){ if(CROSAIR_SHIP_PRICE < CROSAIR_PRICE_THRESHOLD){ CROSAIR_SHIP_PRICE += CROSAIR_PRICE_INCREMENT; } } } if(_collectibleType == 1 && _collectibleClass == 3) { require(_price == INTREPID_SHIP_PRICE); _Obj.owner = _buyer; _Obj.boughtTimestamp = now; addressToValue[_buyer] += _price; intrepidSoldCount++; if(intrepidSoldCount % 10 == 0){ if(INTREPID_SHIP_PRICE < INTREPID_PRICE_THRESHOLD){ INTREPID_SHIP_PRICE += INTREPID_PRICE_INCREMENT; } } } if(_collectibleType == 0 &&_collectibleClass == 1) { require(_price == PROMETHEUS_VOUCHER_PRICE); _Obj.owner = _buyer; _Obj.boughtTimestamp = now; addressToValue[_buyer] += _price; prometheusVoucherSoldCount++; } if(_collectibleType == 0 && _collectibleClass == 2) { require(_price == CROSAIR_VOUCHER_PRICE); _Obj.owner = _buyer; _Obj.boughtTimestamp = now; addressToValue[_buyer] += _price; crosairVoucherSoldCount++; } if(_collectibleType == 0 && _collectibleClass == 3) { require(_price == INTREPID_VOUCHER_PRICE); _Obj.owner = _buyer; _Obj.boughtTimestamp = now; addressToValue[_buyer] += _price; intrepidVoucherSoldCount++; } addressToCollectibleTypeBalance[_buyer][_collectibleType][_collectibleClass]++; CollectibleBought(_assetId, _buyer); } function getCollectibleTypeBalance(address _owner, uint256 _collectibleType, uint256 _collectibleClass) external view returns(uint256) { require(_owner != address(0)); return addressToCollectibleTypeBalance[_owner][_collectibleType][_collectibleClass]; } function getCollectiblePrice(uint256 _collectibleType, uint256 _collectibleClass) external view returns(uint256 _price){ // For Ships if(_collectibleType == 1 && _collectibleClass == 1) { return PROMETHEUS_SHIP_PRICE; } if(_collectibleType == 1 && _collectibleClass == 2) { return CROSAIR_SHIP_PRICE; } if(_collectibleType == 1 && _collectibleClass == 3) { return INTREPID_SHIP_PRICE; } // For Vouchers if(_collectibleType == 0 && _collectibleClass == 1) { return PROMETHEUS_VOUCHER_PRICE; } if(_collectibleType == 0 && _collectibleClass == 2) { return CROSAIR_VOUCHER_PRICE; } if(_collectibleType == 0 && _collectibleClass == 3) { return INTREPID_VOUCHER_PRICE; } } } /* Lucid Sight, Inc. ERC-721 Collectibles. * @title LSNFT - Lucid Sight, Inc. Non-Fungible Token * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract CSCPreSaleManager is CSCCollectibleSale { event RefundClaimed(address owner, uint256 refundValue); // Ship Names string private constant prometheusShipName = "Vulcan Harvester"; string private constant crosairShipName = "Phoenix Cruiser"; string private constant intrepidShipName = "Reaper Interceptor"; bool CSCPreSaleInit = false; /// @dev Constructor creates a reference to the NFT (ERC721) ownership contract function CSCPreSaleManager() public { require(msg.sender != address(0)); paused = true; error = false; gameManagerPrimary = msg.sender; } function addToApprovedAddress (address _newAddr) onlyGameManager { require(_newAddr != address(0)); require(!approvedAddressList[_newAddr]); approvedAddressList[_newAddr] = true; } function removeFromApprovedAddress (address _newAddr) onlyGameManager { require(_newAddr != address(0)); require(approvedAddressList[_newAddr]); approvedAddressList[_newAddr] = false; } function() external payable { } /// @dev Bid Function which call the interncal bid function /// after doing all the pre-checks required to initiate a bid function bid(uint256 _collectibleType, uint256 _collectibleClass) external payable { require(msg.sender != address(0)); require(msg.sender != address(this)); require(_collectibleType >= 0 && _collectibleType <= 1); require(_isActive(_assetId)); bytes32 collectibleName; if(_collectibleType == 0){ collectibleName = bytes32("NoNameForVoucher"); if(_collectibleClass == 1){ require(prometheusVouchersMinted < PROMETHEUS_VOUCHER_LIMIT); collectibleName = stringToBytes32(prometheusShipName); prometheusVouchersMinted++; } if(_collectibleClass == 2){ require(crosairVouchersMinted < CROSAIR_VOUCHER_LIMIT); crosairVouchersMinted++; } if(_collectibleClass == 3){ require(intrepidVoucherSoldCount < INTREPID_VOUCHER_LIMIT); intrepidVouchersMinted++; } } if(_collectibleType == 1){ if(_collectibleClass == 1){ require(prometheusShipMinted < PROMETHEUS_SHIP_LIMIT); collectibleName = stringToBytes32(prometheusShipName); prometheusShipMinted++; } if(_collectibleClass == 2){ require(crosairShipMinted < CROSAIR_VOUCHER_LIMIT); collectibleName = stringToBytes32(crosairShipName); crosairShipMinted++; } if(_collectibleClass == 3){ require(intrepidShipMinted < INTREPID_SHIP_LIMIT); collectibleName = stringToBytes32(intrepidShipName); intrepidShipMinted++; } } uint256 _assetId = _createCollectible(collectibleName, _collectibleType, _collectibleClass); CSCPreSaleItem memory _Obj = allPreSaleItems[_assetId]; _bid(_assetId, msg.value, _Obj.collectibleType, _Obj.collectibleClass, msg.sender); _transfer(address(this), msg.sender, _assetId); } /// @dev Bid Function which call the interncal bid function /// after doing all the pre-checks required to initiate a bid function createReferralGiveAways(uint256 _collectibleType, uint256 _collectibleClass, address _toAddress) onlyGameManager external { require(msg.sender != address(0)); require(msg.sender != address(this)); require(_collectibleType >= 0 && _collectibleType <= 1); bytes32 collectibleName; if(_collectibleType == 0){ collectibleName = bytes32("ReferralGiveAwayVoucher"); if(_collectibleClass == 1){ collectibleName = stringToBytes32(prometheusShipName); } if(_collectibleClass == 2){ crosairVouchersMinted++; } if(_collectibleClass == 3){ intrepidVouchersMinted++; } } if(_collectibleType == 1){ if(_collectibleClass == 1){ collectibleName = stringToBytes32(prometheusShipName); } if(_collectibleClass == 2){ collectibleName = stringToBytes32(crosairShipName); } if(_collectibleClass == 3){ collectibleName = stringToBytes32(intrepidShipName); } } uint256 _assetId = _createCollectible(collectibleName, _collectibleType, _collectibleClass); CSCPreSaleItem memory _Obj = allPreSaleItems[_assetId]; _transfer(address(this), _toAddress, _assetId); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyGameManager whenPaused { // Actually unpause the contract. super.unpause(); } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT (ERC721) contract, but can be called either by /// the owner or the NFT (ERC721) contract. function withdrawBalance() onlyBanker { // We are using this boolean method to make sure that even if one fails it will still work bankManager.transfer(this.balance); } function claimRefund(address _ownerAddress) whenError { uint256 refundValue = addressToValue[_ownerAddress]; addressToValue[_ownerAddress] = 0; _ownerAddress.transfer(refundValue); RefundClaimed(_ownerAddress, refundValue); } function preSaleInit() onlyGameManager { require(!CSCPreSaleInit); require(allPreSaleItems.length == 0); CSCPreSaleInit = true; //Fill in index 0 to null requests CSCPreSaleItem memory _Obj = CSCPreSaleItem(0, stringToBytes32("DummyAsset"), 0, 0, 0, address(this), true); allPreSaleItems.push(_Obj); } function isRedeemed(uint256 _assetId) { require(approvedAddressList[msg.sender]); CSCPreSaleItem memory _Obj = allPreSaleItems[_assetId]; _Obj.isRedeemed = true; allPreSaleItems[_assetId] = _Obj; } }
Helps in fetching the attributes of the ship depending on the ship assetId : The actual ERC721 Asset ID sequenceId : Index w.r.t Ship type
function getShipDetails(uint256 _sequenceId, uint256 _shipClass) external view returns ( uint256 assetId, uint256 sequenceId, string shipName, uint256 collectibleClass, uint256 boughtTimestamp, address owner ) { uint256 _assetId = preSaleItemTypeToSequenceIdToCollectible[1][_shipClass][_sequenceId]; CSCPreSaleItem storage _collectibleObj = allPreSaleItems[_assetId]; require(_collectibleObj.collectibleType == 1); assetId = _assetId; sequenceId = _sequenceId; shipName = bytes32ToString(_collectibleObj.collectibleName); collectibleClass = _collectibleObj.collectibleClass; boughtTimestamp = _collectibleObj.boughtTimestamp; owner = _collectibleObj.owner; }
10,103,057
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //implementation of ERC721 Non-Fungible Token Standard import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; //implementation of ERC721 where tokens can be irreversibly burned (destroyed). import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; //implementation of ERC721 where transers can be paused import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; //For verifying messages in lazyMint import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; //Abstract that allows tokens to be listed and exchanged considering royalty fees import "./abstractions/ERC721Exchange.sol"; contract CollectableTime is ERC721, ERC721Burnable, ERC721Pausable, ERC721Exchange { //in only the contract owner can add a fee address private _admin; modifier onlyAdmin { require( _msgSender() == _admin, "Time: Restricted method access to only the admin" ); _; } /** * @dev Constructor function */ constructor (string memory _name, string memory _symbol) ERC721(_name, _symbol) { _admin = _msgSender(); } /** * @dev Sets a fee that will be collected during the exchange method */ function allocate(address recipient, uint256 fee) external virtual onlyAdmin { _allocateFee(recipient, fee); } /** * @dev Mints now and transfers to `recipient` */ function autoMint(address recipient) external virtual onlyAdmin { uint256 timestamp = block.timestamp; _safeMint(recipient, timestamp); } /** * @dev Removes a fee */ function deallocate(address recipient) external virtual onlyAdmin { _deallocateFee(recipient); } /** * @dev Allows anyone to self mint a token */ function lazyMint(uint256 tokenId, address recipient, bytes calldata proof) public virtual { //make sure the admin signed this off require( ECDSA.recover( ECDSA.toEthSignedMessageHash( keccak256( abi.encodePacked(tokenId, recipient) ) ), proof ) == _admin, "Time: Invalid proof." ); _safeMint(recipient, tokenId); } /** * @dev Mints `tokenId` and transfers to `recipient` */ function mint(uint256 tokenId, address recipient) external virtual onlyAdmin { _safeMint(recipient, tokenId); } /** * @dev Lists `tokenId` on the order book for `amount` in wei. */ function list(uint256 tokenId, uint256 amount) external virtual { _list(tokenId, amount); } /** * @dev Removes `tokenId` from the order book. */ function delist(uint256 tokenId) external virtual { _delist(tokenId); } /** * @dev Allows for a sender to exchange `tokenId` for the listed amount */ function exchange(uint256 tokenId) external virtual override payable { _exchange(tokenId, msg.value); } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual onlyAdmin { _pause(); } /** * @dev Returns the total supply of time */ function totalSupply() external view returns(uint256) { return block.timestamp; } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual onlyAdmin { _unpause(); } /** * @dev Resolves duplicate _beforeTokenTransfer method definition * between ERC721 and ERC721Pausable */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } }
Allows for a sender to exchange `tokenId` for the listed amount/
function exchange(uint256 tokenId) external virtual override payable { _exchange(tokenId, msg.value); }
1,017,646
pragma solidity ^0.5.0; import "../accounts/IAuthorizedTokenTransferer.sol"; import "openzeppelin-solidity/contracts/access/roles/WhitelistedRole.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/math/Math.sol"; /** * @title AuthorizedTokenTransferer * @dev Use this contract as a proxy for sending ERC20 tokens from one address to another. The purpose * of this contract is to have a a reusable destination for receiving ERC20 token approvals. * The sender must call ERC20.approve(this address, amount) before attempting any transfer. * * This contract has two different flavors of token transfer functions: * 1) Transfer a specified amount; fail if that amount cannot be transferred. * 2) Calculates the amount of tokens that are transferable and send that amount. * * Calls to the transfer functions are gated behind whitelisted access, which should only be granted to subscriptions * created in a trusted manner (i.e. via SubscriptionFrontEnd.sol or an equivalent factory/frontend created by a trusted developer). */ contract AuthorizedTokenTransferer is IAuthorizedTokenTransferer, WhitelistedRole { event TokenTransferred( address indexed from, address indexed to, IERC20 indexed token, uint amount ); event TokenMaxTransferred( address indexed from, address indexed to, IERC20 indexed token, uint amount, uint remainingAmount ); /** * @dev Transfers a specified amount of ERC20 tokens, and fails if that amount is not transferrable * (due to insufficient balance, lack of token approval for the input amount, etc.). * @param from The address tokens will be transferred from. * @param to The address tokens will be transferred to. * @param token The address of the IERC20 token that will be transferred. * @param amount The amount of tokens to transfer. */ function transfer( address from, address to, IERC20 token, uint amount ) public onlyWhitelisted { require (token.allowance(from, address(this)) >= amount, "Token transfer not authorized"); token.transferFrom(from, to, amount); emit TokenTransferred(from, to, token, amount); } /** * @dev Calculates how many tokens are actually transferable, up to a max of the input amount. * Call is designed to not fail - no transfer occurs if no amount is possible to transfer. * @param from The address tokens will be transferred from. * @param to The address tokens will be transferred to. * @param token The address of the IERC20 token that will be transferred. * @param amount The maximum amount of tokens to transfer. * @return The amount that was paid, and the amount that was unpaid. */ function transferMax( address from, address to, IERC20 token, uint amount ) public onlyWhitelisted returns (uint amountPaid, uint remainingAmount) { // check how much the transferer is authorized to send on behalf of the payor uint authorizedAmount = token.allowance(from, address(this)); uint availableBalance = token.balanceOf(from); amountPaid = Math.min(amount, Math.min(authorizedAmount, availableBalance)); if (amountPaid > 0) { remainingAmount = amount - amountPaid; token.transferFrom(from, to, amountPaid); emit TokenMaxTransferred(from, to, token, amountPaid, remainingAmount); } else { remainingAmount = amount; } return (amountPaid, remainingAmount); } }
Calculates how many tokens are actually transferable, up to a max of the input amount. Call is designed to not fail - no transfer occurs if no amount is possible to transfer. from The address tokens will be transferred from. to The address tokens will be transferred to. token The address of the IERC20 token that will be transferred. amount The maximum amount of tokens to transfer. return The amount that was paid, and the amount that was unpaid./ check how much the transferer is authorized to send on behalf of the payor
function transferMax( address from, address to, IERC20 token, uint amount ) public onlyWhitelisted returns (uint amountPaid, uint remainingAmount) { uint authorizedAmount = token.allowance(from, address(this)); uint availableBalance = token.balanceOf(from); amountPaid = Math.min(amount, Math.min(authorizedAmount, availableBalance)); if (amountPaid > 0) { remainingAmount = amount - amountPaid; token.transferFrom(from, to, amountPaid); emit TokenMaxTransferred(from, to, token, amountPaid, remainingAmount); remainingAmount = amount; } return (amountPaid, remainingAmount); }
1,791,911
./full_match/80001/0x1afC6a78a4887b538e80E9E2455Bf4EC932b5270/sources/SoundMarket.sol
Returns the market fee of the contract /
function getMarketFee() public view returns (uint256) { return _marketFee; }
5,676,220
pragma solidity 0.8.0; // SPDX-License-Identifier: Apache-2.0 import "../modules/query/IQuery.sol"; import "../modules/query/IQueryController.sol"; import "../shared/WithRegistry.sol"; contract OracleOwnerService is WithRegistry { bytes32 public constant NAME = "OracleOwnerService"; // solhint-disable-next-line no-empty-blocks constructor(address _registry) WithRegistry(_registry) {} function proposeOracleType( bytes32 _oracleTypeName, string calldata _inputFormat, string calldata _callbackFormat ) external { // todo: oracle owner should be approved query().proposeOracleType( _oracleTypeName, _inputFormat, _callbackFormat ); } function proposeOracle(bytes32 _name) external returns (uint256 _oracleId) { // todo: oracle owner should be approved _oracleId = query().proposeOracle(_name, msg.sender); } function proposeOracleToOracleType( bytes32 _oracleTypeName, uint256 _oracleId ) external { // todo: oracle owner should be approved query().proposeOracleToOracleType(_oracleTypeName, _oracleId); } function updateOracleContract(address _newOracleContract, uint256 _oracleId) external { // todo: oracle owner should be approved query().updateOracleContract(_newOracleContract, _oracleId); } function revokeOracleFromOracleType( bytes32 _oracleTypeName, uint256 _oracleId ) external { // todo: oracle owner should be approved query().revokeOracleFromOracleType(_oracleTypeName, _oracleId); } /* Lookup */ function query() internal view returns (IQueryController) { return IQueryController(registry.getContract("Query")); } }
todo: oracle owner should be approved
function proposeOracle(bytes32 _name) external returns (uint256 _oracleId) { _oracleId = query().proposeOracle(_name, msg.sender); }
5,503,247
pragma solidity >=0.4.21 <0.7.0; contract Isettle{ //state variables address owner; address[] public adminsList; uint[] public lawyersList; address[] public expertsList; string[] public claimantsList; string[] public respondentsList; address[] public caseList; address[] public inmateList; uint16 public adminIndex; uint public caseCount; uint public claimantsIndex; uint public lawyersIndex; uint public expertsIndex; uint public respondentsIndex; uint public inmateCount; uint public donationTotal; uint public donationCount; struct Admin{ address adminId; bool isAdmin; } struct Lawyers{ address lawyersId; string fullName; string email; uint phoneNumber; string speciality; uint supremeCourtNo; bool isLawyer; address caseId; } struct Experts{ address expertsId; string fullName; string email; uint phoneNumber; string speciality; bool isExpert; address caseId; } struct Case{ address caseId; string complaints;//complainants agitation string response; //defendants response string settlement;//The lawyers(s) settlement string caseSpeciality; bool isSettled;//To know if a case is settled or not bool caseExist;//To know if a case already exist or no } struct Complainants{ address complainantsId; string fullName; string email; uint phoneNumber; string expertise; address caseId; } struct Respondents{ address respondentsId; string fullName; uint phoneNumber; string email; string expertise; address caseId; } struct Inmates{ address inmateId; string fullName; string homeAddress; bytes32 inmateNumber; uint bailFee; bool exist; bool isFreed; } enum caseStatus {pending,ongoing,defaulted,settled} caseStatus public casestatus; mapping (address =>Lawyers)public lawyersmap; mapping(address =>Experts)public expertsmap; mapping(address =>Case) public casesmap; mapping(address =>Complainants) public complainantsmap; mapping(address =>Respondents) public respondentsmap; mapping(address => Admin) public adminsmap; mapping(address => uint256) balances; //MODIFIERS modifier onlyOwner(){ require(msg.sender == owner, "Access denied,not the owner"); _; } modifier onlyAdmins{ require(adminsmap[msg.sender].isAdmin,"Access denied,only admin"); _; } modifier onlyExperts(){ require(expertsmap[msg.sender].isExpert,"Access denied,only expert"); _; } modifier onlyLawyers(){ require(lawyersmap[msg.sender].isLawyer,"Access denied,only lawyer"); _; } //modifier onlyExperts(string memory _speciality){ //Experts memory expertStruct; //require(expertsmap[msg.sender].isExpert == true && // keccak256(abi.encodePacked(expertStruct.speciality)) //== keccak256(abi.encodePacked(_speciality)),"Not an expert or in the field"); // _; //} //modifier onlyLawyers(string memory _speciality){ // Lawyers memory lawyerStruct; //require(lawyersmap[msg.sender].isLawyer == true && //keccak256(abi.encodePacked(lawyerStruct.speciality)) //== keccak256(abi.encodePacked(_speciality)),"Not an expert or in the field"); //_; //} //EVENTS event AdminAdded(address newAdmin,uint indexed adminIndex); event lawyersAdded(string msg,string indexed fullName,string speciality,uint _supremeCourtNo); event expertsAdded(string msg,string indexed fullName,string speciality); event AdminRemoved(address admin,uint indexed adminIndex); event LawyerRemoved(address lawyerAddress,uint indexed lawyersIndex); event ExpertRemoved(address expertAddress,uint indexed lawyersIndex); event CaseAdded(string msg,address indexed caseId,string caseSpeciality,string complaints); event ResponseAdded(string msg,address indexed caseId,string caseSpeciality,string _response); event CaseAnalysisAdded(string msg,address indexed caseId,string caseSpeciality,string ); event CaseResolutionAdded(string msg,address indexed caseId,string caseSpeciality,string response); event NewInmateAdded(string msg,address _inmateId, string _fullName,string _homeAddress,bytes32 _inmateNumber,uint _bailFee); //CONSTRUCTOR constructor() public{ owner = msg.sender; addAdmin(owner); casestatus = caseStatus.pending; } //FUNCTIONS //Allows owner to add an admin function addAdmin(address _newAdmin) public onlyOwner{ Admin memory _admin; require(adminsmap[_newAdmin].isAdmin == false,"Admin already exist"); adminsmap[_newAdmin] = _admin; adminsmap[_newAdmin].isAdmin = true; adminIndex += 1; adminsList.push(_newAdmin); emit AdminAdded(_newAdmin,adminIndex); } //Allows admins to add lawyers function addLawyer(address _lawyersId,string memory _fullName,string memory _email,uint _phoneNumber,string memory _speciality,uint _supremeCourtNo)public onlyAdmins { Experts memory _expertStruct; Lawyers memory _lawyerStruct; require(_expertStruct.isExpert == false,"Already registered as an expert"); require(_lawyerStruct.isLawyer == false,"Already registered as a lawyer"); require(adminsmap[_lawyersId].isAdmin == false,"Address already exist as an admin"); _lawyerStruct.lawyersId =_lawyersId; _lawyerStruct.email =_email; _lawyerStruct.phoneNumber = _phoneNumber; _lawyerStruct.fullName =_fullName; _lawyerStruct.speciality =_speciality; _lawyerStruct.supremeCourtNo =_supremeCourtNo; caseCount = 0; lawyersIndex += 1; lawyersList.push(_supremeCourtNo); emit lawyersAdded("New lawyer added:",_fullName,_speciality,_supremeCourtNo); } //Allows admin to add experts function addExpert(address _expertsId,string memory _fullName,string memory _email,uint _phoneNumber,string memory _speciality)public onlyAdmins { Lawyers memory _lawyerStruct; Experts memory _expertStruct; require(adminsmap[_expertsId].isAdmin == false,"Address already exist as an admin"); require(_expertStruct.isExpert == false,"Expert already exist"); require(_lawyerStruct.isLawyer == false,"Already registered as a lawyer"); _expertStruct.expertsId = _expertsId; _expertStruct.fullName =_fullName; _expertStruct.phoneNumber =_phoneNumber; _expertStruct.email =_email; _expertStruct.speciality =_speciality; caseCount = 0; expertsIndex += 1; emit expertsAdded("New expert added:",_fullName,_speciality); } function addComplainant(address _complainantsId,string memory _fullName,string memory _email,uint _phoneNumber)public onlyAdmins { //Case memory caseStruct; require(adminsmap[_complainantsId].isAdmin == false,"Address already exist as an admin"); Complainants memory complainantStruct; complainantStruct.complainantsId =_complainantsId; complainantStruct.fullName =_fullName; complainantStruct.email =_email; complainantStruct.phoneNumber =_phoneNumber; claimantsIndex += 1; claimantsList.push(_fullName); // emit lawyersAdded("New lawyer added:",_fullName,_speciality,_supremeCourtNo); } function addRespondents(address _respondentsId,string memory _fullName,uint _phoneNumber, string memory _email)public onlyAdmins { Respondents memory respondentStruct; respondentStruct.respondentsId =_respondentsId; respondentStruct.fullName =_fullName; respondentStruct.email =_email; respondentStruct.phoneNumber =_phoneNumber; respondentsIndex += 1; respondentsList.push(_email); //emit respondentsAdded("New lawyer added:",_fullName,_speciality,_supremeCourtNo); } //Allow the current owner to remove an Admin function removeAdmin(address _adminAddress) public onlyOwner{ require(adminsmap[_adminAddress].isAdmin == true,"Sorry,address is not an admin"); require(adminIndex > 1,"Atleast one admin is required"); require(_adminAddress != owner,"owner cannot be removed"); delete adminsmap[_adminAddress]; adminIndex -= 1; emit AdminRemoved( _adminAddress,adminIndex); } function removeLawyer(address _lawyerAddress) public onlyOwner{ require(lawyersmap[_lawyerAddress].isLawyer == true,"Sorry,address is not a lawyer"); require(lawyersIndex > 1,"Atleast one lawyer is required"); require(_lawyerAddress != owner,"owner cannot be removed"); delete lawyersmap[_lawyerAddress]; adminIndex -= 1; emit LawyerRemoved( _lawyerAddress,lawyersIndex); } function removeExpert(address _expertAddress) public onlyOwner{ require(expertsmap[_expertAddress].isExpert == true,"Sorry,address is not an expert"); require(expertsIndex > 1,"Atleast one expert is required"); require(_expertAddress != owner,"owner cannot be removed"); delete expertsmap[_expertAddress]; adminIndex -= 1; emit ExpertRemoved( _expertAddress,expertsIndex); } function lodgeComplaint(address _caseId,string memory _caseSpeciality,string memory _complaint)public { Case memory _caseStruct; require(_caseStruct.caseExist == false,"Case already exist"); require(_caseStruct.isSettled == false,"Case has been settled by a lawyer"); require(casesmap[_caseId].caseExist == false,"Case already exist"); _caseStruct.caseId = _caseId; _caseStruct.caseSpeciality =_caseSpeciality; caseCount += 1; caseList.push(_caseId); emit CaseAdded("New case added:",_caseId,_caseSpeciality,_complaint); } function respondToComplaint(address _caseId,string memory _caseSpeciality,string memory _response)public { Case memory _caseStruct; require(_caseStruct.caseExist == true,"Case does not exist"); require(_caseStruct.isSettled == false,"Case has been settled by a lawyer"); _caseStruct.caseId = _caseId; _caseStruct.caseSpeciality =_caseSpeciality; caseCount += 1; caseList.push(_caseId); emit ResponseAdded("New response added:",_caseId,_caseSpeciality,_response); } function analyseCase(address _caseId,string memory _caseSpeciality,string memory _analysis)public onlyExperts { Case memory _caseStruct; require(_caseStruct.caseExist == false,"Case already exist"); require(_caseStruct.isSettled == false,"Case has been settled by a lawyer"); require(casesmap[_caseId].caseExist == false,"Case already exist"); _caseStruct.caseId = _caseId; _caseStruct.caseSpeciality =_caseSpeciality; caseCount += 1; caseList.push(_caseId); emit CaseAnalysisAdded("New case analysis added:",_caseId,_caseSpeciality,_analysis); } function resolveDispute(address _caseId,string memory _caseSpeciality,string memory _resolution)public onlyLawyers { Case memory _caseStruct; require(_caseStruct.caseExist == false,"Case already exist"); require(_caseStruct.isSettled == false,"Case has been settled by a lawyer"); require(casesmap[_caseId].caseExist == false,"Case already exist"); _caseStruct.caseId = _caseId; _caseStruct.caseSpeciality =_caseSpeciality; caseCount += 1; caseList.push(_caseId); emit CaseResolutionAdded("New case resolution added:",_caseId,_caseSpeciality,_resolution); } function addInmate(address _inmateId,string memory _fullName,string memory _homeAddress,bytes32 _inmateNumber,uint _bailFee)public { Inmates memory inmateStruct; require(inmateStruct.exist == false,"inmate already exist"); inmateStruct.inmateId = _inmateId; inmateStruct.fullName =_fullName; inmateStruct.homeAddress =_homeAddress; inmateStruct.inmateNumber =_inmateNumber; inmateStruct.bailFee =_bailFee; inmateCount += 1; inmateList.push(_inmateId); emit NewInmateAdded("New inmate added:",_inmateId,_fullName,_homeAddress,_inmateNumber,_bailFee); } function freeInmate(address inmateId,string memory fullName,bytes32 inmateNumber,uint bailFee)public { Inmates memory inmateStruct; require(inmateStruct.exist == true,"inmate does not exist"); require(inmateStruct.isFreed == false,"inmate"); } function donateEth(uint _donation) public payable { balances[msg.sender] -= _donation; donationTotal += _donation; donationCount += 1; require(_donation >= 5000000000000000,"Below minimum donation"); } function withdraw(uint _withdrawal) public payable onlyOwner{ balances[msg.sender] += _withdrawal; donationTotal -= _withdrawal; require(msg.sender.send(donationTotal)); } }
Allows admins to add lawyers
function addLawyer(address _lawyersId,string memory _fullName,string memory _email,uint _phoneNumber,string memory _speciality,uint _supremeCourtNo)public onlyAdmins { Experts memory _expertStruct; Lawyers memory _lawyerStruct; require(_expertStruct.isExpert == false,"Already registered as an expert"); require(_lawyerStruct.isLawyer == false,"Already registered as a lawyer"); require(adminsmap[_lawyersId].isAdmin == false,"Address already exist as an admin"); _lawyerStruct.lawyersId =_lawyersId; _lawyerStruct.email =_email; _lawyerStruct.phoneNumber = _phoneNumber; _lawyerStruct.fullName =_fullName; _lawyerStruct.speciality =_speciality; _lawyerStruct.supremeCourtNo =_supremeCourtNo; caseCount = 0; lawyersIndex += 1; lawyersList.push(_supremeCourtNo); emit lawyersAdded("New lawyer added:",_fullName,_speciality,_supremeCourtNo); }
5,379,026
pragma solidity >=0.4.21 <0.7.0; pragma experimental ABIEncoderV2; contract Election { struct Voter { bool voted; uint optionId; } struct Option { string name; uint noVotes; } // uint maxVoters = 15; uint countVoters = 0; // address chairperson; mapping(address => Voter) voters; Option[] options; uint256 deadline = 0; constructor (string[] memory optionNames) public { chairperson = msg.sender; for (uint i = 0; i < optionNames.length; i++) { options.push( Option({ name: optionNames[i], noVotes: 0 })); } deadline = block.timestamp + 120; } function isVotingOpen() public view returns (bool){ if(deadline == 0 || deadline == 1 || block.timestamp > deadline) return false; return true; } function getDeadline() public view returns (uint256){ return deadline; } function getBlockStamp() public view returns (uint256){ return block.timestamp; } function votedAlready(address addr) public view returns (Voter memory){ return voters[addr]; } function startVoting(uint secTillDeadLine) public { require(msg.sender == chairperson, 'You do not have the right to initiate this action!'); deadline = block.timestamp + secTillDeadLine; } function vote(uint option) public { require(block.timestamp <= deadline, 'You are not able to vote!'); require(option < options.length, 'Invallid option!'); address voter = msg.sender; if (voters[voter].voted == true) { options[voters[voter].optionId].noVotes--; } // else{ countVoters ++; //am numarat cati au votat, indiferent daca si-au schimbat votul } // voters[voter].voted = true; voters[voter].optionId = option; options[option].noVotes++; } function viewOptions() public view returns (string[] memory) { string[] memory _options = new string[](options.length); for (uint i = 0; i < options.length; i++) { _options[i] = options[i].name; } return _options; } function viewResults() public view returns (string memory, uint, uint) { require(deadline > 0 && block.timestamp > deadline, 'The voting process has not ended yet!'); uint maxNoVotes = options[0].noVotes; uint noVoters = maxNoVotes; uint winnerId = 0; for (uint i = 1; i < options.length; i++) { if (options[i].noVotes > maxNoVotes) { maxNoVotes = options[i].noVotes; winnerId = i; } noVoters += options[i].noVotes; } return (options[winnerId].name, noVoters, maxNoVotes); } function showNoVoters() public view returns (uint){ //cati au votat pana acum, asta poate vedea doar admin-ul require(msg.sender == chairperson, 'You do not have the right to initiate this action!'); require(deadline != 0,'The voting process has not started yet!'); return countVoters; } function stopVoting() public { require(msg.sender == chairperson, 'You do not have the right to initiate this action!'); require(deadline != 0,'The voting process has not started yet, so you can not stop it!'); deadline = 1; } function adviserElection() public view returns(string memory){ //putem opri votul cand stim ca au votat mai mult de jumate din candidati, si toate voturile le are exclusiv cineva require(msg.sender == chairperson, 'You do not have the right to initiate this action!'); bool say = false; require(deadline != 0,'The voting process has not started yet!'); require(countVoters >= (maxVoters/2 + 1),'Half of the candidates have not yet voted, I can not advise you'); uint maxVotes = options[0].noVotes; for (uint i = 1; i < options.length; i++ ){ //are warning din cauza break-ului if(options[i].noVotes > maxVotes) maxVotes = options[i].noVotes; if(maxVotes >= (maxVoters/2 + 1)) say = true; break; //iesim, nu mai are rost sa votam } if(maxVotes >= (maxVoters/2 +1)) say = true; if(say == true) return "The Election can end, we have already a winner"; else return "If you stop the election right now, it will not be a fair voting"; } function modifyCandidateName(uint candidate,string memory newName)public{ require(msg.sender == chairperson, 'You do not have the right to initiate this action!'); require(deadline == 0 ,'The voting has started or ended, you can not modify the candidates'); require(candidate < options.length, 'Invalid option, give me a valid number!'); options[candidate].name = newName; } }
cati au votat pana acum, asta poate vedea doar admin-ul
function showNoVoters() public view returns (uint){
5,433,503
// File: contracts/zeppelin/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/zeppelin/ownership/Secondary.sol pragma solidity ^0.5.0; /** * @dev A Secondary contract can only be used by its primary account (the one that created it). */ contract Secondary is Context { address private _primary; /** * @dev Emitted when the primary contract changes. */ event PrimaryTransferred( address recipient ); /** * @dev Sets the primary account to the one that is creating the Secondary contract. */ constructor () internal { _primary = _msgSender(); emit PrimaryTransferred(_primary); } /** * @dev Reverts if called from any account other than the primary. */ modifier onlyPrimary() { require(_msgSender() == _primary, "Secondary: caller is not the primary account"); _; } /** * @return the address of the primary. */ function primary() public view returns (address) { return _primary; } /** * @dev Transfers contract to a new primary. * @param recipient The address of new primary. */ function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0), "Secondary: new primary is the zero address"); _primary = recipient; emit PrimaryTransferred(_primary); } } // File: contracts/ISideTokenFactory.sol pragma solidity ^0.5.0; interface ISideTokenFactory { function createSideToken(string calldata name, string calldata symbol, uint256 granularity) external returns(address); event SideTokenCreated(address indexed sideToken, string symbol, uint256 granularity); } // File: contracts/zeppelin/token/ERC777/IERC777.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * [ERC1820 registry standard](https://eips.ethereum.org/EIPS/eip-1820) to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See `IERC1820Registry` and * `ERC1820Implementer`. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See `IERC777Sender` and `IERC777Recipient`. * * Emits a `Sent` event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the `tokensReceived` * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See `IERC777Sender`. * * Emits a `Burned` event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See `operatorSend` and `operatorBurn`. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See `isOperatorFor`. * * Emits an `AuthorizedOperator` event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See `isOperatorFor` and `defaultOperators`. * * Emits a `RevokedOperator` event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if `authorizeOperator` was never called on * them. * * This list is immutable, but individual holders may revoke these via * `revokeOperator`, in which case `isOperatorFor` will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See `IERC777Sender` and `IERC777Recipient`. * * Emits a `Sent` event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the `tokensReceived` * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See `IERC777Sender`. * * Emits a `Burned` event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // File: contracts/zeppelin/token/ERC777/IERC777Recipient.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of `IERC777` tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820). * * See `IERC1820Registry` and `ERC1820Implementer`. */ interface IERC777Recipient { /** * @dev Called by an `IERC777` token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * `IERC777.balanceOf`, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint amount, bytes calldata userData, bytes calldata operatorData ) external; } // File: contracts/zeppelin/token/ERC777/IERC777Sender.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * `IERC777` Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820). * * See `IERC1820Registry` and `ERC1820Implementer`. */ interface IERC777Sender { /** * @dev Called by an `IERC777` token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * `IERC777.balanceOf`, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint amount, bytes calldata userData, bytes calldata operatorData ) external; } // File: contracts/zeppelin/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/zeppelin/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/zeppelin/utils/Address.sol pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } } // File: contracts/zeppelin/introspection/IERC1820Registry.sol pragma solidity ^0.5.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // File: contracts/zeppelin/token/ERC777/ERC777.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name, string memory symbol, address[] memory defaultOperators ) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(_msgSender(), _msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "ERC777: transfer to zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes calldata data) external { _burn(_msgSender(), _msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator"); _send(_msgSender(), sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator"); _burn(_msgSender(), account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "ERC777: transfer to zero address"); require(holder != address(0), "ERC777: transfer from zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { require(account != address(0), "ERC777: mint to zero address"); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from zero address"); require(to != address(0), "ERC777: send to zero address"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal { require(from != address(0), "ERC777: burn from zero address"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } function _approve(address holder, address spender, uint256 value) internal { // TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is // currently unnecessary. //require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } } // File: contracts/IERC677Receiver.sol pragma solidity ^0.5.0; interface IERC677Receiver { function onTokenTransfer(address _sender, uint _value, bytes calldata _data) external; } // File: contracts/ISideToken.sol pragma solidity ^0.5.0; interface ISideToken { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external pure returns (uint8); function granularity() external view returns (uint256); function burn(uint256 amount, bytes calldata data) external; function mint(address account, uint256 amount, bytes calldata userData, bytes calldata operatorData) external; function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function send(address recipient, uint256 amount, bytes calldata data) external; 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); } // File: contracts/SideToken_v1.sol pragma solidity ^0.5.0; contract SideToken_v1 is ISideToken, ERC777 { using Address for address; using SafeMath for uint256; address public minter; uint256 private _granularity; event Transfer(address,address,uint256,bytes); constructor(string memory _tokenName, string memory _tokenSymbol, address _minterAddr, uint256 _newGranularity) ERC777(_tokenName, _tokenSymbol, new address[](0)) public { require(_minterAddr != address(0), "SideToken: Minter address is null"); require(_newGranularity >= 1, "SideToken: Granularity must be equal or bigger than 1"); minter = _minterAddr; _granularity = _newGranularity; } modifier onlyMinter() { require(_msgSender() == minter, "SideToken: Caller is not the minter"); _; } function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external onlyMinter { _mint(_msgSender(), account, amount, userData, operatorData); } /** * @dev ERC677 transfer token with additional data if the recipient is a contact. * @param recipient The address to transfer to. * @param amount The amount to be transferred. * @param data The extra data to be passed to the receiving contract. */ function transferAndCall(address recipient, uint amount, bytes calldata data) external returns (bool success) { address from = _msgSender(); _send(from, from, recipient, amount, data, "", false); emit Transfer(from, recipient, amount, data); IERC677Receiver(recipient).onTokenTransfer(from, amount, data); return true; } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `amount` is multiple of the granularity /// @param amount The quantity that want's to be checked function requireGranularityMultiple(uint256 amount) internal view { require(amount.mod(_granularity) == 0, "SideToken: Balance is not a multiple of Granularity"); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { requireGranularityMultiple(balanceOf(from).sub(amount)); requireGranularityMultiple(balanceOf(to).add(amount)); super._move(operator, from, to, amount, userData, operatorData); } function _burn( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal { requireGranularityMultiple(balanceOf(from).sub(amount)); super._burn(operator, from, amount, data, operatorData); } function _mint( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { requireGranularityMultiple(balanceOf(account).add(amount)); super._mint(operator, account, amount, userData, operatorData); } function granularity() public view returns (uint256) { return _granularity; } } // File: contracts/SideTokenFactory_v1.sol pragma solidity ^0.5.0; contract SideTokenFactory_v1 is ISideTokenFactory, Secondary { function createSideToken(string calldata name, string calldata symbol, uint256 granularity) external onlyPrimary returns(address) { address sideToken = address(new SideToken_v1(name, symbol, primary(), granularity)); emit SideTokenCreated(sideToken, symbol, granularity); return sideToken; } }
See {IERC777-revokeOperator}./
function revokeOperator(address operator) external { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); }
2,056,616
pragma solidity ^0.5.10; contract NEST_NodeSave { IBMapping mappingContract; IBNEST nestContract; constructor (address map) public { mappingContract = IBMapping(address(map)); nestContract = IBNEST(address(mappingContract.CHECKADDRESS222("nest"))); } function CHANGEMAPPING301(address map) public ONLYOWNER374 { //inject NONSTANDARD NAMING mappingContract = IBMapping(address(map)); nestContract = IBNEST(address(mappingContract.CHECKADDRESS222("nest"))); } function TURNOUT485(uint256 amount, address to) public ONLYMININGCALCULATION602 returns(uint256) { //inject NONSTANDARD NAMING uint256 leftNum = nestContract.BALANCEOF780(address(this)); if (leftNum >= amount) { nestContract.TRANSFER685(to, amount); return amount; } else { return 0; } } modifier ONLYOWNER374(){ //inject NONSTANDARD NAMING require(mappingContract.CHECKOWNERS909(msg.sender) == true); _; } modifier ONLYMININGCALCULATION602(){ //inject NONSTANDARD NAMING require(address(mappingContract.CHECKADDRESS222("nodeAssignment")) == msg.sender); _; } } contract NEST_NodeAssignmentData { using SafeMath for uint256; IBMapping mappingContract; uint256 nodeAllAmount = 0; mapping(address => uint256) nodeLatestAmount; constructor (address map) public { mappingContract = IBMapping(map); } function CHANGEMAPPING301(address map) public ONLYOWNER374{ //inject NONSTANDARD NAMING mappingContract = IBMapping(map); } // Add nest function ADDNEST102(uint256 amount) public ONLYNODEASSIGNMENT511 { //inject NONSTANDARD NAMING nodeAllAmount = nodeAllAmount.ADD302(amount); } // View cumulative total function CHECKNODEALLAMOUNT929() public view returns (uint256) { //inject NONSTANDARD NAMING return nodeAllAmount; } // Record last received quantity function ADDNODELATESTAMOUNT655(address add ,uint256 amount) public ONLYNODEASSIGNMENT511 { //inject NONSTANDARD NAMING nodeLatestAmount[add] = amount; } // View last received quantity function CHECKNODELATESTAMOUNT653(address add) public view returns (uint256) { //inject NONSTANDARD NAMING return nodeLatestAmount[address(add)]; } modifier ONLYOWNER374(){ //inject NONSTANDARD NAMING require(mappingContract.CHECKOWNERS909(msg.sender) == true); _; } modifier ONLYNODEASSIGNMENT511(){ //inject NONSTANDARD NAMING require(address(msg.sender) == address(mappingContract.CHECKADDRESS222("nodeAssignment"))); _; } } contract NEST_NodeAssignment { using SafeMath for uint256; IBMapping mappingContract; IBNEST nestContract; SuperMan supermanContract; NEST_NodeSave nodeSave; NEST_NodeAssignmentData nodeAssignmentData; constructor (address map) public { mappingContract = IBMapping(map); nestContract = IBNEST(address(mappingContract.CHECKADDRESS222("nest"))); supermanContract = SuperMan(address(mappingContract.CHECKADDRESS222("nestNode"))); nodeSave = NEST_NodeSave(address(mappingContract.CHECKADDRESS222("nestNodeSave"))); nodeAssignmentData = NEST_NodeAssignmentData(address(mappingContract.CHECKADDRESS222("nodeAssignmentData"))); } function CHANGEMAPPING301(address map) public ONLYOWNER374{ //inject NONSTANDARD NAMING mappingContract = IBMapping(map); nestContract = IBNEST(address(mappingContract.CHECKADDRESS222("nest"))); supermanContract = SuperMan(address(mappingContract.CHECKADDRESS222("nestNode"))); nodeSave = NEST_NodeSave(address(mappingContract.CHECKADDRESS222("nestNodeSave"))); nodeAssignmentData = NEST_NodeAssignmentData(address(mappingContract.CHECKADDRESS222("nodeAssignmentData"))); } function BOOKKEEPING887(uint256 amount) public { //inject NONSTANDARD NAMING require(amount > 0); require(nestContract.BALANCEOF780(address(msg.sender)) >= amount); require(nestContract.ALLOWANCE615(address(msg.sender), address(this)) >= amount); require(nestContract.TRANSFERFROM303(address(msg.sender), address(nodeSave), amount)); nodeAssignmentData.ADDNEST102(amount); } function NODEGET172() public { //inject NONSTANDARD NAMING require(address(msg.sender) == address(tx.origin)); require(supermanContract.BALANCEOF780(address(msg.sender)) > 0); uint256 allAmount = nodeAssignmentData.CHECKNODEALLAMOUNT929(); uint256 amount = allAmount.SUB809(nodeAssignmentData.CHECKNODELATESTAMOUNT653(address(msg.sender))); uint256 getAmount = amount.MUL451(supermanContract.BALANCEOF780(address(msg.sender))).DIV932(1500); require(nestContract.BALANCEOF780(address(nodeSave)) >= getAmount); nodeSave.TURNOUT485(getAmount,address(msg.sender)); nodeAssignmentData.ADDNODELATESTAMOUNT655(address(msg.sender),allAmount); } function NODECOUNT170(address fromAdd, address toAdd) public { //inject NONSTANDARD NAMING require(address(supermanContract) == address(msg.sender)); require(supermanContract.BALANCEOF780(address(fromAdd)) > 0); uint256 allAmount = nodeAssignmentData.CHECKNODEALLAMOUNT929(); uint256 amountFrom = allAmount.SUB809(nodeAssignmentData.CHECKNODELATESTAMOUNT653(address(fromAdd))); uint256 getAmountFrom = amountFrom.MUL451(supermanContract.BALANCEOF780(address(fromAdd))).DIV932(1500); require(nestContract.BALANCEOF780(address(nodeSave)) >= getAmountFrom); nodeSave.TURNOUT485(getAmountFrom,address(fromAdd)); nodeAssignmentData.ADDNODELATESTAMOUNT655(address(fromAdd),allAmount); uint256 amountTo = allAmount.SUB809(nodeAssignmentData.CHECKNODELATESTAMOUNT653(address(toAdd))); uint256 getAmountTo = amountTo.MUL451(supermanContract.BALANCEOF780(address(toAdd))).DIV932(1500); require(nestContract.BALANCEOF780(address(nodeSave)) >= getAmountTo); nodeSave.TURNOUT485(getAmountTo,address(toAdd)); nodeAssignmentData.ADDNODELATESTAMOUNT655(address(toAdd),allAmount); } // Amount available to the guardian node function CHECKNODENUM994() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 allAmount = nodeAssignmentData.CHECKNODEALLAMOUNT929(); uint256 amount = allAmount.SUB809(nodeAssignmentData.CHECKNODELATESTAMOUNT653(address(msg.sender))); uint256 getAmount = amount.MUL451(supermanContract.BALANCEOF780(address(msg.sender))).DIV932(1500); return getAmount; } modifier ONLYOWNER374(){ //inject NONSTANDARD NAMING require(mappingContract.CHECKOWNERS909(msg.sender) == true); _; } } interface IERC20 { function TOTALSUPPLY171() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF780(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE615(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER685(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE777(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM303(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER309(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL404(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract SuperMan is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; IBMapping mappingContract; //1111 uint256 private _totalSupply = 1500; string public name = "NestNode"; string public symbol = "NN"; uint8 public decimals = 0; constructor (address map) public { _balances[msg.sender] = _totalSupply; mappingContract = IBMapping(map); } function CHANGEMAPPING301(address map) public ONLYOWNER374{ //inject NONSTANDARD NAMING mappingContract = IBMapping(map); } function TOTALSUPPLY171() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF780(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE615(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER685(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER545(msg.sender, to, value); return true; } function APPROVE777(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = value; emit APPROVAL404(msg.sender, spender, value); return true; } function TRANSFERFROM303(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[from][msg.sender] = _allowed[from][msg.sender].SUB809(value); _TRANSFER545(from, to, value); emit APPROVAL404(from, msg.sender, _allowed[from][msg.sender]); return true; } function INCREASEALLOWANCE778(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD302(addedValue); emit APPROVAL404(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function DECREASEALLOWANCE839(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB809(subtractedValue); emit APPROVAL404(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _TRANSFER545(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); NEST_NodeAssignment nodeAssignment = NEST_NodeAssignment(address(mappingContract.CHECKADDRESS222("nodeAssignment"))); nodeAssignment.NODECOUNT170(from, to); _balances[from] = _balances[from].SUB809(value); _balances[to] = _balances[to].ADD302(value); emit TRANSFER309(from, to, value); } modifier ONLYOWNER374(){ //inject NONSTANDARD NAMING require(mappingContract.CHECKOWNERS909(msg.sender) == true); _; } } library SafeMath { int256 constant private int256_min212 = -2**255; //inject NONSTANDARD NAMING function MUL451(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function MUL451(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == int256_min212)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } function DIV932(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function DIV932(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == int256_min212)); // This is the only case of overflow int256 c = a / b; return c; } function SUB809(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function SUB809(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } function ADD302(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function ADD302(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function MOD929(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } contract IBMapping { function CHECKADDRESS222(string memory name) public view returns (address contractAddress); //inject NONSTANDARD NAMING function CHECKOWNERS909(address man) public view returns (bool); //inject NONSTANDARD NAMING } contract IBNEST { function TOTALSUPPLY171() public view returns (uint supply); //inject NONSTANDARD NAMING function BALANCEOF780( address who ) public view returns (uint value); //inject NONSTANDARD NAMING function ALLOWANCE615( address owner, address spender ) public view returns (uint _allowance); //inject NONSTANDARD NAMING function TRANSFER685( address to, uint256 value) external; //inject NONSTANDARD NAMING function TRANSFERFROM303( address from, address to, uint value) public returns (bool ok); //inject NONSTANDARD NAMING function APPROVE777( address spender, uint value ) public returns (bool ok); //inject NONSTANDARD NAMING event TRANSFER309( address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL404( address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING function BALANCESSTART356() public view returns(uint256); //inject NONSTANDARD NAMING function BALANCESGETBOOL55(uint256 num) public view returns(bool); //inject NONSTANDARD NAMING function BALANCESGETNEXT455(uint256 num) public view returns(uint256); //inject NONSTANDARD NAMING function BALANCESGETVALUE432(uint256 num) public view returns(address, uint256); //inject NONSTANDARD NAMING }
inject NONSTANDARD NAMING
function APPROVE777(address spender, uint256 value) public returns (bool) {
898,785
./full_match/1/0x1d3Aa9DCC61e9DAC0111D3ADc85064F6dA28FDEa/sources/contracts/FlypToadz.sol
check sametoad ownership
function rescueToad(uint256 _id) public payable { require(sameToadz.ownerOf(_id) == msg.sender, "Not able to free flyptoad."); _safeMint(msg.sender, _id); totalSupply += 1; numAvailableTokens -= 1; }
4,888,219
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; interface IRadRouter is IERC721Receiver { /** * @dev Emitted when a retail revenue split is updated for asset ledger `ledger` */ event RetailRevenueSplitChange(address indexed ledger, address indexed stakeholder, uint256 share, uint256 totalStakeholders, uint256 totalSplit); /** * @dev Emitted when a resale revenue split is updated for asset ledger `ledger` */ event ResaleRevenueSplitChange(address indexed ledger, address indexed stakeholder, uint256 share, uint256 totalStakeholders, uint256 totalSplit); /** * @dev Emitted when the minimum price of asset `assetId` is updated */ event AssetMinPriceChange(address indexed ledger, uint256 indexed assetId, uint256 minPrice); /** * @dev Emitted when seller `seller` changes ownership for asset `assetId` in ledger `ledger` to or from this escrow. `escrowed` is true for deposits and false for withdrawals */ event SellerEscrowChange(address indexed ledger, uint256 indexed assetId, address indexed seller, bool escrowed); /** * @dev Emitted when buyer `buyer` deposits or withdraws ETH from this escrow for asset `assetId` in ledger `ledger`. `escrowed` is true for deposits and false for withdrawals */ event BuyerEscrowChange(address indexed ledger, uint256 indexed assetId, address indexed buyer, bool escrowed); /** * @dev Emitted when stakeholder `stakeholder` is paid out from a retail sale or resale */ event StakeholderPayout(address indexed ledger, uint256 indexed assetId, address indexed stakeholder, uint256 payout, uint256 share, bool retail); /** * @dev Emitted when buyer `buyer` deposits or withdraws ETH from this escrow for asset `assetId` in ledger `ledger`. `escrowed` is true for deposits and false for withdrawals */ event EscrowFulfill(address indexed ledger, uint256 indexed assetId, address seller, address buyer, uint256 value); /** * @dev Sets a stakeholder's revenue share for an asset ledger. If `retail` is true, sets retail revenue splits; otherwise sets resale revenue splits * * Requirements: * * - `_ledger` cannot be the zero address. * - `_stakeholder` cannot be the zero address. * - `_share` must be >= 0 and <= 100 * - Revenue cannot be split more than 5 ways * * Emits a {RetailRevenueSplitChange|ResaleRevenueSplitChange} event. */ function setRevenueSplit(address _ledger, address payable _stakeholder, uint256 _share, bool _retail) external returns (bool success); /** * @dev Returns the revenue share of `_stakeholder` for ledger `_ledger` * * See {setRevenueSplit} */ function getRevenueSplit(address _ledger, address payable _stakeholder, bool _retail) external view returns (uint256 share); /** * @dev Sets multiple stakeholders' revenue shares for an asset ledger. Overwrites any existing revenue share. If `retail` is true, sets retail revenue splits; otherwise sets resale revenue splits * See {setRevenueSplit} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_stakeholders` cannot contain zero addresses. * - `_shares` must be >= 0 and <= 100 * - Revenue cannot be split more than 5 ways * * Emits a {RetailRevenueSplitChange|ResaleRevenueSplitChange} event. */ function setRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail) external returns (bool success); /** * @dev For ledger `_ledger`, returns retail revenue stakeholders if `_retail` is true, otherwise returns resale revenue stakeholders. */ function getRevenueStakeholders(address _ledger, bool _retail) external view returns (address[] memory stakeholders); /** * @dev Sets the minimum price for asset `_assetId` * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * - `_minPrice` is in wei * * Emits a {AssetMinPriceChange} event. */ function setAssetMinPrice(address _ledger, uint256 _assetId, uint256 _minPrice) external returns (bool success); /** * @dev Sets a stakeholder's revenue share for an asset ledger. If `retail` is true, sets retail revenue splits; otherwise sets resale revenue splits. * Also sets the minimum price for asset `_assetId` * See {setAssetMinPrice | setRevenueSplits} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_stakeholder` cannot be the zero address. * - `_share` must be > 0 and <= 100 * - Revenue cannot be split more than 5 ways * - `_owner` must first approve this contract as an operator for ledger `_ledger` * - `_minPrice` is in wei * * Emits a {RetailRevenueSplitChange|ResaleRevenueSplitChange} event. */ function setAssetMinPriceAndRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail, uint256 _assetId, uint256 _minPrice) external returns (bool success); /** * @dev Returns the minium price of asset `_assetId` in ledger `_ledger` * * See {setAssetMinPrice} */ function getAssetMinPrice(address _ledger, uint256 _assetId) external view returns (uint256 minPrice); /** * @dev Transfers ownership of asset `_assetId` to this contract for escrow. * If buyer has already escrowed, triggers escrow fulfillment. * See {fulfill} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDeposit(address _ledger, uint256 _assetId) external returns (bool success); /** * @dev Transfers ownership of asset `_assetId` to this contract for escrow. * If buyer has already escrowed, triggers escrow fulfillment. * See {fulfill} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDepositWithCreatorShare(address _ledger, uint256 _assetId, uint256 _creatorResaleShare) external returns (bool success); function sellerEscrowDepositWithCreatorShareBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare) external returns (bool success); /** * @dev Transfers ownership of asset `_assetId` to this contract for escrow. * If buyer has already escrowed, triggers escrow fulfillment. * See {fulfill} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDepositWithCreatorShareWithMinPrice(address _ledger, uint256 _assetId, uint256 _creatorResaleShare, uint256 _minPrice) external returns (bool success); function sellerEscrowDepositWithCreatorShareWithMinPriceBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare, uint256 _minPrice) external returns (bool success); /** * @dev Transfers ownership of asset `_assetId` to this contract for escrow. * Sets asset min price to `_minPrice` if `_setMinPrice` is true. Reverts if `_setMinPrice` is true and buyer has already escrowed. Otherwise, if buyer has already escrowed, triggers escrow fulfillment. * See {fulfill | setAssetMinPrice} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * - `_minPrice` is in wei * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDeposit(address _ledger, uint256 _assetId, bool _setMinPrice, uint256 _minPrice) external returns (bool success); /** * @dev Transfers ownership of all assets `_assetIds` to this contract for escrow. * If any buyers have already escrowed, triggers escrow fulfillment for the respective asset. * See {fulfill} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds) external returns (bool success); /** * @dev Transfers ownership of all assets `_assetIds` to this contract for escrow. * Sets each asset min price to `_minPrice` if `_setMinPrice` is true. Reverts if `_setMinPrice` is true and buyer has already escrowed. Otherwise, if any buyers have already escrowed, triggers escrow fulfillment for the respective asset. * See {fulfill | setAssetMinPrice} * * Requirements: * * - `_ledger` cannot be the zero address. * - `_owner` must first approve this contract as an operator for ledger `_ledger` * - `_minPrice` is in wei * * Emits a {SellerEscrowChange} event. */ function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds, bool _setMinPrice, uint256 _minPrice) external returns (bool success); /** * @dev Transfers ownership of asset `_assetId` from this contract for escrow back to seller. * * Requirements: * * - `_ledger` cannot be the zero address. * * Emits a {SellerEscrowChange} event. */ function sellerEscrowWithdraw(address _ledger, uint256 _assetId) external returns (bool success); /** * @dev Accepts buyer's `msg.sender` funds into escrow for asset `_assetId` in ledger `_ledger`. * If seller has already escrowed, triggers escrow fulfillment. * See {fulfill} * * Requirements: * * - `_ledger` cannot be the zero address. * - `msg.value` must be at least the seller's listed price * - `_assetId` in `ledger` cannot already have an escrowed buyer * * Emits a {BuyerEscrowChange} event. */ function buyerEscrowDeposit(address _ledger, uint256 _assetId) external payable returns (bool success); /** * @dev Returns buyer's `msg.sender` funds back from escrow for asset `_assetId` in ledger `_ledger`. * * Requirements: * * - `_ledger` cannot be the zero address. * - `msg.sender` must be the escrowed buyer for asset `_assetId` in ledger `_ledger`, asset owner, or Rad operator * * Emits a {BuyerEscrowChange} event. */ function buyerEscrowWithdraw(address _ledger, uint256 _assetId) external returns (bool success); /** * @dev Returns the wallet address of the seller of asset `_assetId` * * See {sellerEscrowDeposit} */ function getSellerWallet(address _ledger, uint256 _assetId) external view returns (address wallet); /** * @dev Returns the wallet address of the buyer of asset `_assetId` * * See {buyerEscrowDeposit} */ function getBuyerWallet(address _ledger, uint256 _assetId) external view returns (address wallet); /** * @dev Returns the escrowed `_assetId` by the seller of asset `_assetId` * * See {sellerEscrowDeposit} */ function getSellerDeposit(address _ledger, uint256 _assetId) external view returns (uint256 amount); /** * @dev Returns the escrowed amount by the buyer of asset `_assetId` * * See {buyerEscrowDeposit} */ function getBuyerDeposit(address _ledger, uint256 _assetId) external view returns (uint256 amount); /** * @dev Returns the wallet address of the creator of asset `_assetId` * * See {sellerEscrowDeposit} */ function getCreatorWallet(address _ledger, uint256 _assetId) external view returns (address wallet); /** * @dev Returns the amount of the creator's share of asset `_assetId` * * See {sellerEscrowDeposit} */ function getCreatorShare(address _ledger, uint256 _assetId) external view returns (uint256 amount); /** * @dev Returns true if an asset has been sold for retail and will be considered resale moving forward */ function getAssetIsResale(address _ledger, uint256 _assetId) external view returns (bool resale); /** * @dev Returns an array of all retailed asset IDs for ledger `_ledger` */ function getRetailedAssets(address _ledger) external view returns (uint256[] memory assets); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import './IRadRouter.sol'; import './RevenueSplitMapping.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol'; contract RadRouter is IRadRouter, ERC721Holder { using RevenueSplitMapping for RevMap; struct Ledger { RevMap RetailSplits; RevMap ResaleSplits; mapping (uint256 => Asset) Assets; uint256[] retailedAssets; } struct Asset { address owner; // does not change on escrow, only through sale uint256 minPrice; bool resale; Creator creator; Buyer buyer; } struct Creator { address wallet; uint256 share; } struct Buyer { address wallet; uint256 amountEscrowed; } modifier onlyBy(address _account) { require( msg.sender == _account, 'Sender not authorized' ); _; } address public administrator_; // Rad administrator account mapping(address => Ledger) private Ledgers; /** * @dev Initializes the contract and sets the router administrator `administrator_` */ constructor() { administrator_ = msg.sender; } /** * @dev See {IRadRouter-setRevenueSplit}. */ function setRevenueSplit(address _ledger, address payable _stakeholder, uint256 _share, bool _retail) public onlyBy(administrator_) virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); require(_stakeholder != address(0), 'Stakeholder cannot be the zero address'); require(_share >= 0 && _share <= 100, 'Stakeholder share must be at least 0% and at most 100%'); uint256 total; if (_retail) { if (_share == 0) { Ledgers[_ledger].RetailSplits.remove(_stakeholder); emit RetailRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].RetailSplits.size(), Ledgers[_ledger].RetailSplits.total); return true; } if (Ledgers[_ledger].RetailSplits.contains(_stakeholder)) { require(Ledgers[_ledger].RetailSplits.size() <= 5, 'Cannot split revenue more than 5 ways.'); total = Ledgers[_ledger].RetailSplits.total - Ledgers[_ledger].RetailSplits.get(_stakeholder); } else { require(Ledgers[_ledger].RetailSplits.size() < 5, 'Cannot split revenue more than 5 ways.'); total = Ledgers[_ledger].RetailSplits.total; } } else { if (_share == 0) { Ledgers[_ledger].ResaleSplits.remove(_stakeholder); emit ResaleRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].ResaleSplits.size(), Ledgers[_ledger].ResaleSplits.total); return true; } if (Ledgers[_ledger].ResaleSplits.contains(_stakeholder)) { require(Ledgers[_ledger].ResaleSplits.size() <= 5, 'Cannot split revenue more than 5 ways.'); total = Ledgers[_ledger].ResaleSplits.total - Ledgers[_ledger].RetailSplits.get(_stakeholder); } else { require(Ledgers[_ledger].ResaleSplits.size() < 5, 'Cannot split revenue more than 5 ways.'); total = Ledgers[_ledger].ResaleSplits.total; } } require(_share + total <= 100, 'Total revenue split cannot exceed 100%'); if (_retail) { Ledgers[_ledger].RetailSplits.set(_stakeholder, _share); emit RetailRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].RetailSplits.size(), Ledgers[_ledger].RetailSplits.total); } else { Ledgers[_ledger].ResaleSplits.set(_stakeholder, _share); emit ResaleRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].ResaleSplits.size(), Ledgers[_ledger].ResaleSplits.total); } success = true; } /** * @dev See {IRadRouter-getRevenueSplit}. */ function getRevenueSplit(address _ledger, address payable _stakeholder, bool _retail) external view virtual override returns (uint256 share) { if (_retail) { share = Ledgers[_ledger].RetailSplits.get(_stakeholder); } else { share = Ledgers[_ledger].ResaleSplits.get(_stakeholder); } } /** * @dev See {IRadRouter-setRevenueSplits}. */ function setRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail) public virtual override returns (bool success) { require(_stakeholders.length == _shares.length, 'Stakeholders and shares must have equal length'); require(_stakeholders.length <= 5, 'Cannot split revenue more than 5 ways.'); if (_retail) { Ledgers[_ledger].RetailSplits.clear(); } else { Ledgers[_ledger].ResaleSplits.clear(); } for (uint256 i = 0; i < _stakeholders.length; i++) { setRevenueSplit(_ledger, _stakeholders[i], _shares[i], _retail); } success = true; } function getRevenueStakeholders(address _ledger, bool _retail) external view virtual override returns (address[] memory stakeholders) { if (_retail) { stakeholders = Ledgers[_ledger].RetailSplits.keys; } else { stakeholders = Ledgers[_ledger].ResaleSplits.keys; } } /** * @dev See {IRadRouter-setAssetMinPrice}. */ function setAssetMinPrice(address _ledger, uint256 _assetId, uint256 _minPrice) public virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); IERC721 ledger = IERC721(_ledger); address owner = ledger.ownerOf(_assetId); require(msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can set the asset minimum price'); require(owner == address(this) || ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must approve Rad Router as an operator before setting minimum price.'); Ledgers[_ledger].Assets[_assetId].owner = owner; Ledgers[_ledger].Assets[_assetId].minPrice = _minPrice; emit AssetMinPriceChange(_ledger, _assetId, _minPrice); success = true; } /** * @dev See {IRadRouter-getAssetMinPrice}. */ function getAssetMinPrice(address _ledger, uint256 _assetId) external view virtual override returns (uint256 minPrice) { minPrice = Ledgers[_ledger].Assets[_assetId].minPrice; } /** * @dev See {IRadRouter-setAssetMinPriceAndRevenueSplits}. */ function setAssetMinPriceAndRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail, uint256 _assetId, uint256 _minPrice) public virtual override returns (bool success) { success = setRevenueSplits(_ledger, _stakeholders, _shares, _retail) && setAssetMinPrice(_ledger, _assetId, _minPrice); } /** * @dev See {IRadRouter-sellerEscrowDeposit}. */ function sellerEscrowDeposit(address _ledger, uint256 _assetId) public virtual override returns (bool success) { success = sellerEscrowDeposit(_ledger, _assetId, false, 0); } /** * @dev See {IRadRouter-sellerEscrowDepositWithCreatorShare}. */ function sellerEscrowDepositWithCreatorShare(address _ledger, uint256 _assetId, uint256 _creatorResaleShare) public virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); require(_creatorResaleShare >= 0 && _creatorResaleShare <= 100, 'Creator share must be at least 0% and at most 100%'); IERC721 ledger = IERC721(_ledger); address owner = ledger.ownerOf(_assetId); require( msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership' ); require( ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must set Rad Router as an operator for all assets before depositing to escrow.' ); if ( Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0) || Ledgers[_ledger].Assets[_assetId].creator.wallet == owner || Ledgers[_ledger].Assets[_assetId].owner == owner ) { if (Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0)) { Ledgers[_ledger].Assets[_assetId].creator.wallet = owner; } require( Ledgers[_ledger].Assets[_assetId].creator.wallet == owner || Ledgers[_ledger].Assets[_assetId].creator.share == 0 || Ledgers[_ledger].Assets[_assetId].owner == owner, 'Cannot set creator share.' ); uint256 total = Ledgers[_ledger].Assets[_assetId].creator.share; address[] storage stakeholders = Ledgers[_ledger].ResaleSplits.keys; for (uint256 i = 0; i < stakeholders.length; i++) { total += Ledgers[_ledger].ResaleSplits.get(stakeholders[i]); } require(total <= 100, 'Creator share cannot exceed total ledger stakeholder when it is 100.'); Ledgers[_ledger].Assets[_assetId].creator.share = _creatorResaleShare; } success = sellerEscrowDeposit(_ledger, _assetId, false, 0); } /** * @dev See {IRadRouter-sellerEscrowDepositWithCreatorShareBatch}. */ function sellerEscrowDepositWithCreatorShareBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare) public virtual override returns (bool success) { success = false; for (uint256 i = 0; i < _assetIds.length; i++) { if (!sellerEscrowDepositWithCreatorShare(_ledger, _assetIds[i], _creatorResaleShare)) { success = false; break; } else { success = true; } } } /** * @dev See {IRadRouter-sellerEscrowDepositWithCreatorShareWithMinPrice}. */ function sellerEscrowDepositWithCreatorShareWithMinPrice(address _ledger, uint256 _assetId, uint256 _creatorResaleShare, uint256 _minPrice) public virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); require(_creatorResaleShare >= 0 && _creatorResaleShare <= 100, 'Creator share must be at least 0% and at most 100%'); IERC721 ledger = IERC721(_ledger); address owner = ledger.ownerOf(_assetId); require( msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership' ); require( ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must set Rad Router as an operator for all assets before depositing to escrow.' ); if ( Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0) || Ledgers[_ledger].Assets[_assetId].creator.wallet == owner || Ledgers[_ledger].Assets[_assetId].owner == owner ) { if (Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0)) { Ledgers[_ledger].Assets[_assetId].creator.wallet = owner; } require( Ledgers[_ledger].Assets[_assetId].creator.wallet == owner || Ledgers[_ledger].Assets[_assetId].creator.share == 0 || Ledgers[_ledger].Assets[_assetId].owner == owner, 'Cannot set creator share.' ); uint256 total = Ledgers[_ledger].Assets[_assetId].creator.share; address[] storage stakeholders = Ledgers[_ledger].ResaleSplits.keys; for (uint256 i = 0; i < stakeholders.length; i++) { total += Ledgers[_ledger].ResaleSplits.get(stakeholders[i]); } require(total <= 100, 'Creator share cannot exceed total ledger stakeholder when it is 100.'); Ledgers[_ledger].Assets[_assetId].creator.share = _creatorResaleShare; } success = sellerEscrowDeposit(_ledger, _assetId, true, _minPrice); } /** * @dev See {IRadRouter-sellerEscrowDepositWithCreatorShareWithMinPriceBatch}. */ function sellerEscrowDepositWithCreatorShareWithMinPriceBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare, uint256 _minPrice) public virtual override returns (bool success) { success = false; for (uint256 i = 0; i < _assetIds.length; i++) { if (!sellerEscrowDepositWithCreatorShareWithMinPrice(_ledger, _assetIds[i], _creatorResaleShare, _minPrice)) { success = false; break; } else { success = true; } } } /** * @dev See {IRadRouter-sellerEscrowDeposit}. */ function sellerEscrowDeposit(address _ledger, uint256 _assetId, bool _setMinPrice, uint256 _minPrice) public virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); IERC721 ledger = IERC721(_ledger); address owner = ledger.ownerOf(_assetId); require(msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership'); require(ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must set Rad Router as an operator for all assets before depositing to escrow'); if (_setMinPrice) { setAssetMinPrice(_ledger, _assetId, _minPrice); } Ledgers[_ledger].Assets[_assetId].owner = owner; ledger.safeTransferFrom(owner, address(this), _assetId); if (Ledgers[_ledger].Assets[_assetId].buyer.wallet != address(0)) { _fulfill(_ledger, _assetId); } emit SellerEscrowChange(_ledger, _assetId, owner, true); success = true; } /** * @dev See {IRadRouter-sellerEscrowDepositBatch}. */ function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds) external virtual override returns (bool success) { success = sellerEscrowDepositBatch(_ledger, _assetIds, false, 0); } /** * @dev See {IRadRouter-sellerEscrowDepositBatch}. */ function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds, bool _setMinPrice, uint256 _minPrice) public virtual override returns (bool success) { for (uint256 i = 0; i < _assetIds.length; i++) { sellerEscrowDeposit(_ledger, _assetIds[i], _setMinPrice, _minPrice); } success = true; } /** * @dev See {IRadRouter-sellerEscrowWithdraw}. */ function sellerEscrowWithdraw(address _ledger, uint256 _assetId) external virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); IERC721 ledger = IERC721(_ledger); address owner = Ledgers[_ledger].Assets[_assetId].owner; require(msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership'); require(ledger.isApprovedForAll(owner, address(this)), 'Must set Rad Router as an operator for all assets before depositing to escrow'); Ledgers[_ledger].Assets[_assetId].creator.wallet = address(0); Ledgers[_ledger].Assets[_assetId].creator.share = 0; ledger.safeTransferFrom(address(this), owner, _assetId); emit SellerEscrowChange(_ledger, _assetId, owner, false); success = true; } /** * @dev See {IRadRouter-buyerEscrowDeposit}. */ function buyerEscrowDeposit(address _ledger, uint256 _assetId) external payable virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); require( Ledgers[_ledger].Assets[_assetId].buyer.wallet == address(0) || Ledgers[_ledger].Assets[_assetId].buyer.wallet == msg.sender, 'Another buyer has already escrowed' ); require( Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed + msg.value >= Ledgers[_ledger].Assets[_assetId].minPrice, 'Buyer did not send enough ETH' ); Ledgers[_ledger].Assets[_assetId].buyer.wallet = msg.sender; Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed += msg.value; IERC721 ledger = IERC721(_ledger); if (ledger.ownerOf(_assetId) == address(this)) { _fulfill(_ledger, _assetId); } emit BuyerEscrowChange(_ledger, _assetId, msg.sender, true); success = true; } /** * @dev See {IRadRouter-buyerEscrowWithdraw}. */ function buyerEscrowWithdraw(address _ledger, uint256 _assetId) external virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); require( msg.sender == Ledgers[_ledger].Assets[_assetId].buyer.wallet || msg.sender == Ledgers[_ledger].Assets[_assetId].owner || msg.sender == administrator_, 'msg.sender must be the buyer, seller, or Rad operator' ); payable(Ledgers[_ledger].Assets[_assetId].buyer.wallet).transfer(Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed); Ledgers[_ledger].Assets[_assetId].buyer.wallet = address(0); Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed = 0; emit BuyerEscrowChange(_ledger, _assetId, msg.sender, false); success = true; } /** * @dev See {IRadRouter-getSellerWallet}. */ function getSellerWallet(address _ledger, uint256 _assetId) public view override returns (address wallet) { if (Ledgers[_ledger].Assets[_assetId].owner == address(0)) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); IERC721 ledger = IERC721(_ledger); wallet = ledger.ownerOf(_assetId); } else { wallet = Ledgers[_ledger].Assets[_assetId].owner; } } /** * @dev See {IRadRouter-getSellerWallet}. */ function getSellerDeposit(address _ledger, uint256 _assetId) public view override returns (uint256 amount) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); IERC721 ledger = IERC721(_ledger); address owner = ledger.ownerOf(_assetId); if (owner == address(this)) { return _assetId; } return 0; } /** * @dev See {IRadRouter-getBuyerWallet}. */ function getBuyerWallet(address _ledger, uint256 _assetId) public view override returns (address wallet) { wallet = Ledgers[_ledger].Assets[_assetId].buyer.wallet; } /** * @dev See {IRadRouter-getBuyerDeposit}. */ function getBuyerDeposit(address _ledger, uint256 _assetId) public view override returns (uint256 amount) { amount = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed; } /** * @dev See {IRadRouter-getAssetIsResale}. */ function getAssetIsResale(address _ledger, uint256 _assetId) public view override returns (bool resale) { resale = Ledgers[_ledger].Assets[_assetId].resale; } /** * @dev See {IRadRouter-getRetailedAssets}. */ function getRetailedAssets(address _ledger) public view override returns (uint256[] memory assets) { assets = Ledgers[_ledger].retailedAssets; } /** * @dev See {IRadRouter-getCreatorWallet}. */ function getCreatorWallet(address _ledger, uint256 _assetId) public view override returns (address wallet) { wallet = Ledgers[_ledger].Assets[_assetId].creator.wallet; } /** * @dev See {IRadRouter-getCreatorShare}. */ function getCreatorShare(address _ledger, uint256 _assetId) public view override returns (uint256 amount) { amount = Ledgers[_ledger].Assets[_assetId].creator.share; } /** * @dev Fulfills asset sale transaction and pays out all revenue split stakeholders * * Requirements: * * - `_ledger` cannot be the zero address. * - `_assetId` owner must be this contract * - `_assetId` buyer must not be the zero address * * Emits a {EscrowFulfill} event. */ function _fulfill(address _ledger, uint256 _assetId) internal virtual returns (bool success) { IERC721 ledger = IERC721(_ledger); require( ledger.ownerOf(_assetId) == address(this), 'Seller has not escrowed' ); require( Ledgers[_ledger].Assets[_assetId].buyer.wallet != address(0), 'Buyer has not escrowed' ); require( Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed >= Ledgers[_ledger].Assets[_assetId].minPrice, 'Buyer escrow amount is less than asset min price' ); ledger.safeTransferFrom( address(this), Ledgers[_ledger].Assets[_assetId].buyer.wallet, _assetId ); if (!Ledgers[_ledger].Assets[_assetId].resale) { if (Ledgers[_ledger].RetailSplits.size() > 0) { uint256 totalShareSplit = 0; for (uint256 i = 0; i < Ledgers[_ledger].RetailSplits.size(); i++) { address stakeholder = Ledgers[_ledger].RetailSplits.getKeyAtIndex(i); uint256 share = Ledgers[_ledger].RetailSplits.get(stakeholder); if (totalShareSplit + share > 100) { share = totalShareSplit + share - 100; } uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * share / 100; payable(stakeholder).transfer(payout); emit StakeholderPayout(_ledger, _assetId, stakeholder, payout, share, true); totalShareSplit += share; // ignore other share stake holders if total max split has been reached if (totalShareSplit >= 100) { break; } } if (totalShareSplit < 100) { uint256 remainingShare = 100 - totalShareSplit; uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * remainingShare / 100; payable(Ledgers[_ledger].Assets[_assetId].owner).transfer(payout); emit StakeholderPayout(_ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, payout, remainingShare, true); } } else { // if no revenue split is defined, send all to asset owner uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed; payable(Ledgers[_ledger].Assets[_assetId].owner).transfer(payout); emit StakeholderPayout(_ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, payout, 100, true); } Ledgers[_ledger].Assets[_assetId].resale = true; Ledgers[_ledger].retailedAssets.push(_assetId); } else { uint256 totalShareSplit = 0; if ( Ledgers[_ledger].Assets[_assetId].creator.share > 0 && Ledgers[_ledger].Assets[_assetId].creator.wallet != address(0) ) { uint256 creatorPayout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * Ledgers[_ledger].Assets[_assetId].creator.share / 100; if (creatorPayout > 0) { totalShareSplit = Ledgers[_ledger].Assets[_assetId].creator.share; payable(Ledgers[_ledger].Assets[_assetId].creator.wallet).transfer(creatorPayout); } emit StakeholderPayout( _ledger, _assetId, Ledgers[_ledger].Assets[_assetId].creator.wallet, creatorPayout, Ledgers[_ledger].Assets[_assetId].creator.share, false); } if (Ledgers[_ledger].ResaleSplits.size() > 0) { for (uint256 i = 0; i < Ledgers[_ledger].ResaleSplits.size(); i++) { address stakeholder = Ledgers[_ledger].ResaleSplits.getKeyAtIndex(i); uint256 share = Ledgers[_ledger].ResaleSplits.get(stakeholder) - (Ledgers[_ledger].Assets[_assetId].creator.share / 100); if (totalShareSplit + share > 100) { share = totalShareSplit + share - 100; } uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * share / 100; payable(stakeholder).transfer(payout); emit StakeholderPayout(_ledger, _assetId, stakeholder, payout, share, false); totalShareSplit += share; // ignore other share stake holders if total max split has been reached if (totalShareSplit >= 100) { break; } } if (totalShareSplit < 100) { uint256 remainingShare = 100 - totalShareSplit; uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * remainingShare / 100; payable(Ledgers[_ledger].Assets[_assetId].owner).transfer(payout); emit StakeholderPayout(_ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, payout, remainingShare, false); } } else { // if no revenue split is defined, send all to asset owner uint256 remainingShare = 100 - totalShareSplit; uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * remainingShare / 100; payable(Ledgers[_ledger].Assets[_assetId].owner).transfer(payout); emit StakeholderPayout(_ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, payout, remainingShare, false); } } emit EscrowFulfill( _ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, Ledgers[_ledger].Assets[_assetId].buyer.wallet, Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed ); Ledgers[_ledger].Assets[_assetId].owner = Ledgers[_ledger].Assets[_assetId].buyer.wallet; Ledgers[_ledger].Assets[_assetId].minPrice = 0; Ledgers[_ledger].Assets[_assetId].buyer.wallet = address(0); Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed = 0; success = true; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.8 <0.9.0; struct RevMap { address[] keys; uint256 total; mapping(address => IndexValue) values; } struct IndexValue { uint256 value; uint256 indexOf; bool inserted; } // https://solidity-by-example.org/app/iterable-mapping/ library RevenueSplitMapping { function get(RevMap storage map, address key) external view returns (uint256) { return map.values[key].value; } function getKeyAtIndex(RevMap storage map, uint256 index) external view returns (address) { return map.keys[index]; } function size(RevMap storage map) external view returns (uint256) { return map.keys.length; } function set(RevMap storage map, address key, uint256 val) external { if (map.values[key].inserted) { map.total-=map.values[key].value; map.values[key].value = val; map.total+=val; } else { map.values[key].inserted = true; map.values[key].value = val; map.total+=val; map.values[key].indexOf = map.keys.length; map.keys.push(key); } } function remove(RevMap storage map, address key) external { if (!map.values[key].inserted) { return; } map.total-=map.values[key].value; uint256 index = map.values[key].indexOf; uint256 lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.values[lastKey].indexOf = index; delete map.values[key]; map.keys[index] = lastKey; map.keys.pop(); } function contains(RevMap storage map, address key) external view returns(bool) { return map.values[key].inserted; } function clear(RevMap storage map) external { for (uint256 i = 0; i < map.keys.length; i++) { delete map.values[map.keys[i]]; } delete map.keys; map.total = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // 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); }
See {IRadRouter-sellerEscrowDepositWithCreatorShare}./
function sellerEscrowDepositWithCreatorShare(address _ledger, uint256 _assetId, uint256 _creatorResaleShare) public virtual override returns (bool success) { require(_ledger != address(0), 'Asset ledger cannot be the zero address'); require(_creatorResaleShare >= 0 && _creatorResaleShare <= 100, 'Creator share must be at least 0% and at most 100%'); IERC721 ledger = IERC721(_ledger); address owner = ledger.ownerOf(_assetId); require( msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership' ); require( ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must set Rad Router as an operator for all assets before depositing to escrow.' ); if ( Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0) || Ledgers[_ledger].Assets[_assetId].creator.wallet == owner || Ledgers[_ledger].Assets[_assetId].owner == owner ) { if (Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0)) { Ledgers[_ledger].Assets[_assetId].creator.wallet = owner; } require( Ledgers[_ledger].Assets[_assetId].creator.wallet == owner || Ledgers[_ledger].Assets[_assetId].creator.share == 0 || Ledgers[_ledger].Assets[_assetId].owner == owner, 'Cannot set creator share.' ); uint256 total = Ledgers[_ledger].Assets[_assetId].creator.share; address[] storage stakeholders = Ledgers[_ledger].ResaleSplits.keys; for (uint256 i = 0; i < stakeholders.length; i++) { total += Ledgers[_ledger].ResaleSplits.get(stakeholders[i]); } require(total <= 100, 'Creator share cannot exceed total ledger stakeholder when it is 100.'); Ledgers[_ledger].Assets[_assetId].creator.share = _creatorResaleShare; } success = sellerEscrowDeposit(_ledger, _assetId, false, 0); }
1,269,329
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; // Uncomment if needed. // import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "../libraries/UniswapOracle.sol"; import "../libraries/FixedPoints.sol"; import "../multicall.sol"; /// @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; } /// @title Simple math library for Max and Min. library Math { function max(int24 a, int24 b) internal pure returns (int24) { return a >= b ? a : b; } function min(int24 a, int24 b) internal pure returns (int24) { return a < b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function tickFloor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 c = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) { c = c - 1; } c = c * tickSpacing; return c; } function tickUpper(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 c = tick / tickSpacing; if (tick > 0 && tick % tickSpacing != 0) { c = c + 1; } c = c * tickSpacing; return c; } } /// @title Uniswap V3 Liquidity Mining Main Contract contract MiningOneSideBoost is Ownable, Multicall, ReentrancyGuard { // using Math for int24; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.UintSet; using UniswapOracle for address; int24 internal constant TICK_MAX = 500000; int24 internal constant TICK_MIN = -500000; struct PoolInfo { address token0; address token1; uint24 fee; } bool uniIsETH; address uniToken; address lockToken; /// @dev Contract of the uniV3 Nonfungible Position Manager. address uniV3NFTManager; address uniFactory; address swapPool; PoolInfo public rewardPool; /// @dev Last block number that the accRewardRerShare is touched. uint256 lastTouchBlock; /// @dev The block number when NFT mining rewards starts/ends. uint256 startBlock; uint256 endBlock; uint256 lockBoostMultiplier; struct RewardInfo { /// @dev Contract of the reward erc20 token. address rewardToken; /// @dev who provides reward address provider; /// @dev Accumulated Reward Tokens per share, times Q128. uint256 accRewardPerShare; /// @dev Reward amount for each block. uint256 rewardPerBlock; } mapping(uint256 => RewardInfo) public rewardInfos; uint256 public rewardInfosLen; /// @dev Store the owner of the NFT token mapping(uint256 => address) public owners; /// @dev The inverse mapping of owners. mapping(address => EnumerableSet.UintSet) private tokenIds; /// @dev Record the status for a certain token for the last touched time. struct TokenStatus { uint256 nftId; // bool isDepositWithNFT; uint128 uniLiquidity; uint256 lockAmount; uint256 vLiquidity; uint256 validVLiquidity; uint256 nIZI; uint256 lastTouchBlock; uint256[] lastTouchAccRewardPerShare; } mapping(uint256 => TokenStatus) public tokenStatus; receive() external payable {} /// @dev token to lock, 0 for not boost IERC20 public iziToken; /// @dev current total nIZI. uint256 public totalNIZI; /// @dev Current total virtual liquidity. uint256 public totalVLiquidity; /// @dev Current total lock token uint256 public totalLock; // Events event Deposit(address indexed user, uint256 tokenId, uint256 nIZI); event Withdraw(address indexed user, uint256 tokenId); event CollectReward(address indexed user, uint256 tokenId, address token, uint256 amount); event ModifyEndBlock(uint256 endBlock); event ModifyRewardPerBlock(address indexed rewardToken, uint256 rewardPerBlock); event ModifyProvider(address indexed rewardToken, address provider); function _setRewardPool( address _uniToken, address _lockToken, uint24 fee ) internal { address token0; address token1; if (_uniToken < _lockToken) { token0 = _uniToken; token1 = _lockToken; } else { token0 = _lockToken; token1 = _uniToken; } rewardPool.token0 = token0; rewardPool.token1 = token1; rewardPool.fee = fee; } struct PoolParams { address uniV3NFTManager; address uniTokenAddr; address lockTokenAddr; uint24 fee; } constructor( PoolParams memory poolParams, RewardInfo[] memory _rewardInfos, uint256 _lockBoostMultiplier, address iziTokenAddr, uint256 _startBlock, uint256 _endBlock ) { uniV3NFTManager = poolParams.uniV3NFTManager; _setRewardPool( poolParams.uniTokenAddr, poolParams.lockTokenAddr, poolParams.fee ); address weth = INonfungiblePositionManager(uniV3NFTManager).WETH9(); require(weth != poolParams.lockTokenAddr, "WETH NOT SUPPORT"); uniFactory = INonfungiblePositionManager(uniV3NFTManager).factory(); uniToken = poolParams.uniTokenAddr; uniIsETH = (uniToken == weth); lockToken = poolParams.lockTokenAddr; IERC20(uniToken).safeApprove(uniV3NFTManager, type(uint256).max); swapPool = IUniswapV3Factory(uniFactory).getPool( lockToken, uniToken, poolParams.fee ); require(swapPool != address(0), "NO UNI POOL"); rewardInfosLen = _rewardInfos.length; require(rewardInfosLen > 0, "NO REWARD"); require(rewardInfosLen < 3, "AT MOST 2 REWARDS"); for (uint256 i = 0; i < rewardInfosLen; i++) { rewardInfos[i] = _rewardInfos[i]; rewardInfos[i].accRewardPerShare = 0; } require(_lockBoostMultiplier > 0, "M>0"); require(_lockBoostMultiplier < 4, "M<4"); lockBoostMultiplier = _lockBoostMultiplier; // iziTokenAddr == 0 means not boost iziToken = IERC20(iziTokenAddr); startBlock = _startBlock; endBlock = _endBlock; lastTouchBlock = startBlock; totalVLiquidity = 0; totalNIZI = 0; } /// @notice Get the overall info for the mining contract. function getMiningContractInfo() external view returns ( address uniToken_, address lockToken_, uint24 fee_, uint256 lockBoostMultiplier_, address iziTokenAddr_, uint256 lastTouchBlock_, uint256 totalVLiquidity_, uint256 totalLock_, uint256 totalNIZI_, uint256 startBlock_, uint256 endBlock_ ) { return ( uniToken, lockToken, rewardPool.fee, lockBoostMultiplier, address(iziToken), lastTouchBlock, totalVLiquidity, totalLock, totalNIZI, startBlock, endBlock ); } /// @dev compute amount of lockToken /// @param sqrtPriceX96 sqrtprice value viewed from uniswap pool /// @param uniAmount amount of uniToken user deposits /// or amount computed corresponding to deposited uniswap NFT /// @return lockAmount amount of lockToken function _getLockAmount(uint160 sqrtPriceX96, uint256 uniAmount) private view returns (uint256 lockAmount) { // uniAmount is less than Q96, checked before uint256 precision = FixedPoints.Q96; uint256 sqrtPriceXP = sqrtPriceX96; // if price > 1, we discard the useless precision if (sqrtPriceX96 > FixedPoints.Q96) { precision = FixedPoints.Q32; // sqrtPriceXP <= Q96 after >> operation sqrtPriceXP = (sqrtPriceXP >> 64); } // priceXP <= Q160 if price >= 1 // priceXP <= Q96 if price < 1 uint256 priceXP = (sqrtPriceXP * sqrtPriceXP) / precision; if (priceXP > 0) { if (uniToken < lockToken) { // price is lockToken / uniToken lockAmount = (uniAmount * priceXP) / precision; } else { lockAmount = (uniAmount * precision) / priceXP; } } else { // in this case sqrtPriceXP <= Q48, precision = Q96 if (uniToken < lockToken) { // price is lockToken / uniToken // lockAmount = uniAmount * sqrtPriceXP * sqrtPriceXP / precision / precision; // the above expression will always get 0 lockAmount = 0; } else { lockAmount = uniAmount * precision / sqrtPriceXP / sqrtPriceXP; // lockAmount is always < Q128, since sqrtPriceXP > Q32 // we still add the require statement to double check require(lockAmount < FixedPoints.Q160, "TOO MUCH LOCK"); lockAmount *= precision; } } require(lockAmount > 0, "LOCK 0"); } /// @notice new a token status when touched. function _newTokenStatus(TokenStatus memory newTokenStatus) internal { tokenStatus[newTokenStatus.nftId] = newTokenStatus; TokenStatus storage t = tokenStatus[newTokenStatus.nftId]; t.lastTouchBlock = lastTouchBlock; t.lastTouchAccRewardPerShare = new uint256[](rewardInfosLen); for (uint256 i = 0; i < rewardInfosLen; i++) { t.lastTouchAccRewardPerShare[i] = rewardInfos[i].accRewardPerShare; } } /// @notice update a token status when touched function _updateTokenStatus( uint256 tokenId, uint256 validVLiquidity, uint256 nIZI ) internal { TokenStatus storage t = tokenStatus[tokenId]; // when not boost, validVL == vL t.validVLiquidity = validVLiquidity; t.nIZI = nIZI; t.lastTouchBlock = lastTouchBlock; for (uint256 i = 0; i < rewardInfosLen; i++) { t.lastTouchAccRewardPerShare[i] = rewardInfos[i].accRewardPerShare; } } /// @notice Update reward variables to be up-to-date. function _updateVLiquidity(uint256 vLiquidity, bool isAdd) internal { if (isAdd) { totalVLiquidity = totalVLiquidity + vLiquidity; } else { totalVLiquidity = totalVLiquidity - vLiquidity; } // max lockBoostMultiplier is 3 require(totalVLiquidity <= FixedPoints.Q128 * 3, "TOO MUCH LIQUIDITY STAKED"); } function _updateNIZI(uint256 nIZI, bool isAdd) internal { if (isAdd) { totalNIZI = totalNIZI + nIZI; } else { totalNIZI = totalNIZI - nIZI; } } /// @notice Update the global status. function _updateGlobalStatus() internal { if (block.number <= lastTouchBlock) { return; } if (lastTouchBlock >= endBlock) { return; } uint256 currBlockNumber = Math.min(block.number, endBlock); if (totalVLiquidity == 0) { lastTouchBlock = currBlockNumber; return; } for (uint256 i = 0; i < rewardInfosLen; i++) { // tokenReward < 2^25 * 2^64 * 2*10, 15 years, 1000 r/block uint256 tokenReward = (currBlockNumber - lastTouchBlock) * rewardInfos[i].rewardPerBlock; // tokenReward * Q128 < 2^(25 + 64 + 10 + 128) rewardInfos[i].accRewardPerShare = rewardInfos[i].accRewardPerShare + ((tokenReward * FixedPoints.Q128) / totalVLiquidity); } lastTouchBlock = currBlockNumber; } function _computeValidVLiquidity(uint256 vLiquidity, uint256 nIZI) internal view returns (uint256) { if (totalNIZI == 0) { return vLiquidity; } uint256 iziVLiquidity = (vLiquidity * 4 + (totalVLiquidity * nIZI * 6) / totalNIZI) / 10; return Math.min(iziVLiquidity, vLiquidity); } /// @dev get sqrtPrice of pool(uniToken/tokenSwap/fee) /// and compute tick range converted from [TICK_MIN, PriceUni] or [PriceUni, TICK_MAX] /// @return sqrtPriceX96 current sqrtprice value viewed from uniswap pool, is a 96-bit fixed point number /// note this value might mean price of lockToken/uniToken (if uniToken < lockToken) /// or price of uniToken / lockToken (if uniToken > lockToken) /// @return tickLeft /// @return tickRight function _getPriceAndTickRange() private view returns ( uint160 sqrtPriceX96, int24 tickLeft, int24 tickRight ) { (int24 avgTick, uint160 avgSqrtPriceX96, int24 currTick, ) = swapPool .getAvgTickPriceWithin2Hour(); int24 tickSpacing = IUniswapV3Factory(uniFactory).feeAmountTickSpacing( rewardPool.fee ); if (uniToken < lockToken) { // price is lockToken / uniToken // uniToken is X tickLeft = Math.max(currTick + 1, avgTick); tickRight = TICK_MAX; tickLeft = Math.tickUpper(tickLeft, tickSpacing); tickRight = Math.tickUpper(tickRight, tickSpacing); } else { // price is uniToken / lockToken // uniToken is Y tickRight = Math.min(currTick, avgTick); tickLeft = TICK_MIN; tickLeft = Math.tickFloor(tickLeft, tickSpacing); tickRight = Math.tickFloor(tickRight, tickSpacing); } require(tickLeft < tickRight, "L<R"); sqrtPriceX96 = avgSqrtPriceX96; } function getOraclePrice() external view returns ( int24 avgTick, uint160 avgSqrtPriceX96 ) { (avgTick, avgSqrtPriceX96, , ) = swapPool.getAvgTickPriceWithin2Hour(); } // fill INonfungiblePositionManager.MintParams struct to call INonfungiblePositionManager.mint(...) function _mintUniswapParam( uint256 uniAmount, int24 tickLeft, int24 tickRight, uint256 deadline ) private view returns (INonfungiblePositionManager.MintParams memory params) { params.fee = rewardPool.fee; params.tickLower = tickLeft; params.tickUpper = tickRight; params.deadline = deadline; params.recipient = address(this); if (uniToken < lockToken) { params.token0 = uniToken; params.token1 = lockToken; params.amount0Desired = uniAmount; params.amount1Desired = 0; params.amount0Min = 1; params.amount1Min = 0; } else { params.token0 = lockToken; params.token1 = uniToken; params.amount0Desired = 0; params.amount1Desired = uniAmount; params.amount0Min = 0; params.amount1Min = 1; } } /// @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"); } function depositWithuniToken( uint256 uniAmount, uint256 numIZI, uint256 deadline ) external payable nonReentrant { require(uniAmount >= 1e7, "TOKENUNI AMOUNT TOO SMALL"); require(uniAmount < FixedPoints.Q96 / 3, "TOKENUNI AMOUNT TOO LARGE"); if (uniIsETH) { require(msg.value >= uniAmount, "ETHER INSUFFICIENT"); } else { IERC20(uniToken).safeTransferFrom( msg.sender, address(this), uniAmount ); } ( uint160 sqrtPriceX96, int24 tickLeft, int24 tickRight ) = _getPriceAndTickRange(); TokenStatus memory newTokenStatus; INonfungiblePositionManager.MintParams memory uniParams = _mintUniswapParam( uniAmount, tickLeft, tickRight, deadline ); uint256 actualAmountUni; if (uniToken < lockToken) { ( newTokenStatus.nftId, newTokenStatus.uniLiquidity, actualAmountUni, ) = INonfungiblePositionManager(uniV3NFTManager).mint{ value: msg.value }(uniParams); } else { ( newTokenStatus.nftId, newTokenStatus.uniLiquidity, , actualAmountUni ) = INonfungiblePositionManager(uniV3NFTManager).mint{ value: msg.value }(uniParams); } // mark owners and append to list owners[newTokenStatus.nftId] = msg.sender; bool res = tokenIds[msg.sender].add(newTokenStatus.nftId); require(res); if (actualAmountUni < uniAmount) { if (uniIsETH) { // refund uniToken // from uniswap to this INonfungiblePositionManager(uniV3NFTManager).refundETH(); // from this to msg.sender if (address(this).balance > 0) safeTransferETH(msg.sender, address(this).balance); } else { // refund uniToken IERC20(uniToken).safeTransfer( msg.sender, uniAmount - actualAmountUni ); } } _updateGlobalStatus(); newTokenStatus.vLiquidity = actualAmountUni * lockBoostMultiplier; newTokenStatus.lockAmount = _getLockAmount( sqrtPriceX96, newTokenStatus.vLiquidity ); // make vLiquidity lower newTokenStatus.vLiquidity = newTokenStatus.vLiquidity / 1e6; IERC20(lockToken).safeTransferFrom( msg.sender, address(this), newTokenStatus.lockAmount ); totalLock += newTokenStatus.lockAmount; _updateVLiquidity(newTokenStatus.vLiquidity, true); newTokenStatus.nIZI = numIZI; if (address(iziToken) == address(0)) { // boost is not enabled newTokenStatus.nIZI = 0; } _updateNIZI(newTokenStatus.nIZI, true); newTokenStatus.validVLiquidity = _computeValidVLiquidity( newTokenStatus.vLiquidity, newTokenStatus.nIZI ); require(newTokenStatus.nIZI < FixedPoints.Q128 / 6, "NIZI O"); _newTokenStatus(newTokenStatus); if (newTokenStatus.nIZI > 0) { // lock izi in this contract iziToken.safeTransferFrom( msg.sender, address(this), newTokenStatus.nIZI ); } emit Deposit(msg.sender, newTokenStatus.nftId, newTokenStatus.nIZI); } function _withdrawUniswapParam( uint256 uniPositionID, uint128 liquidity, uint256 deadline ) private pure returns ( INonfungiblePositionManager.DecreaseLiquidityParams memory params ) { params.tokenId = uniPositionID; params.liquidity = liquidity; params.amount0Min = 0; params.amount1Min = 0; params.deadline = deadline; } /// @notice deposit iZi to an nft token /// @param tokenId nft already deposited /// @param deltaNIZI amount of izi to deposit function depositIZI(uint256 tokenId, uint256 deltaNIZI) external nonReentrant { require(owners[tokenId] == msg.sender, "NOT OWNER or NOT EXIST"); require(address(iziToken) != address(0), "NOT BOOST"); require(deltaNIZI > 0, "DEPOSIT IZI MUST BE POSITIVE"); _collectReward(tokenId); TokenStatus memory t = tokenStatus[tokenId]; _updateNIZI(deltaNIZI, true); uint256 nIZI = t.nIZI + deltaNIZI; // update validVLiquidity uint256 validVLiquidity = _computeValidVLiquidity(t.vLiquidity, nIZI); _updateTokenStatus(tokenId, validVLiquidity, nIZI); // transfer iZi from user iziToken.safeTransferFrom(msg.sender, address(this), deltaNIZI); } // fill INonfungiblePositionManager.CollectParams struct to call INonfungiblePositionManager.collect(...) function _collectUniswapParam(uint256 uniPositionID, address recipient) private pure returns (INonfungiblePositionManager.CollectParams memory params) { params.tokenId = uniPositionID; params.recipient = recipient; params.amount0Max = 0xffffffffffffffffffffffffffffffff; params.amount1Max = 0xffffffffffffffffffffffffffffffff; } /// @notice Widthdraw a single position. /// @param tokenId The related position id. /// @param noReward true if use want to withdraw without reward function withdraw(uint256 tokenId, bool noReward) external nonReentrant { require(owners[tokenId] == msg.sender, "NOT OWNER OR NOT EXIST"); if (noReward) { _updateGlobalStatus(); } else { _collectReward(tokenId); } TokenStatus storage t = tokenStatus[tokenId]; _updateVLiquidity(t.vLiquidity, false); if (t.nIZI > 0) { _updateNIZI(t.nIZI, false); // refund iZi to user iziToken.safeTransfer(msg.sender, t.nIZI); } if (t.lockAmount > 0) { // refund lockToken to user IERC20(lockToken).safeTransfer(msg.sender, t.lockAmount); totalLock -= t.lockAmount; } INonfungiblePositionManager(uniV3NFTManager).decreaseLiquidity( _withdrawUniswapParam(tokenId, t.uniLiquidity, type(uint256).max) ); if (!uniIsETH) { INonfungiblePositionManager(uniV3NFTManager).collect( _collectUniswapParam(tokenId, msg.sender) ); } else { (uint256 amount0, uint256 amount1) = INonfungiblePositionManager( uniV3NFTManager ).collect( _collectUniswapParam( tokenId, address(this) ) ); (uint256 amountUni, uint256 amountLock) = (uniToken < lockToken)? (amount0, amount1) : (amount1, amount0); if (amountLock > 0) { IERC20(lockToken).safeTransfer(msg.sender, amountLock); } if (amountUni > 0) { IWETH9(uniToken).withdraw(amountUni); safeTransferETH(msg.sender, amountUni); } } owners[tokenId] = address(0); bool res = tokenIds[msg.sender].remove(tokenId); require(res); emit Withdraw(msg.sender, tokenId); } /// @notice Collect pending reward for a single position. /// @param tokenId The related position id. function _collectReward(uint256 tokenId) internal { TokenStatus memory t = tokenStatus[tokenId]; _updateGlobalStatus(); for (uint256 i = 0; i < rewardInfosLen; i++) { // multiplied by Q128 before uint256 _reward = (t.validVLiquidity * (rewardInfos[i].accRewardPerShare - t.lastTouchAccRewardPerShare[i])) / FixedPoints.Q128; if (_reward > 0) { IERC20(rewardInfos[i].rewardToken).safeTransferFrom( rewardInfos[i].provider, msg.sender, _reward ); } emit CollectReward( msg.sender, tokenId, rewardInfos[i].rewardToken, _reward ); } // update validVLiquidity uint256 validVLiquidity = _computeValidVLiquidity(t.vLiquidity, t.nIZI); _updateTokenStatus(tokenId, validVLiquidity, t.nIZI); } /// @notice Collect pending reward for a single position. /// @param tokenId The related position id. function collect(uint256 tokenId) external nonReentrant { require(owners[tokenId] == msg.sender, "NOT OWNER or NOT EXIST"); _collectReward(tokenId); INonfungiblePositionManager.CollectParams memory params = _collectUniswapParam(tokenId, msg.sender); // collect swap fee from uniswap INonfungiblePositionManager(uniV3NFTManager).collect(params); } /// @notice Collect all pending rewards. function collectAllTokens() external nonReentrant { EnumerableSet.UintSet storage ids = tokenIds[msg.sender]; for (uint256 i = 0; i < ids.length(); i++) { require(owners[ids.at(i)] == msg.sender, "NOT OWNER"); _collectReward(ids.at(i)); INonfungiblePositionManager.CollectParams memory params = _collectUniswapParam(ids.at(i), msg.sender); // collect swap fee from uniswap INonfungiblePositionManager(uniV3NFTManager).collect(params); } } /// @notice View function to get position ids staked here for an user. /// @param _user The related address. function getTokenIds(address _user) external view returns (uint256[] memory) { EnumerableSet.UintSet storage ids = tokenIds[_user]; // push could not be used in memory array // we set the tokenIdList into a fixed-length array rather than dynamic uint256[] memory tokenIdList = new uint256[](ids.length()); for (uint256 i = 0; i < ids.length(); i++) { tokenIdList[i] = ids.at(i); } return tokenIdList; } /// @notice Return reward multiplier over the given _from to _to block. /// @param _from The start block. /// @param _to The end block. function _getRewardBlockNum(uint256 _from, uint256 _to) internal view returns (uint256) { if (_from > _to) { return 0; } if (_to <= endBlock) { return _to - _from; } else if (_from >= endBlock) { return 0; } else { return endBlock - _from; } } /// @notice View function to see pending Reward for a single position. /// @param tokenId The related position id. function pendingReward(uint256 tokenId) public view returns (uint256[] memory) { TokenStatus memory t = tokenStatus[tokenId]; uint256[] memory _reward = new uint256[](rewardInfosLen); for (uint256 i = 0; i < rewardInfosLen; i++) { uint256 tokenReward = _getRewardBlockNum( lastTouchBlock, block.number ) * rewardInfos[i].rewardPerBlock; uint256 rewardPerShare = rewardInfos[i].accRewardPerShare + (tokenReward * FixedPoints.Q128) / totalVLiquidity; // l * (currentAcc - lastAcc) _reward[i] = (t.validVLiquidity * (rewardPerShare - t.lastTouchAccRewardPerShare[i])) / FixedPoints.Q128; } return _reward; } /// @notice View function to see pending Rewards for an address. /// @param _user The related address. function pendingRewards(address _user) external view returns (uint256[] memory) { uint256[] memory _reward = new uint256[](rewardInfosLen); for (uint256 j = 0; j < rewardInfosLen; j++) { _reward[j] = 0; } for (uint256 i = 0; i < tokenIds[_user].length(); i++) { uint256[] memory r = pendingReward(tokenIds[_user].at(i)); for (uint256 j = 0; j < rewardInfosLen; j++) { _reward[j] += r[j]; } } return _reward; } // Control fuctions for the contract owner and operators. /// @notice If something goes wrong, we can send back user's nft and locked assets /// @param tokenId The related position id. function emergenceWithdraw(uint256 tokenId) external onlyOwner { address owner = owners[tokenId]; require(owner != address(0)); INonfungiblePositionManager(uniV3NFTManager).safeTransferFrom( address(this), owner, tokenId ); TokenStatus storage t = tokenStatus[tokenId]; if (t.nIZI > 0) { // we should ensure nft refund to user // omit the case when transfer() returns false unexpectedly iziToken.transfer(owner, t.nIZI); } if (t.lockAmount > 0) { // we should ensure nft refund to user // omit the case when transfer() returns false unexpectedly IERC20(lockToken).transfer(owner, t.lockAmount); } // makesure user cannot withdraw/depositIZI or collect reward on this nft owners[tokenId] = address(0); } /// @notice Set new reward end block. /// @param _endBlock New end block. function modifyEndBlock(uint256 _endBlock) external onlyOwner { require(_endBlock > block.number, "OUT OF DATE"); _updateGlobalStatus(); // jump if origin endBlock < block.number lastTouchBlock = block.number; endBlock = _endBlock; emit ModifyEndBlock(endBlock); } /// @notice Set new reward per block. /// @param rewardIdx which rewardInfo to modify /// @param _rewardPerBlock new reward per block function modifyRewardPerBlock(uint256 rewardIdx, uint256 _rewardPerBlock) external onlyOwner { require(rewardIdx < rewardInfosLen, "OUT OF REWARD INFO RANGE"); _updateGlobalStatus(); rewardInfos[rewardIdx].rewardPerBlock = _rewardPerBlock; emit ModifyRewardPerBlock( rewardInfos[rewardIdx].rewardToken, _rewardPerBlock ); } /// @notice Set new reward provider. /// @param rewardIdx which rewardInfo to modify /// @param provider New provider function modifyProvider(uint256 rewardIdx, address provider) external onlyOwner { require(rewardIdx < rewardInfosLen, "OUT OF REWARD INFO RANGE"); rewardInfos[rewardIdx].provider = provider; emit ModifyProvider(rewardInfos[rewardIdx].rewardToken, provider); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "../uniswap/interfaces.sol"; import "./LogPowMath.sol"; library UniswapOracle { using UniswapOracle for address; struct Observation { uint32 blockTimestamp; int56 tickCumulative; uint160 secondsPerLiquidityCumulativeX128; bool initialized; } /// @dev query a certain observation from uniswap pool /// @param pool address of uniswap pool /// @param observationIndex index of wanted observation /// @return observation desired observation, see Observation to learn more function getObservation(address pool, uint observationIndex) internal view returns (Observation memory observation) { ( observation.blockTimestamp, observation.tickCumulative, observation.secondsPerLiquidityCumulativeX128, observation.initialized ) = IUniswapV3Pool(pool).observations(observationIndex); } /// @dev query latest and oldest observations from uniswap pool /// @param pool address of uniswap pool /// @param latestIndex index of latest observation in the pool /// @param observationCardinality size of observation queue in the pool /// @return oldestObservation /// @return latestObservation function getObservationBoundary(address pool, uint16 latestIndex, uint16 observationCardinality) internal view returns (Observation memory oldestObservation, Observation memory latestObservation) { uint16 oldestIndex = (latestIndex + 1) % observationCardinality; oldestObservation = pool.getObservation(oldestIndex); if (!oldestObservation.initialized) { oldestIndex = 0; oldestObservation = pool.getObservation(0); } if (latestIndex == oldestIndex) { // oldest observation is latest observation latestObservation = oldestObservation; } else { latestObservation = pool.getObservation(latestIndex); } } struct Slot0 { int24 tick; uint160 sqrtPriceX96; uint16 observationIndex; uint16 observationCardinality; } /// @dev view slot0 infomations from uniswap pool /// @param pool address of uniswap /// @return slot0 a Slot0 struct with necessary info, see Slot0 struct above function getSlot0(address pool) internal view returns (Slot0 memory slot0) { ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); slot0.tick = tick; slot0.sqrtPriceX96 = sqrtPriceX96; slot0.observationIndex = observationIndex; slot0.observationCardinality = observationCardinality; } // note if we call this interface, we must ensure that the // oldest observation preserved in pool is older than 2h ago function _getAvgTickFromTarget(address pool, uint32 targetTimestamp, int56 latestTickCumu, uint32 latestTimestamp) private view returns (int24 tick) { uint32[] memory secondsAgo = new uint32[](1); secondsAgo[0] = uint32(block.timestamp) - targetTimestamp; int56[] memory tickCumulatives; (tickCumulatives,) = IUniswapV3Pool(pool).observe(secondsAgo); uint56 timeDelta = latestTimestamp - targetTimestamp; int56 tickAvg = (latestTickCumu - tickCumulatives[0]) / int56(timeDelta); tick = int24(tickAvg); } /// @dev compute avg tick and avg sqrt price of pool within one hour from now /// @param pool address of uniswap pool /// @return tick computed avg tick /// @return sqrtPriceX96 computed avg sqrt price, in the form of 96-bit fixed point number function getAvgTickPriceWithin2Hour(address pool) internal view returns (int24 tick, uint160 sqrtPriceX96, int24 currTick, uint160 currSqrtPriceX96) { Slot0 memory slot0 = pool.getSlot0(); if (slot0.observationCardinality == 1) { // only 1 observation in the swap pool // we could simply return tick/sqrtPrice of slot0 return (slot0.tick, slot0.sqrtPriceX96, slot0.tick, slot0.sqrtPriceX96); } else { // we will search the latest observation and the observation 1h ago // 1st, we should get the boundary of the observations in the pool Observation memory oldestObservation; Observation memory latestObservation; (oldestObservation, latestObservation) = pool.getObservationBoundary(slot0.observationIndex, slot0.observationCardinality); if (oldestObservation.blockTimestamp == latestObservation.blockTimestamp) { // there is only 1 valid observation in the pool return (slot0.tick, slot0.sqrtPriceX96, slot0.tick, slot0.sqrtPriceX96); } uint32 twoHourAgo = uint32(block.timestamp - 7200); // now there must be at least 2 valid observations in the pool if (twoHourAgo <= oldestObservation.blockTimestamp || latestObservation.blockTimestamp <= oldestObservation.blockTimestamp + 3600) { // the oldest observation updated within 1h // we can not safely call IUniswapV3Pool.observe(...) for it 1h ago uint56 timeDelta = latestObservation.blockTimestamp - oldestObservation.blockTimestamp; int56 tickAvg = (latestObservation.tickCumulative - oldestObservation.tickCumulative) / int56(timeDelta); tick = int24(tickAvg); } else { // we are sure that the oldest observation is old enough // we can safely call IUniswapV3Pool.observe(...) for it 1h ago uint32 targetTimestamp = twoHourAgo; if (targetTimestamp + 3600 > latestObservation.blockTimestamp) { targetTimestamp = latestObservation.blockTimestamp - 3600; } tick = _getAvgTickFromTarget(pool, targetTimestamp, latestObservation.tickCumulative, latestObservation.blockTimestamp); } sqrtPriceX96 = LogPowMath.getSqrtPrice(tick); return (tick, sqrtPriceX96, slot0.tick, slot0.sqrtPriceX96); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library FixedPoints { uint256 constant Q32 = (1 << 32); uint256 constant Q64 = (1 << 64); uint256 constant Q96 = (1 << 96); uint256 constant Q128 = (1 << 128); uint256 constant Q160 = (1 << 160); } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall { function multicall(bytes[] calldata data) external payable returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IUniswapV3Pool { function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); } interface IUniswapV3Factory { /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); } interface INonfungiblePositionManager { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function ownerOf(uint256 tokenId) external view returns (address); function transferFrom( address from, address to, uint256 tokenId ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library LogPowMath { int24 internal constant MIN_POINT = -887272; int24 internal constant MAX_POINT = -MIN_POINT; uint160 internal constant MIN_SQRT_PRICE = 4295128739; uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342; /// @notice sqrt(1.0001^point) in form oy 96-bit fix point num function getSqrtPrice(int24 point) internal pure returns (uint160 sqrtPrice_96) { uint256 absIdx = point < 0 ? uint256(-int256(point)) : uint256(int256(point)); require(absIdx <= uint256(int256(MAX_POINT)), 'T'); uint256 value = absIdx & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absIdx & 0x2 != 0) value = (value * 0xfff97272373d413259a46990580e213a) >> 128; if (absIdx & 0x4 != 0) value = (value * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absIdx & 0x8 != 0) value = (value * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absIdx & 0x10 != 0) value = (value * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absIdx & 0x20 != 0) value = (value * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absIdx & 0x40 != 0) value = (value * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absIdx & 0x80 != 0) value = (value * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absIdx & 0x100 != 0) value = (value * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absIdx & 0x200 != 0) value = (value * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absIdx & 0x400 != 0) value = (value * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absIdx & 0x800 != 0) value = (value * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absIdx & 0x1000 != 0) value = (value * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absIdx & 0x2000 != 0) value = (value * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absIdx & 0x4000 != 0) value = (value * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absIdx & 0x8000 != 0) value = (value * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absIdx & 0x10000 != 0) value = (value * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absIdx & 0x20000 != 0) value = (value * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absIdx & 0x40000 != 0) value = (value * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absIdx & 0x80000 != 0) value = (value * 0x48a170391f7dc42444e8fa2) >> 128; if (point > 0) value = type(uint256).max / value; sqrtPrice_96 = uint160((value >> 32) + (value % (1 << 32) == 0 ? 0 : 1)); } // floor(log1.0001(sqrtPrice_96)) function getLogSqrtPriceFloor(uint160 sqrtPrice_96) internal pure returns (int24 logValue) { // second inequality must be < because the price can nevex reach the price at the max tick require(sqrtPrice_96 >= MIN_SQRT_PRICE && sqrtPrice_96 < MAX_SQRT_PRICE, 'R'); uint256 sqrtPrice_128 = uint256(sqrtPrice_96) << 32; uint256 x = sqrtPrice_128; uint256 m = 0; assembly { let y := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(5, gt(x, 0xFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(4, gt(x, 0xFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(3, gt(x, 0xFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(2, gt(x, 0xF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(1, gt(x, 0x3)) m := or(m, y) x := shr(y, x) } assembly { let y := gt(x, 0x1) m := or(m, y) } if (m >= 128) x = sqrtPrice_128 >> (m - 127); else x = sqrtPrice_128 << (127 - m); int256 l2 = (int256(m) - 128) << 64; assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(63, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(62, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(61, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(60, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(59, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(58, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(57, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(56, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(55, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(54, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(53, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(52, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(51, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(50, y)) } int256 ls10001 = l2 * 255738958999603826347141; int24 logFloor = int24((ls10001 - 3402992956809132418596140100660247210) >> 128); int24 logUpper = int24((ls10001 + 291339464771989622907027621153398088495) >> 128); logValue = logFloor == logUpper ? logFloor : getSqrtPrice(logUpper) <= sqrtPrice_96 ? logUpper : logFloor; } function getLogSqrtPriceFU(uint160 sqrtPrice_96) internal pure returns (int24 logFloor, int24 logUpper) { // second inequality must be < because the price can nevex reach the price at the max tick require(sqrtPrice_96 >= MIN_SQRT_PRICE && sqrtPrice_96 < MAX_SQRT_PRICE, 'R'); uint256 sqrtPrice_128 = uint256(sqrtPrice_96) << 32; uint256 x = sqrtPrice_128; uint256 m = 0; assembly { let y := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(5, gt(x, 0xFFFFFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(4, gt(x, 0xFFFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(3, gt(x, 0xFF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(2, gt(x, 0xF)) m := or(m, y) x := shr(y, x) } assembly { let y := shl(1, gt(x, 0x3)) m := or(m, y) x := shr(y, x) } assembly { let y := gt(x, 0x1) m := or(m, y) } if (m >= 128) x = sqrtPrice_128 >> (m - 127); else x = sqrtPrice_128 << (127 - m); int256 l2 = (int256(m) - 128) << 64; assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(63, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(62, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(61, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(60, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(59, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(58, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(57, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(56, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(55, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(54, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(53, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(52, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(51, y)) x := shr(y, x) } assembly { x := shr(127, mul(x, x)) let y := shr(128, x) l2 := or(l2, shl(50, y)) } int256 ls10001 = l2 * 255738958999603826347141; logFloor = int24((ls10001 - 3402992956809132418596140100660247210) >> 128); logUpper = int24((ls10001 + 291339464771989622907027621153398088495) >> 128); } }
Set new reward provider. rewardIdx which rewardInfo to modify provider New provider
function modifyProvider(uint256 rewardIdx, address provider) external onlyOwner { require(rewardIdx < rewardInfosLen, "OUT OF REWARD INFO RANGE"); rewardInfos[rewardIdx].provider = provider; emit ModifyProvider(rewardInfos[rewardIdx].rewardToken, provider); }
5,850,582
//Address: 0x00391d08b3e68e476a774ada379258264eb74485 //Contract name: DipTge //Balance: 0 Ether //Verification Date: 6/22/2018 //Transacion Count: 14 // CODE STARTS HERE pragma solidity 0.4.24; // File: contracts/tokensale/DipTgeInterface.sol contract DipTgeInterface { function tokenIsLocked(address _contributor) public constant returns (bool); } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event 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; } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @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; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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]; } } // File: zeppelin-solidity/contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public 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); } // File: zeppelin-solidity/contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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; } } // File: zeppelin-solidity/contracts/token/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ 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; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() 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(); } } // File: zeppelin-solidity/contracts/token/PausableToken.sol /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ 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); } } // File: contracts/token/DipToken.sol /** * @title DIP Token * @dev The Decentralized Insurance Platform Token. * @author Christoph Mussenbrock * @copyright 2017 Etherisc GmbH */ pragma solidity 0.4.24; contract DipToken is PausableToken, MintableToken { string public constant name = "Decentralized Insurance Protocol"; string public constant symbol = "DIP"; uint256 public constant decimals = 18; uint256 public constant MAXIMUM_SUPPLY = 10**9 * 10**18; // 1 Billion 1'000'000'000 DipTgeInterface public DipTokensale; constructor() public { DipTokensale = DipTgeInterface(owner); } modifier shouldNotBeLockedIn(address _contributor) { // after LockIntTime2, we don't need to check anymore, and // the DipTokensale contract is no longer required. require(DipTokensale.tokenIsLocked(_contributor) == false); _; } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public returns (bool) { if (totalSupply.add(_amount) > MAXIMUM_SUPPLY) { return false; } return super.mint(_to, _amount); } /** * Owner can transfer back tokens which have been sent to this contract by mistake. * @param _token address of token contract of the respective tokens * @param _to where to send the tokens */ function salvageTokens(ERC20Basic _token, address _to) onlyOwner public { _token.transfer(_to, _token.balanceOf(this)); } function transferFrom(address _from, address _to, uint256 _value) shouldNotBeLockedIn(_from) public returns (bool) { return super.transferFrom(_from, _to, _value); } function transfer(address to, uint256 value) shouldNotBeLockedIn(msg.sender) public returns (bool) { return super.transfer(to, value); } } // File: zeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ 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; } } // File: contracts/tokensale/DipWhitelistedCrowdsale.sol /** * @title DIP Token Generating Event * @dev The Decentralized Insurance Platform Token. * @author Christoph Mussenbrock * @copyright 2017 Etherisc GmbH */ pragma solidity 0.4.24; contract DipWhitelistedCrowdsale is Ownable { using SafeMath for uint256; struct ContributorData { uint256 allowance; uint256 contributionAmount; uint256 tokensIssued; bool airdrop; uint256 bonus; // 0 == 0%, 4 == 25%, 10 == 10% uint256 lockupPeriod; // 0, 1 or 2 (years) } mapping (address => ContributorData) public contributorList; event Whitelisted(address indexed _contributor, uint256 _allowance, bool _airdrop, uint256 _bonus, uint256 _lockupPeriod); /** * Push contributor data to the contract before the crowdsale */ function editContributors ( address[] _contributorAddresses, uint256[] _contributorAllowance, bool[] _airdrop, uint256[] _bonus, uint256[] _lockupPeriod ) onlyOwner public { // Check if input data is consistent require( _contributorAddresses.length == _contributorAllowance.length && _contributorAddresses.length == _airdrop.length && _contributorAddresses.length == _bonus.length && _contributorAddresses.length == _lockupPeriod.length ); for (uint256 cnt = 0; cnt < _contributorAddresses.length; cnt = cnt.add(1)) { require(_bonus[cnt] == 0 || _bonus[cnt] == 4 || _bonus[cnt] == 10); require(_lockupPeriod[cnt] <= 2); address contributor = _contributorAddresses[cnt]; contributorList[contributor].allowance = _contributorAllowance[cnt]; contributorList[contributor].airdrop = _airdrop[cnt]; contributorList[contributor].bonus = _bonus[cnt]; contributorList[contributor].lockupPeriod = _lockupPeriod[cnt]; emit Whitelisted( _contributorAddresses[cnt], _contributorAllowance[cnt], _airdrop[cnt], _bonus[cnt], _lockupPeriod[cnt] ); } } } // File: zeppelin-solidity/contracts/crowdsale/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ 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 { } } // File: contracts/tokensale/DipTge.sol /** * @title DIP Token Generating Event * @notice The Decentralized Insurance Platform Token. * @author Christoph Mussenbrock * * @copyright 2017 Etherisc GmbH */ pragma solidity 0.4.24; contract DipTge is DipWhitelistedCrowdsale, FinalizableCrowdsale { using SafeMath for uint256; enum state { pendingStart, priorityPass, crowdsale, crowdsaleEnded } uint256 public startOpenPpTime; uint256 public hardCap; uint256 public lockInTime1; // token lock-in period for team, ECA, US accredited investors uint256 public lockInTime2; // token lock-in period for founders state public crowdsaleState = state.pendingStart; event DipTgeStarted(uint256 _time); event CrowdsaleStarted(uint256 _time); event HardCapReached(uint256 _time); event DipTgeEnded(uint256 _time); event TokenAllocated(address _beneficiary, uint256 _amount); constructor( uint256 _startTime, uint256 _startOpenPpTime, uint256 _endTime, uint256 _lockInTime1, uint256 _lockInTime2, uint256 _hardCap, uint256 _rate, address _wallet ) Crowdsale(_startTime, _endTime, _rate, _wallet) public { // Check arguments require(_startTime >= block.timestamp); require(_startOpenPpTime >= _startTime); require(_endTime >= _startOpenPpTime); require(_lockInTime1 >= _endTime); require(_lockInTime2 > _lockInTime1); require(_hardCap > 0); require(_rate > 0); require(_wallet != 0x0); // Set contract fields startOpenPpTime = _startOpenPpTime; hardCap = _hardCap; lockInTime1 = _lockInTime1; lockInTime2 = _lockInTime2; DipToken(token).pause(); } function setRate(uint256 _rate) onlyOwner public { require(crowdsaleState == state.pendingStart); rate = _rate; } function unpauseToken() onlyOwner external { DipToken(token).unpause(); } /** * Calculate the maximum remaining contribution allowed for an address * @param _contributor the address of the contributor * @return maxContribution maximum allowed amount in wei */ function calculateMaxContribution(address _contributor) public constant returns (uint256 _maxContribution) { uint256 maxContrib = 0; if (crowdsaleState == state.priorityPass) { maxContrib = contributorList[_contributor].allowance.sub(contributorList[_contributor].contributionAmount); if (maxContrib > hardCap.sub(weiRaised)) { maxContrib = hardCap.sub(weiRaised); } } else if (crowdsaleState == state.crowdsale) { if (contributorList[_contributor].allowance > 0) { maxContrib = hardCap.sub(weiRaised); } } return maxContrib; } /** * Calculate amount of tokens * This is used twice: * 1) For calculation of token amount plus optional bonus from wei amount contributed * In this case, rate is the defined exchange rate of ETH against DIP. * 2) For calculation of token amount plus optional bonus from DIP token amount * In the second case, rate == 1 because we have already calculated DIP tokens from RSC amount * by applying a factor of 10/32. * @param _contributor the address of the contributor * @param _amount contribution amount * @return _tokens amount of tokens */ function calculateTokens(address _contributor, uint256 _amount, uint256 _rate) public constant returns (uint256 _tokens) { uint256 bonus = contributorList[_contributor].bonus; assert(bonus == 0 || bonus == 4 || bonus == 10); if (bonus > 0) { _tokens = _amount.add(_amount.div(bonus)).mul(_rate); } else { _tokens = _amount.mul(_rate); } } /** * Set the current state of the crowdsale. */ function setCrowdsaleState() public { if (weiRaised >= hardCap && crowdsaleState != state.crowdsaleEnded) { crowdsaleState = state.crowdsaleEnded; emit HardCapReached(block.timestamp); emit DipTgeEnded(block.timestamp); } else if ( block.timestamp >= startTime && block.timestamp < startOpenPpTime && crowdsaleState != state.priorityPass ) { crowdsaleState = state.priorityPass; emit DipTgeStarted(block.timestamp); } else if ( block.timestamp >= startOpenPpTime && block.timestamp <= endTime && crowdsaleState != state.crowdsale ) { crowdsaleState = state.crowdsale; emit CrowdsaleStarted(block.timestamp); } else if ( crowdsaleState != state.crowdsaleEnded && block.timestamp > endTime ) { crowdsaleState = state.crowdsaleEnded; emit DipTgeEnded(block.timestamp); } } /** * The token buying function. * @param _beneficiary receiver of tokens. */ function buyTokens(address _beneficiary) public payable { require(_beneficiary != 0x0); require(validPurchase()); require(contributorList[_beneficiary].airdrop == false); setCrowdsaleState(); uint256 weiAmount = msg.value; uint256 maxContrib = calculateMaxContribution(_beneficiary); uint256 refund; if (weiAmount > maxContrib) { refund = weiAmount.sub(maxContrib); weiAmount = maxContrib; } // stop here if transaction does not yield tokens require(weiAmount > 0); // calculate token amount to be created uint256 tokens = calculateTokens(_beneficiary, weiAmount, rate); assert(tokens > 0); // update state weiRaised = weiRaised.add(weiAmount); require(token.mint(_beneficiary, tokens)); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); contributorList[_beneficiary].contributionAmount = contributorList[_beneficiary].contributionAmount.add(weiAmount); contributorList[_beneficiary].tokensIssued = contributorList[_beneficiary].tokensIssued.add(tokens); wallet.transfer(weiAmount); if (refund != 0) _beneficiary.transfer(refund); } /** * Check if token is locked. */ function tokenIsLocked(address _contributor) public constant returns (bool) { if (block.timestamp < lockInTime1 && contributorList[_contributor].lockupPeriod == 1) { return true; } else if (block.timestamp < lockInTime2 && contributorList[_contributor].lockupPeriod == 2) { return true; } return false; } /** * Distribute tokens to selected team members & founders. * Unit of Allowance is ETH and is converted in number of tokens by multiplying with Rate. * This can be called by any whitelisted beneficiary. */ function airdrop() public { airdropFor(msg.sender); } /** * Alternatively to airdrop(); tokens can be directly sent to beneficiaries by this function * This can be called only once. */ function airdropFor(address _beneficiary) public { require(_beneficiary != 0x0); require(contributorList[_beneficiary].airdrop == true); require(contributorList[_beneficiary].tokensIssued == 0); require(contributorList[_beneficiary].allowance > 0); setCrowdsaleState(); require(crowdsaleState == state.crowdsaleEnded); uint256 amount = contributorList[_beneficiary].allowance.mul(rate); require(token.mint(_beneficiary, amount)); emit TokenAllocated(_beneficiary, amount); contributorList[_beneficiary].tokensIssued = contributorList[_beneficiary].tokensIssued.add(amount); } /** * Creates an new ERC20 Token contract for the DIP Token. * Overrides Crowdsale function * @return the created token */ function createTokenContract() internal returns (MintableToken) { return new DipToken(); } /** * Finalize sale and perform cleanup actions. */ function finalization() internal { uint256 maxSupply = DipToken(token).MAXIMUM_SUPPLY(); token.mint(wallet, maxSupply.sub(token.totalSupply())); // Alternativly, hardcode remaining token distribution. token.finishMinting(); token.transferOwnership(owner); } /** * Owner can transfer back tokens which have been sent to this contract by mistake. * @param _token address of token contract of the respective tokens * @param _to where to send the tokens */ function salvageTokens(ERC20Basic _token, address _to) onlyOwner external { _token.transfer(_to, _token.balanceOf(this)); } }
Calculate amount of tokens This is used twice: 1) For calculation of token amount plus optional bonus from wei amount contributed In this case, rate is the defined exchange rate of ETH against DIP. 2) For calculation of token amount plus optional bonus from DIP token amount In the second case, rate == 1 because we have already calculated DIP tokens from RSC amount by applying a factor of 10/32. _contributor the address of the contributor _amount contribution amount return _tokens amount of tokens/
function calculateTokens(address _contributor, uint256 _amount, uint256 _rate) public constant returns (uint256 _tokens) { uint256 bonus = contributorList[_contributor].bonus; assert(bonus == 0 || bonus == 4 || bonus == 10); if (bonus > 0) { _tokens = _amount.add(_amount.div(bonus)).mul(_rate); _tokens = _amount.mul(_rate); } }
994,333
// File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // 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: contracts/interfaces/IVat.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the vat contract from MakerDAO /// Taken from https://github.com/makerdao/developerguides/blob/master/devtools/working-with-dsproxy/working-with-dsproxy.md interface IVat { // function can(address, address) external view returns (uint); function hope(address) external; function nope(address) external; function live() external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function urns(bytes32, address) external view returns (uint, uint); function gem(bytes32, address) external view returns (uint); // function dai(address) external view returns (uint); function frob(bytes32, address, address, address, int, int) external; function fork(bytes32, address, address, int, int) external; function move(address, address, uint) external; function flux(bytes32, address, address, uint) external; } // File: contracts/interfaces/IPot.sol pragma solidity ^0.6.10; /// @dev interface for the pot contract from MakerDao /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IPot { function chi() external view returns (uint256); function pie(address) external view returns (uint256); // Not a function, but a public variable. function rho() external returns (uint256); function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } // 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/interfaces/IWeth.sol pragma solidity ^0.6.10; interface IWeth { function deposit() external payable; function withdraw(uint) external; function approve(address, uint) external returns (bool) ; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } // File: contracts/interfaces/IGemJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using ERC20 interface IGemJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IDaiJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using Dai interface IDaiJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IChai.sol pragma solidity ^0.6.10; /// @dev interface for the chai contract /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IChai { function balanceOf(address account) external view returns (uint256); function transfer(address dst, uint wad) external returns (bool); function move(address src, address dst, uint wad) external returns (bool); function transferFrom(address src, address dst, uint wad) external returns (bool); function approve(address usr, uint wad) external returns (bool); function dai(address usr) external returns (uint wad); function join(address dst, uint wad) external; function exit(address src, uint wad) external; function draw(address src, uint wad) external; function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function nonces(address account) external view returns (uint256); } // File: contracts/interfaces/ITreasury.sol pragma solidity ^0.6.10; interface ITreasury { function debt() external view returns(uint256); function savings() external view returns(uint256); function pushDai(address user, uint256 dai) external; function pullDai(address user, uint256 dai) external; function pushChai(address user, uint256 chai) external; function pullChai(address user, uint256 chai) external; function pushWeth(address to, uint256 weth) external; function pullWeth(address to, uint256 weth) external; function shutdown() external; function live() external view returns(bool); function vat() external view returns (IVat); function weth() external view returns (IWeth); function dai() external view returns (IERC20); function daiJoin() external view returns (IDaiJoin); function wethJoin() external view returns (IGemJoin); function pot() external view returns (IPot); function chai() external view returns (IChai); } // File: contracts/interfaces/IDelegable.sol pragma solidity ^0.6.10; interface IDelegable { function addDelegate(address) external; function addDelegateBySignature(address, address, uint, uint8, bytes32, bytes32) external; } // File: contracts/interfaces/IERC2612.sol // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ pragma solidity ^0.6.0; /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612 { /** * @dev Sets `amount` 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: * * - `owner` cannot be the zero address. * - `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 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current ERC2612 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); } // File: contracts/interfaces/IFYDai.sol pragma solidity ^0.6.10; interface IFYDai is IERC20, IERC2612 { function isMature() external view returns(bool); function maturity() external view returns(uint); function chi0() external view returns(uint); function rate0() external view returns(uint); function chiGrowth() external view returns(uint); function rateGrowth() external view returns(uint); function mature() external; function unlocked() external view returns (uint); function mint(address, uint) external; function burn(address, uint) external; function flashMint(uint, bytes calldata) external; function redeem(address, address, uint256) external returns (uint256); // function transfer(address, uint) external returns (bool); // function transferFrom(address, address, uint) external returns (bool); // function approve(address, uint) external returns (bool); } // File: contracts/interfaces/IController.sol pragma solidity ^0.6.10; interface IController is IDelegable { function treasury() external view returns (ITreasury); function series(uint256) external view returns (IFYDai); function seriesIterator(uint256) external view returns (uint256); function totalSeries() external view returns (uint256); function containsSeries(uint256) external view returns (bool); function posted(bytes32, address) external view returns (uint256); function debtFYDai(bytes32, uint256, address) external view returns (uint256); function debtDai(bytes32, uint256, address) external view returns (uint256); function totalDebtDai(bytes32, address) external view returns (uint256); function isCollateralized(bytes32, address) external view returns (bool); function inDai(bytes32, uint256, uint256) external view returns (uint256); function inFYDai(bytes32, uint256, uint256) external view returns (uint256); function erase(bytes32, address) external returns (uint256, uint256); function shutdown() external; function post(bytes32, address, address, uint256) external; function withdraw(bytes32, address, address, uint256) external; function borrow(bytes32, uint256, address, address, uint256) external; function repayFYDai(bytes32, uint256, address, address, uint256) external returns (uint256); function repayDai(bytes32, uint256, address, address, uint256) external returns (uint256); } // File: contracts/helpers/Delegable.sol pragma solidity ^0.6.10; /// @dev Delegable enables users to delegate their account management to other users. /// Delegable implements addDelegateBySignature, to add delegates using a signature instead of a separate transaction. contract Delegable is IDelegable { event Delegate(address indexed user, address indexed delegate, bool enabled); // keccak256("Signature(address user,address delegate,uint256 nonce,uint256 deadline)"); bytes32 public immutable SIGNATURE_TYPEHASH = 0x0d077601844dd17f704bafff948229d27f33b57445915754dfe3d095fda2beb7; bytes32 public immutable DELEGABLE_DOMAIN; mapping(address => uint) public signatureCount; mapping(address => mapping(address => bool)) public delegated; constructor () public { uint256 chainId; assembly { chainId := chainid() } DELEGABLE_DOMAIN = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes('Yield')), keccak256(bytes('1')), chainId, address(this) ) ); } /// @dev Require that msg.sender is the account holder or a delegate modifier onlyHolderOrDelegate(address holder, string memory errorMessage) { require( msg.sender == holder || delegated[holder][msg.sender], errorMessage ); _; } /// @dev Enable a delegate to act on the behalf of caller function addDelegate(address delegate) public override { _addDelegate(msg.sender, delegate); } /// @dev Stop a delegate from acting on the behalf of caller function revokeDelegate(address delegate) public { _revokeDelegate(msg.sender, delegate); } /// @dev Add a delegate through an encoded signature function addDelegateBySignature(address user, address delegate, uint deadline, uint8 v, bytes32 r, bytes32 s) public override { require(deadline >= block.timestamp, 'Delegable: Signature expired'); bytes32 hashStruct = keccak256( abi.encode( SIGNATURE_TYPEHASH, user, delegate, signatureCount[user]++, deadline ) ); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DELEGABLE_DOMAIN, hashStruct ) ); address signer = ecrecover(digest, v, r, s); require( signer != address(0) && signer == user, 'Delegable: Invalid signature' ); _addDelegate(user, delegate); } /// @dev Enable a delegate to act on the behalf of an user function _addDelegate(address user, address delegate) internal { require(!delegated[user][delegate], "Delegable: Already delegated"); delegated[user][delegate] = true; emit Delegate(user, delegate, true); } /// @dev Stop a delegate from acting on the behalf of an user function _revokeDelegate(address user, address delegate) internal { require(delegated[user][delegate], "Delegable: Already undelegated"); delegated[user][delegate] = false; emit Delegate(user, delegate, false); } } // File: contracts/helpers/DecimalMath.sol pragma solidity ^0.6.10; /// @dev Implements simple fixed point math mul and div operations for 27 decimals. contract DecimalMath { using SafeMath for uint256; uint256 constant public UNIT = 1e27; /// @dev Multiplies x and y, assuming they are both fixed point with 27 digits. function muld(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(y).div(UNIT); } /// @dev Divides x between y, assuming they are both fixed point with 27 digits. function divd(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(UNIT).div(y); } /// @dev Multiplies x and y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function muldrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(y); return z.mod(UNIT) == 0 ? z.div(UNIT) : z.div(UNIT).add(1); } /// @dev Divides x between y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function divdrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(UNIT); return z.mod(y) == 0 ? z.div(y) : z.div(y).add(1); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/helpers/Orchestrated.sol pragma solidity ^0.6.10; /** * @dev Orchestrated allows to define static access control between multiple contracts. * This contract would be used as a parent contract of any contract that needs to restrict access to some methods, * which would be marked with the `onlyOrchestrated` modifier. * During deployment, the contract deployer (`owner`) can register any contracts that have privileged access by calling `orchestrate`. * Once deployment is completed, `owner` should call `transferOwnership(address(0))` to avoid any more contracts ever gaining privileged access. */ contract Orchestrated is Ownable { event GrantedAccess(address access, bytes4 signature); mapping(address => mapping (bytes4 => bool)) public orchestration; constructor () public Ownable() {} /// @dev Restrict usage to authorized users /// @param err The error to display if the validation fails modifier onlyOrchestrated(string memory err) { require(orchestration[msg.sender][msg.sig], err); _; } /// @dev Add orchestration /// @param user Address of user or contract having access to this contract. /// @param signature bytes4 signature of the function we are giving orchestrated access to. /// It seems to me a bad idea to give access to humans, and would use this only for predictable smart contracts. function orchestrate(address user, bytes4 signature) public onlyOwner { orchestration[user][signature] = true; emit GrantedAccess(user, signature); } /// @dev Adds orchestration for the provided function signatures function batchOrchestrate(address user, bytes4[] memory signatures) public onlyOwner { for (uint256 i = 0; i < signatures.length; i++) { orchestrate(user, signatures[i]); } } } // File: contracts/Controller.sol pragma solidity ^0.6.10; /** * @dev The Controller manages collateral and debt levels for all users, and it is a major user entry point for the Yield protocol. * Controller keeps track of a number of fyDai contracts. * Controller allows users to post and withdraw Chai and Weth collateral. * Any transactions resulting in a user weth collateral below dust are reverted. * Controller allows users to borrow fyDai against their Chai and Weth collateral. * Controller allows users to repay their fyDai debt with fyDai or with Dai. * Controller integrates with fyDai contracts for minting fyDai on borrowing, and burning fyDai on repaying debt with fyDai. * Controller relies on Treasury for all other asset transfers. * Controller allows orchestrated contracts to erase any amount of debt or collateral for an user. This is to be used during liquidations or during unwind. * Users can delegate the control of their accounts in Controllers to any address. */ contract Controller is IController, Orchestrated(), Delegable(), DecimalMath { using SafeMath for uint256; event Posted(bytes32 indexed collateral, address indexed user, int256 amount); event Borrowed(bytes32 indexed collateral, uint256 indexed maturity, address indexed user, int256 amount); bytes32 public constant CHAI = "CHAI"; bytes32 public constant WETH = "ETH-A"; uint256 public constant DUST = 50e15; // 0.05 ETH IVat public vat; IPot public pot; ITreasury public override treasury; mapping(uint256 => IFYDai) public override series; // FYDai series, indexed by maturity uint256[] public override seriesIterator; // We need to know all the series mapping(bytes32 => mapping(address => uint256)) public override posted; // Collateral posted by each user mapping(bytes32 => mapping(uint256 => mapping(address => uint256))) public override debtFYDai; // Debt owed by each user, by series bool public live = true; /// @dev Set up addresses for vat, pot and Treasury. constructor ( address treasury_, address[] memory fyDais ) public { treasury = ITreasury(treasury_); vat = treasury.vat(); pot = treasury.pot(); for (uint256 i = 0; i < fyDais.length; i += 1) { addSeries(fyDais[i]); } } /// @dev Modified functions only callable while the Controller is not unwinding due to a MakerDAO shutdown. modifier onlyLive() { require(live == true, "Controller: Not available during unwind"); _; } /// @dev Only valid collateral types are Weth and Chai. modifier validCollateral(bytes32 collateral) { require( collateral == WETH || collateral == CHAI, "Controller: Unrecognized collateral" ); _; } /// @dev Only series added through `addSeries` are valid. modifier validSeries(uint256 maturity) { require( containsSeries(maturity), "Controller: Unrecognized series" ); _; } /// @dev Safe casting from uint256 to int256 function toInt256(uint256 x) internal pure returns(int256) { require( x <= uint256(type(int256).max), "Controller: Cast overflow" ); return int256(x); } /// @dev Disables post, withdraw, borrow and repay. To be called only when Treasury shuts down. function shutdown() public override { require( treasury.live() == false, "Controller: Treasury is live" ); live = false; } /// @dev Return if the borrowing power for a given collateral of a user is equal or greater /// than its debt for the same collateral /// @param collateral Valid collateral type /// @param user Address of the user vault function isCollateralized(bytes32 collateral, address user) public view override returns (bool) { return powerOf(collateral, user) >= totalDebtDai(collateral, user); } /// @dev Return if the collateral of an user is between zero and the dust level /// @param collateral Valid collateral type /// @param user Address of the user vault function aboveDustOrZero(bytes32 collateral, address user) public view returns (bool) { uint256 postedCollateral = posted[collateral][user]; return postedCollateral == 0 || DUST < postedCollateral; } /// @dev Return the total number of series registered function totalSeries() public view override returns (uint256) { return seriesIterator.length; } /// @dev Returns if a series has been added to the Controller. /// @param maturity Maturity of the series to verify. function containsSeries(uint256 maturity) public view override returns (bool) { return address(series[maturity]) != address(0); } /// @dev Adds an fyDai series to this Controller /// After deployment, ownership should be renounced, so that no more series can be added. /// @param fyDaiContract Address of the fyDai series to add. function addSeries(address fyDaiContract) private { uint256 maturity = IFYDai(fyDaiContract).maturity(); require( !containsSeries(maturity), "Controller: Series already added" ); series[maturity] = IFYDai(fyDaiContract); seriesIterator.push(maturity); } /// @dev Dai equivalent of an fyDai amount. /// After maturity, the Dai value of an fyDai grows according to either the stability fee (for WETH collateral) or the Dai Saving Rate (for Chai collateral). /// @param collateral Valid collateral type /// @param maturity Maturity of an added series /// @param fyDaiAmount Amount of fyDai to convert. /// @return Dai equivalent of an fyDai amount. function inDai(bytes32 collateral, uint256 maturity, uint256 fyDaiAmount) public view override validCollateral(collateral) returns (uint256) { IFYDai fyDai = series[maturity]; if (fyDai.isMature()){ if (collateral == WETH){ return muld(fyDaiAmount, fyDai.rateGrowth()); } else if (collateral == CHAI) { return muld(fyDaiAmount, fyDai.chiGrowth()); } } else { return fyDaiAmount; } } /// @dev fyDai equivalent of a Dai amount. /// After maturity, the fyDai value of a Dai decreases according to either the stability fee (for WETH collateral) or the Dai Saving Rate (for Chai collateral). /// @param collateral Valid collateral type /// @param maturity Maturity of an added series /// @param daiAmount Amount of Dai to convert. /// @return fyDai equivalent of a Dai amount. function inFYDai(bytes32 collateral, uint256 maturity, uint256 daiAmount) public view override validCollateral(collateral) returns (uint256) { IFYDai fyDai = series[maturity]; if (fyDai.isMature()){ if (collateral == WETH){ return divd(daiAmount, fyDai.rateGrowth()); } else if (collateral == CHAI) { return divd(daiAmount, fyDai.chiGrowth()); } } else { return daiAmount; } } /// @dev Debt in dai of an user /// After maturity, the Dai debt of a position grows according to either the stability fee (for WETH collateral) or the Dai Saving Rate (for Chai collateral). /// @param collateral Valid collateral type /// @param maturity Maturity of an added series /// @param user Address of the user vault /// @return Debt in dai of an user // // rate_now // debt_now = debt_mat * ---------- // rate_mat // function debtDai(bytes32 collateral, uint256 maturity, address user) public view override returns (uint256) { return inDai(collateral, maturity, debtFYDai[collateral][maturity][user]); } /// @dev Total debt of an user across all series, in Dai /// The debt is summed across all series, taking into account interest on the debt after a series matures. /// This function loops through all maturities, limiting the contract to hundreds of maturities. /// @param collateral Valid collateral type /// @param user Address of the user vault /// @return Total debt of an user across all series, in Dai function totalDebtDai(bytes32 collateral, address user) public view override returns (uint256) { uint256 totalDebt; uint256[] memory _seriesIterator = seriesIterator; for (uint256 i = 0; i < _seriesIterator.length; i += 1) { if (debtFYDai[collateral][_seriesIterator[i]][user] > 0) { totalDebt = totalDebt.add(debtDai(collateral, _seriesIterator[i], user)); } } // We don't expect hundreds of maturities per controller return totalDebt; } /// @dev Borrowing power (in dai) of a user for a specific series and collateral. /// @param collateral Valid collateral type /// @param user Address of the user vault /// @return Borrowing power of an user in dai. // // powerOf[user](wad) = posted[user](wad) * price()(ray) // function powerOf(bytes32 collateral, address user) public view returns (uint256) { // dai = price * collateral if (collateral == WETH){ (,, uint256 spot,,) = vat.ilks(WETH); // Stability fee and collateralization ratio for Weth return muld(posted[collateral][user], spot); } else if (collateral == CHAI) { uint256 chi = pot.chi(); return muld(posted[collateral][user], chi); } else { revert("Controller: Invalid collateral type"); } } /// @dev Returns the amount of collateral locked in borrowing operations. /// @param collateral Valid collateral type. /// @param user Address of the user vault. function locked(bytes32 collateral, address user) public view validCollateral(collateral) returns (uint256) { if (collateral == WETH){ (,, uint256 spot,,) = vat.ilks(WETH); // Stability fee and collateralization ratio for Weth return divdrup(totalDebtDai(collateral, user), spot); } else if (collateral == CHAI) { return divdrup(totalDebtDai(collateral, user), pot.chi()); } } /// @dev Takes collateral assets from `from` address, and credits them to `to` collateral account. /// `from` can delegate to other addresses to take assets from him. Also needs to use `ERC20.approve`. /// Calling ERC20.approve for Treasury contract is a prerequisite to this function /// @param collateral Valid collateral type. /// @param from Wallet to take collateral from. /// @param to Yield vault to put the collateral in. /// @param amount Amount of collateral to move. // from --- Token ---> us(to) function post(bytes32 collateral, address from, address to, uint256 amount) public override validCollateral(collateral) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive { posted[collateral][to] = posted[collateral][to].add(amount); if (collateral == WETH){ require( aboveDustOrZero(collateral, to), "Controller: Below dust" ); treasury.pushWeth(from, amount); } else if (collateral == CHAI) { treasury.pushChai(from, amount); } emit Posted(collateral, to, toInt256(amount)); } /// @dev Returns collateral to `to` wallet, taking it from `from` Yield vault account. /// `from` can delegate to other addresses to take assets from him. /// @param collateral Valid collateral type. /// @param from Yield vault to take collateral from. /// @param to Wallet to put the collateral in. /// @param amount Amount of collateral to move. // us(from) --- Token ---> to function withdraw(bytes32 collateral, address from, address to, uint256 amount) public override validCollateral(collateral) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive { posted[collateral][from] = posted[collateral][from].sub(amount); // Will revert if not enough posted require( isCollateralized(collateral, from), "Controller: Too much debt" ); if (collateral == WETH){ require( aboveDustOrZero(collateral, from), "Controller: Below dust" ); treasury.pullWeth(to, amount); } else if (collateral == CHAI) { treasury.pullChai(to, amount); } emit Posted(collateral, from, -toInt256(amount)); } /// @dev Mint fyDai for a given series for wallet `to` by increasing the user debt in Yield vault `from` /// `from` can delegate to other addresses to borrow using his vault. /// The collateral needed changes according to series maturity and MakerDAO rate and chi, depending on collateral type. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param from Yield vault that gets an increased debt. /// @param to Wallet to put the fyDai in. /// @param fyDaiAmount Amount of fyDai to borrow. // // posted[user](wad) >= (debtFYDai[user](wad)) * amount (wad)) * collateralization (ray) // // us(from) --- fyDai ---> to // debt++ function borrow(bytes32 collateral, uint256 maturity, address from, address to, uint256 fyDaiAmount) public override validCollateral(collateral) validSeries(maturity) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive { IFYDai fyDai = series[maturity]; debtFYDai[collateral][maturity][from] = debtFYDai[collateral][maturity][from].add(fyDaiAmount); require( isCollateralized(collateral, from), "Controller: Too much debt" ); fyDai.mint(to, fyDaiAmount); emit Borrowed(collateral, maturity, from, toInt256(fyDaiAmount)); } /// @dev Burns fyDai from `from` wallet to repay debt in a Yield Vault. /// User debt is decreased for the given collateral and fyDai series, in Yield vault `to`. /// `from` can delegate to other addresses to take fyDai from him for the repayment. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param from Wallet providing the fyDai for repayment. /// @param to Yield vault to repay debt for. /// @param fyDaiAmount Amount of fyDai to use for debt repayment. // // debt_nominal // debt_discounted = debt_nominal - repay_amount * --------------- // debt_now // // user(from) --- fyDai ---> us(to) // debt-- function repayFYDai(bytes32 collateral, uint256 maturity, address from, address to, uint256 fyDaiAmount) public override validCollateral(collateral) validSeries(maturity) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive returns (uint256) { uint256 toRepay = Math.min(fyDaiAmount, debtFYDai[collateral][maturity][to]); series[maturity].burn(from, toRepay); _repay(collateral, maturity, to, toRepay); return toRepay; } /// @dev Burns Dai from `from` wallet to repay debt in a Yield Vault. /// User debt is decreased for the given collateral and fyDai series, in Yield vault `to`. /// The amount of debt repaid changes according to series maturity and MakerDAO rate and chi, depending on collateral type. /// `from` can delegate to other addresses to take Dai from him for the repayment. /// Calling ERC20.approve for Treasury contract is a prerequisite to this function /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param from Wallet providing the Dai for repayment. /// @param to Yield vault to repay debt for. /// @param daiAmount Amount of Dai to use for debt repayment. // // debt_nominal // debt_discounted = debt_nominal - repay_amount * --------------- // debt_now // // user --- dai ---> us // debt-- function repayDai(bytes32 collateral, uint256 maturity, address from, address to, uint256 daiAmount) public override validCollateral(collateral) validSeries(maturity) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive returns (uint256) { uint256 toRepay = Math.min(daiAmount, debtDai(collateral, maturity, to)); treasury.pushDai(from, toRepay); // Have Treasury process the dai _repay(collateral, maturity, to, inFYDai(collateral, maturity, toRepay)); return toRepay; } /// @dev Removes an amount of debt from an user's vault. /// Internal function. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param user Yield vault to repay debt for. /// @param fyDaiAmount Amount of fyDai to use for debt repayment. // // principal // principal_repayment = gross_repayment * ---------------------- // principal + interest // function _repay(bytes32 collateral, uint256 maturity, address user, uint256 fyDaiAmount) internal { debtFYDai[collateral][maturity][user] = debtFYDai[collateral][maturity][user].sub(fyDaiAmount); emit Borrowed(collateral, maturity, user, -toInt256(fyDaiAmount)); } /// @dev Removes all collateral and debt for an user, for a given collateral type. /// This function can only be called by other Yield contracts, not users directly. /// @param collateral Valid collateral type. /// @param user Address of the user vault /// @return The amounts of collateral and debt removed from Controller. function erase(bytes32 collateral, address user) public override validCollateral(collateral) onlyOrchestrated("Controller: Not Authorized") returns (uint256, uint256) { uint256 userCollateral = posted[collateral][user]; delete posted[collateral][user]; uint256 userDebt; uint256[] memory _seriesIterator = seriesIterator; for (uint256 i = 0; i < _seriesIterator.length; i += 1) { uint256 maturity = _seriesIterator[i]; userDebt = userDebt.add(debtDai(collateral, maturity, user)); // SafeMath shouldn't be needed delete debtFYDai[collateral][maturity][user]; } // We don't expect hundreds of maturities per controller return (userCollateral, userDebt); } }
Multiplies x and y, rounding up to the closest representable number. Assumes x and y are both fixed point with `decimals` digits.
function muldrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(y); return z.mod(UNIT) == 0 ? z.div(UNIT) : z.div(UNIT).add(1); }
608,326
/////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2018-2020 Crossbar.io Technologies GmbH and contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////////// pragma solidity ^0.5.12; pragma experimental ABIEncoderV2; // https://openzeppelin.org/api/docs/math_SafeMath.html import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./XBRMaintained.sol"; import "./XBRTypes.sol"; import "./XBRToken.sol"; import "./XBRNetwork.sol"; /// XBR API catalogs contract. contract XBRCatalog is XBRMaintained { // Add safe math functions to uint256 using SafeMath lib from OpenZeppelin using SafeMath for uint256; /// Event emitted when a new catalog was created. event CatalogCreated (bytes16 indexed catalogId, uint256 created, uint32 catalogSeq, address owner, string terms, string meta); /// Event emitted when an API has been published to a catalog. event ApiPublished (bytes16 indexed catalogId, bytes16 apiId, uint256 published, string schema, string meta); /// Instance of XBRNetwork contract this contract is linked to. XBRNetwork public network; /// Created catalogs are sequence numbered using this counter (to allow deterministic collision-free IDs for markets) uint32 private catalogSeq = 1; /// Current XBR Catalogs ("catalog directory") mapping(bytes16 => XBRTypes.Catalog) public catalogs; /// List of IDs of current XBR Catalogs. bytes16[] public catalogIds; // Constructor for this contract, only called once (when deploying the network). // // @param networkAdr The XBR network contract this instance is associated with. constructor (address networkAdr) public { network = XBRNetwork(networkAdr); } /// Create a new XBR catalog. The sender of the transaction must be XBR network member /// and automatically becomes owner of the new catalog. /// /// @param catalogId The ID of the new catalog. /// @param terms Multihash for terms that apply to the catalog and to all APIs as published to this catalog. /// @param meta Multihash for optional catalog meta-data. function createCatalog (bytes16 catalogId, string memory terms, string memory meta) public { _createCatalog(msg.sender, block.number, catalogId, terms, meta, ""); } /// Create a new XBR catalog for a member. The member must be XBR network member, must have signed the /// transaction data, and will become owner of the new catalog. /// /// Note: This version uses pre-signed data where the actual blockchain transaction is /// submitted by a gateway paying the respective gas (in ETH) for the blockchain transaction. /// /// @param member Member that creates the catalog and will become owner. /// @param created Block number when the catalog was created. /// @param catalogId The ID of the new catalog. /// @param terms Multihash for terms that apply to the catalog and to all APIs as published to this catalog. /// @param meta Multihash for optional catalog meta-data. /// @param signature Signature created by the member. function createCatalogFor (address member, uint256 created, bytes16 catalogId, string memory terms, string memory meta, bytes memory signature) public { require(XBRTypes.verify(member, XBRTypes.EIP712CatalogCreate(network.verifyingChain(), network.verifyingContract(), member, created, catalogId, terms, meta), signature), "INVALID_CATALOG_CREATE_SIGNATURE"); // signature must have been created in a window of 5 blocks from the current one require(created <= block.number && created >= (block.number - 4), "INVALID_CATALOG_CREATE_BLOCK_NUMBER"); _createCatalog(member, created, catalogId, terms, meta, signature); } function _createCatalog (address member, uint256 created, bytes16 catalogId, string memory terms, string memory meta, bytes memory signature) private { (, , , XBRTypes.MemberLevel member_level, ) = network.members(member); // the catalog owner must be a registered member require(member_level == XBRTypes.MemberLevel.ACTIVE || member_level == XBRTypes.MemberLevel.VERIFIED, "SENDER_NOT_A_MEMBER"); // catalogs must not yet exist require(catalogs[catalogId].owner == address(0), "CATALOG_ALREADY_EXISTS"); // store new catalog object catalogs[catalogId] = XBRTypes.Catalog(created, catalogSeq, member, terms, meta, signature); // add catalogId to list of all catalog IDs catalogIds.push(catalogId); // increment catalog sequence for next catalog catalogSeq = catalogSeq + 1; // notify observers of new catalogs emit CatalogCreated(catalogId, created, catalogSeq, member, terms, meta); } /// Publish the given API to the specified catalog. /// /// @param catalogId The ID of the XBR API catalog to publish the API to. /// @param apiId The ID of the new API (must be unique). /// @param schema Multihash of API Flatbuffers schema (required). /// @param meta Multihash for optional meta-data. function publishApi (bytes16 catalogId, bytes16 apiId, string memory schema, string memory meta) public { _publishApi(msg.sender, block.number, catalogId, apiId, schema, meta, ""); } /// Publish the given API to the specified catalog. /// /// Note: This version uses pre-signed data where the actual blockchain transaction is /// submitted by a gateway paying the respective gas (in ETH) for the blockchain transaction. /// /// @param member Member that is publishing the API. /// @param published Block number when the API was published. /// @param catalogId The ID of the XBR API catalog to publish the API to. /// @param apiId The ID of the new API (must be unique). /// @param schema Multihash of API Flatbuffers schema (required). /// @param meta Multihash for optional meta-data. /// @param signature Signature created by the member. function publishApiFor (address member, uint256 published, bytes16 catalogId, bytes16 apiId, string memory schema, string memory meta, bytes memory signature) public { require(XBRTypes.verify(member, XBRTypes.EIP712ApiPublish(network.verifyingChain(), network.verifyingContract(), member, published, catalogId, apiId, schema, meta), signature), "INVALID_API_PUBLISH_SIGNATURE"); // signature must have been created in a window of 5 blocks from the current one require(published <= block.number && published >= (block.number - 4), "INVALID_API_PUBLISH_BLOCK_NUMBER"); _publishApi(member, published, catalogId, apiId, schema, meta, signature); } function _publishApi (address member, uint256 published, bytes16 catalogId, bytes16 apiId, string memory schema, string memory meta, bytes memory signature) private { (, , , XBRTypes.MemberLevel member_level, ) = network.members(member); // the publishing user must be a registered member require(member_level == XBRTypes.MemberLevel.ACTIVE, "SENDER_NOT_A_MEMBER"); // the catalog to publish to must exist require(catalogs[catalogId].owner != address(0), "NO_SUCH_CATALOG"); // the publishing member must be owner of the catalog require(catalogs[catalogId].owner == member, "SENDER_IS_NOT_OWNER"); // the API, identified by the ID, must not yet exist require(catalogs[catalogId].apis[apiId].published == 0, "API_ALREADY_EXISTS"); // add API to API-map of catalog catalogs[catalogId].apis[apiId] = XBRTypes.Api(published, schema, meta, signature); } }
Publish the given API to the specified catalog. catalogId The ID of the XBR API catalog to publish the API to. apiId The ID of the new API (must be unique). schema Multihash of API Flatbuffers schema (required). meta Multihash for optional meta-data.
function publishApi (bytes16 catalogId, bytes16 apiId, string memory schema, string memory meta) public { _publishApi(msg.sender, block.number, catalogId, apiId, schema, meta, ""); }
12,668,655
./partial_match/4/0xD978E2881C07813A010Ed1403F3b1ADAc72545D1/sources/Exchange.sol
Returns In Tokens balance/
function getInTokenBalance() external view returns (uint256) { return inToken.balanceOf(address(this)); }
8,716,063
./full_match/4/0xa7b92AC2f431E9BDa86AA34bfaECC24ccf3d5468/sources/BancorNetwork.sol
returns the conversion path between two tokens in the network note that this method is quite expensive in terms of gas and should generally be called off-chain _sourceToken source token address _targetToken target token address return conversion path between the two tokens/
function conversionPath(IERC20Token _sourceToken, IERC20Token _targetToken) public view returns (address[] memory) { IConversionPathFinder pathFinder = IConversionPathFinder(addressOf(CONVERSION_PATH_FINDER)); return pathFinder.findPath(_sourceToken, _targetToken); }
666,165
pragma solidity ^0.4.21; import "@gnosis.pm/util-contracts/contracts/Token.sol"; import "@gnosis.pm/dx-contracts/contracts/DutchExchange.sol"; import "@gnosis.pm/dx-contracts/contracts/Oracle/PriceOracleInterface.sol"; contract BuyBack { address public owner; // SellToken the token that is sold address public sellToken; address public buyToken; address public burnAddress; // mapping of the sell token to mapping (address => uint) public balances; // mapping (address => uint) public // This is a mapping of auction id to amount uint[] auctionIndexes; mapping(uint => uint) public auction; // mapping of a auction id to wether // we currently participating in an auction for // the auction id mapping(uint => bool) public isProcessing; // BuyToken the token that is bought DutchExchange public dx; bool shouldBurnToken; modifier onlyOwner () { require(msg.sender == owner); _; } event Withdraw( address indexed sellToken, address indexed buyToken, uint balance, uint auctionIndex ); event Deposit( address indexed tokenAddress, uint amount ); event ModifyAuction( uint auctionIndex, uint amount ); event ModifyBurnAddress( address burnAddress ); event ModifySellToken( address newSellToken ); event Burn ( address indexed tokenAddress, address burnAddress, uint amount ); event DeleteAuction( uint auctionIndex, uint amount ); /** * @notice Buyback * @param _buyToken Address of the security token * @param _sellToken Address of the polytoken * @param _burn Should burn the token after buy back success * @param _auctionIndexes Auction index the to participate * @param _auctionAmounts Auction amount to fill in auction index */ function BuyBack( address _dx, address _buyToken, address _sellToken, address _burnAddress, bool _burn, uint[] _auctionIndexes, uint[] _auctionAmounts ) public { require(address(_dx) != address(0)); require(address(_buyToken) != address(0)); require(address(_sellToken) != address(0)); require(_auctionIndexes.length == _auctionAmounts.length); dx = DutchExchange(_dx); sellToken = _sellToken; buyToken = _buyToken; shouldBurnToken = _burn; auctionIndexes = _auctionIndexes; owner = msg.sender; burnAddress = _burnAddress; // map the auction ids to the auction amount for(uint i = 0; i < _auctionIndexes.length; i++){ require(_auctionAmounts[i] > 0); auction[_auctionIndexes[i]] = _auctionAmounts[i]; } } /** * @notice modifyAuctionsMulti modify the amount for multiple auction index * @param _auctionIndexes Auction index the to participate * @param _auctionAmounts Auction amount to fill in auction index */ function modifyAuctionsMulti(uint[] _auctionIndexes, uint[] _auctionAmounts) external onlyOwner { require(_auctionIndexes.length > 0); require(_auctionIndexes.length == _auctionAmounts.length); for(uint i = 0; i < _auctionIndexes.length; i++){ modifyAuction(_auctionIndexes[i], _auctionAmounts[i]); } } function modifySellToken(address _sellToken) public onlyOwner{ require(address(_sellToken) != address(0)); sellToken = _sellToken; emit ModifySellToken(sellToken); } /** * @notice getAuctions fetch all the available auctions */ function getAuctionIndexes() public view returns (uint[]){ return auctionIndexes; } /** * @notice getAuctionAmount amount to pariticipate in an auction index * @param _auctionIndex Auction index */ function getAuctionAmount(uint _auctionIndex) public view returns( uint ) { return auction[_auctionIndex]; } /** * @notice modifyAuctions modify the amount for an auction index * @param _auctionIndex Auction index the to participate * @param _auctionAmount Auction amount to fill in auction index */ function modifyAuction(uint _auctionIndex, uint _auctionAmount) public onlyOwner { require(_auctionAmount > 0); auction[_auctionIndex] = _auctionAmount; emit ModifyAuction(_auctionIndex, _auctionAmount); } /** * @notice deleteAuction * @param _index Auction index the to participate */ function deleteAuction(uint _index) public onlyOwner { require(_index < auctionIndexes.length); uint auctionIndex = auctionIndexes[_index]; require(isProcessing[auctionIndex] == false); if(auctionIndexes.length == 1){ delete auctionIndexes[0]; } else { for (uint i = _index; i < auctionIndexes.length-1; i++){ auctionIndexes[i] = auctionIndexes[i+1]; } auctionIndexes.length--; } uint amount = auction[auctionIndex]; delete auction[auctionIndex]; emit DeleteAuction(auctionIndex, amount); } /** * @notice deleteAuctions delete an Auction * @param _indexes indexes of the auction in array */ function deleteAuctionMulti(uint[] _indexes) public onlyOwner { require(_indexes.length > 0); for(uint i = 0; i < _indexes.length; i++) { deleteAuction(_indexes[i]); } } /** * @notice modifyBurn should burn the bought tokens * @param _burn to either burn or not burn i.e. True or false */ function modifyBurn(bool _burn) public onlyOwner returns(bool) { shouldBurnToken = _burn; } /** * @notice getBurnAddress */ function getBurnAddress() public view onlyOwner returns(address) { return burnAddress; } /** * @notice modifyBurnAddress modify address burnt tokens should be sent to * @param _burnAddress burn address */ function modifyBurnAddress(address _burnAddress) public onlyOwner { burnAddress = _burnAddress; emit ModifyBurnAddress(_burnAddress); } function updateDutchExchange(DutchExchange _dx) external onlyOwner { dx = _dx; } /** * @notice deposit * @param _token Address of the deposited token * @param _amount Amount of tokens deposited 10^18 */ function deposit(address _token, uint _amount) public onlyOwner returns (uint) { require(_amount > 0); require(_token == sellToken); require(Token(_token).transferFrom(msg.sender, this, _amount)); balances[_token] += _amount; emit Deposit(_token, _amount); return _amount; } /** * @notice approve dutchx contract */ function approveDutchX(uint amount) internal { require(Token(sellToken).approve(dx, amount)); } /** *@notice depsoit to dutchx contract */ function depositDutchx(uint amount) internal { uint balance = dx.deposit(sellToken, amount); require(balance >= amount); } /** * @notice approve trading */ function postOrder() public { // approve the dx proxy contract to trade on my behalf // _sellToken for( uint i = 0; i < auctionIndexes.length; i++ ) { uint amount = auction[auctionIndexes[i]]; approveDutchX(amount); depositDutchx(amount); dx.postSellOrder(sellToken, buyToken, auctionIndexes[i], amount); } } /** * @notice approve trading */ function claim() public { uint balance; for(uint i = 0; i < auctionIndexes.length; i++) { (balance, ) = dx.claimSellerFunds(sellToken, buyToken, this, auctionIndexes[i]); if(shouldBurnToken == true){ if( burnAddress != address(0) ){ burnTokensWithAddress(buyToken, burnAddress, balance); } burnTokens(buyToken, balance); } emit Withdraw(sellToken, buyToken, balance, auctionIndexes[i]); } } /** * @notice burnTokens * @param _token Address of the token * @param _amount Amount of tokens to burn */ function burnTokens(address _token, uint _amount) internal { // transfer the tokens to address(0) require(_amount > 0); require(Token(_token).transferFrom(this, address(0), _amount)); emit Burn( _token, address(0), _amount ); } /** * @notice burnTokensWithAddress * @param _token Address of the token * @param _burnAddress Address to send burn tokens * @param _amount Amount of tokens to burn */ function burnTokensWithAddress(address _token, address _burnAddress, uint _amount) internal { // transfer the tokens to address(0) require(_amount > 0); require(Token(_token).transferFrom(this, _burnAddress, _amount)); emit Burn( _token, _burnAddress, _amount ); } }
approve dutchx contract/
function approveDutchX(uint amount) internal { require(Token(sellToken).approve(dx, amount)); }
5,377,993
./full_match/11155111/0x35DDeC871aF3D7A51b691D39ACe0511EDd2ed963/sources/project_/contracts/BridgeBase.sol
Ensure that the length of the signature is 65 bytes Declare variables to hold the values of r, s, and v in the signature Extract the values of r, s, and v from the signature
function splitSignature(bytes memory sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } }
3,841,393
./full_match/5/0xf738870a8063a060f59E3754C89039663bA1b027/sources/contracts/messagePassingBridge/MessagePassingBridge.sol
we override the callback that is triggered when a message is received sourceChainId the source chain sourceAddress the source contract from sender to recipient normalizedAmount amount in 18 decimals requestId request id/
) internal virtual override { uint256 chainId = _fromAxelarChainId(sourceChainId); function _axelarBridgeFrom( string memory sourceChainId, address sourceAddress, address from, address to, uint256 normalizedAmount, uint256 requestId if (sourceAddress != address(this)) { emit FalseSender(chainId, sourceAddress); return; } _bridgeFrom(from, to, normalizedAmount, chainId, requestId, BridgeService.AXELAR); }
1,858,655
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import './bases/staking/StakingRewards.sol'; import './bases/BaseTokenUpgradeable.sol'; import './bases/staking/interfaces/IOriginatorStaking.sol'; import '../reserve/IReserve.sol'; import '../utils/SafeMathUint128.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; /** * @title OriginatorStaking * @notice Contract to stake Originator Hub tokens, tokenize the position and get rewards, inheriting from a distribution manager contract * @author Aave / Ethichub **/ contract OriginatorStaking is Initializable, StakingRewards, BaseTokenUpgradeable, IStaking, IProjectFundedRewards, IOriginatorManager { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; using SafeMathUint128 for uint128; enum OriginatorStakingState { UNINITIALIZED, STAKING, STAKING_END, DEFAULT } OriginatorStakingState public state; IERC20Upgradeable public STAKED_TOKEN; /// @notice IReserve to pull from the rewards, needs to have this contract as WITHDRAW role IReserve public REWARDS_VAULT; bytes32 public constant GOVERNANCE_ROLE = keccak256('GOVERNANCE_ROLE'); uint256 public stakingGoal; uint256 public defaultedAmount; mapping(address => uint256) public stakerRewardsToClaim; bytes32 public constant ORIGINATOR_ROLE = keccak256('ORIGINATOR_ROLE'); bytes32 public constant AUDITOR_ROLE = keccak256('AUDITOR_ROLE'); uint256 public DEFAULT_DATE; mapping(bytes32 => uint256) public proposerBalances; event StateChange(uint256 state); event Staked(address indexed from, address indexed onBehalfOf, uint256 amount); event Redeem(address indexed from, address indexed to, uint256 amount); event Withdraw(address indexed proposer, uint256 amount); event RewardsAccrued(address user, uint256 amount); event RewardsClaimed(address indexed from, address indexed to, uint256 amount); event StartRewardsProjectFunded(uint128 previousEmissionPerSecond, uint128 extraEmissionsPerSecond, address lendingContractAddress); event EndRewardsProjectFunded(uint128 restoredEmissionsPerSecond, uint128 extraEmissionsPerSecond, address lendingContractAddress); modifier onlyGovernance() { require(hasRole(GOVERNANCE_ROLE, msg.sender), 'ONLY_GOVERNANCE'); _; } modifier onlyEmissionManager() { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); _; } modifier onlyOnStakingState() { require(state == OriginatorStakingState.STAKING, 'ONLY_ON_STAKING_STATE'); _; } modifier notZeroAmount(uint256 _amount) { require(_amount > 0, 'INVALID_ZERO_AMOUNT'); _; } function initialize( string memory _name, string memory _symbol, IERC20Upgradeable _lockedToken, IReserve _rewardsVault, address _emissionManager, uint128 _distributionDuration ) public initializer { __BaseTokenUpgradeable_init( msg.sender, 0, _name, _symbol, _name ); __StakingRewards_init(_emissionManager, _distributionDuration); STAKED_TOKEN = _lockedToken; REWARDS_VAULT = _rewardsVault; _changeState(OriginatorStakingState.UNINITIALIZED); } /** * @notice Function to set up proposers (originator and auditor) * in proposal period. * @param _auditor address * @param _originator address * @param _auditorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _originatorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _stakingGoal uint256 wei amount in Ethix * @param _defaultDelay uint256 seconds */ function setUpTerms( address _auditor, address _originator, address _governance, uint256 _auditorPercentage, uint256 _originatorPercentage, uint256 _stakingGoal, uint256 _defaultDelay ) external override notZeroAmount(_stakingGoal) onlyEmissionManager { require(_auditor != _originator, 'PROPOSERS_CANNOT_BE_THE_SAME'); require(_auditorPercentage != 0 && _originatorPercentage != 0, 'INVALID_PERCENTAGE_ZERO'); require(state == OriginatorStakingState.UNINITIALIZED, 'ONLY_ON_UNINITILIZED_STATE'); _setupRole(AUDITOR_ROLE, _auditor); _setupRole(ORIGINATOR_ROLE, _originator); _setupRole(GOVERNANCE_ROLE, _governance); _depositProposer(_auditor, _auditorPercentage, _stakingGoal); _depositProposer(_originator, _originatorPercentage, _stakingGoal); stakingGoal = _stakingGoal; DEFAULT_DATE = _defaultDelay.add(DISTRIBUTION_END); _changeState(OriginatorStakingState.STAKING); } /** * @notice Function to renew terms in STAKING_END or DEFAULT period. * @param _newAuditorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _newOriginatorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _newStakingGoal uint256 wei amount in Ethix * @param _newDistributionDuration uint128 seconds (e.g. 365 days == 31536000) * @param _newDefaultDelay uint256 seconds (e.g 90 days == 7776000) */ function renewTerms( uint256 _newAuditorPercentage, uint256 _newOriginatorPercentage, uint256 _newStakingGoal, uint128 _newDistributionDuration, uint256 _newDefaultDelay) external override notZeroAmount(_newStakingGoal) onlyGovernance { require(state == OriginatorStakingState.STAKING_END || state == OriginatorStakingState.DEFAULT, 'INVALID_STATE'); DISTRIBUTION_END = block.timestamp.add(_newDistributionDuration); _depositProposer(getRoleMember(AUDITOR_ROLE, 0), _newAuditorPercentage, _newStakingGoal); _depositProposer(getRoleMember(ORIGINATOR_ROLE, 0), _newOriginatorPercentage, _newStakingGoal); stakingGoal = _newStakingGoal; DEFAULT_DATE = _newDefaultDelay.add(DISTRIBUTION_END); _changeState(OriginatorStakingState.STAKING); } /** * @notice Function to stake tokens * @param _onBehalfOf Address to stake to * @param _amount Amount to stake **/ function stake(address _onBehalfOf, uint256 _amount) external override notZeroAmount(_amount) onlyOnStakingState { require(!hasReachedGoal(), 'GOAL_HAS_REACHED'); if (STAKED_TOKEN.balanceOf(address(this)).add(_amount) > stakingGoal) { _amount = stakingGoal.sub(STAKED_TOKEN.balanceOf(address(this))); } uint256 balanceOfUser = balanceOf(_onBehalfOf); uint256 accruedRewards = _updateUserAssetInternal(_onBehalfOf, address(this), balanceOfUser, totalSupply()); if (accruedRewards != 0) { emit RewardsAccrued(_onBehalfOf, accruedRewards); stakerRewardsToClaim[_onBehalfOf] = stakerRewardsToClaim[_onBehalfOf].add(accruedRewards); } _mint(_onBehalfOf, _amount); IERC20Upgradeable(STAKED_TOKEN).safeTransferFrom(msg.sender, address(this), _amount); emit Staked(msg.sender, _onBehalfOf, _amount); } /** * @dev Redeems staked tokens, and stop earning rewards * @param _to Address to redeem to * @param _amount Amount to redeem **/ function redeem(address _to, uint256 _amount) external override notZeroAmount(_amount) { require(_checkRedeemEligibilityState(), 'WRONG_STATE'); require(balanceOf(msg.sender) != 0, 'SENDER_BALANCE_ZERO'); uint256 balanceOfMessageSender = balanceOf(msg.sender); uint256 amountToRedeem = (_amount > balanceOfMessageSender) ? balanceOfMessageSender : _amount; _updateCurrentUnclaimedRewards(msg.sender, balanceOfMessageSender, true); _burn(msg.sender, amountToRedeem); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(_to, amountToRedeem); emit Redeem(msg.sender, _to, amountToRedeem); } /** * @notice method to withdraw deposited amount. * @param _amount Amount to withdraw */ function withdrawProposerStake(uint256 _amount) external override { require(state == OriginatorStakingState.STAKING_END, 'ONLY_ON_STAKING_END_STATE'); bytes32 senderRole = 0x00; if (msg.sender == getRoleMember(ORIGINATOR_ROLE, 0)) { senderRole = ORIGINATOR_ROLE; } else if (msg.sender == getRoleMember(AUDITOR_ROLE, 0)) { senderRole = AUDITOR_ROLE; } else { revert('WITHDRAW_PERMISSION_DENIED'); } require(proposerBalances[senderRole] != 0, 'INVALID_ZERO_AMOUNT'); uint256 amountToWithdraw = (_amount > proposerBalances[senderRole]) ? proposerBalances[senderRole] : _amount; proposerBalances[senderRole] = proposerBalances[senderRole].sub(amountToWithdraw); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, amountToWithdraw); } /** * @dev Claims an `amount` from Rewards reserve to the address `to` * @param _to Address to stake for * @param _amount Amount to stake **/ function claimRewards(address payable _to, uint256 _amount) external override { uint256 newTotalRewards = _updateCurrentUnclaimedRewards(msg.sender, balanceOf(msg.sender), false); uint256 amountToClaim = (_amount == type(uint256).max) ? newTotalRewards : _amount; stakerRewardsToClaim[msg.sender] = newTotalRewards.sub(amountToClaim, 'INVALID_AMOUNT'); require(REWARDS_VAULT.transfer(_to, amountToClaim), 'ERROR_TRANSFER_FROM_VAULT'); emit RewardsClaimed(msg.sender, _to, amountToClaim); } /** * Function to add an extra emissions per second corresponding to staker rewards when a lending project by this originator * is funded. * @param _extraEmissionsPerSecond emissions per second to be added to current ones. * @param _lendingContractAddress lending contract address is relationated with this rewards */ function startProjectFundedRewards(uint128 _extraEmissionsPerSecond, address _lendingContractAddress) external override onlyOnStakingState { AssetData storage currentDistribution = assets[address(this)]; uint128 currentEmission = currentDistribution.emissionPerSecond; uint128 newEmissionsPerSecond = currentDistribution.emissionPerSecond.add(_extraEmissionsPerSecond); DistributionTypes.AssetConfigInput[] memory newAssetConfig = new DistributionTypes.AssetConfigInput[](1); newAssetConfig[0] = DistributionTypes.AssetConfigInput({ emissionPerSecond: newEmissionsPerSecond, totalStaked: totalSupply(), underlyingAsset: address(this) }); configureAssets(newAssetConfig); emit StartRewardsProjectFunded(currentEmission, _extraEmissionsPerSecond, _lendingContractAddress); } /** * Function to end extra emissions per second corresponding to staker rewards when a lending project by this originator * is funded. * @param _extraEmissionsPerSecond emissions per second to be added to current ones. * @param _lendingContractAddress lending contract address is relationated with this rewards. */ function endProjectFundedRewards(uint128 _extraEmissionsPerSecond, address _lendingContractAddress) external override onlyOnStakingState { AssetData storage currentDistribution = assets[address(this)]; uint128 currentEmission = currentDistribution.emissionPerSecond; uint128 newEmissionsPerSecond = currentDistribution.emissionPerSecond.sub(_extraEmissionsPerSecond); DistributionTypes.AssetConfigInput[] memory newAssetConfig = new DistributionTypes.AssetConfigInput[](1); newAssetConfig[0] = DistributionTypes.AssetConfigInput({ emissionPerSecond: newEmissionsPerSecond, totalStaked: totalSupply(), underlyingAsset: address(this) }); configureAssets(newAssetConfig); emit EndRewardsProjectFunded(currentEmission, _extraEmissionsPerSecond, _lendingContractAddress); } /** * @notice Amount to substract of the contract when state is default * @param _amount amount to substract * @param _role role to substract the amount (Originator, Auditor) */ function liquidateProposerStake(uint256 _amount, bytes32 _role) external override notZeroAmount(_amount) onlyGovernance { require(state == OriginatorStakingState.DEFAULT, 'ONLY_ON_DEFAULT'); require(_role == AUDITOR_ROLE || _role == ORIGINATOR_ROLE, 'INVALID_PROPOSER_ROLE'); proposerBalances[_role] = proposerBalances[_role].sub(_amount, 'INVALID_LIQUIDATE_AMOUNT'); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(msg.sender, _amount); } /** * @notice Function to declare contract on staking end state * Only governance could change to this state **/ function declareStakingEnd() external override onlyGovernance onlyOnStakingState { _endDistributionIfNeeded(); _changeState(OriginatorStakingState.STAKING_END); } /** * @notice Function to declare as DEFAULT * @param _defaultedAmount uint256 **/ function declareDefault(uint256 _defaultedAmount) external override onlyGovernance onlyOnStakingState { require(block.timestamp >= DEFAULT_DATE, 'DEFAULT_DATE_NOT_REACHED'); defaultedAmount = _defaultedAmount; _endDistributionIfNeeded(); _changeState(OriginatorStakingState.DEFAULT); } /** * @dev Return the total rewards pending to claim by an staker * @param _staker The staker address * @return The rewards */ function getTotalRewardsBalance(address _staker) external override view returns (uint256) { DistributionTypes.UserStakeInput[] memory userStakeInputs = new DistributionTypes.UserStakeInput[](1); userStakeInputs[0] = DistributionTypes.UserStakeInput({ underlyingAsset: address(this), stakedByUser: balanceOf(_staker), totalStaked: totalSupply() }); return stakerRewardsToClaim[_staker].add(_getUnclaimedRewards(_staker, userStakeInputs)); } /** * @notice Check if fulfilled the objective (Only valid on STAKING state!!) */ function hasReachedGoal() public override notZeroAmount(stakingGoal) view returns (bool) { if (proposerBalances[ORIGINATOR_ROLE].add(proposerBalances[AUDITOR_ROLE]).add(totalSupply()) >= stakingGoal) { return true; } return false; } /** * @notice Function to transfer participation amount (originator or auditor) */ function _depositProposer(address _proposer, uint256 _percentage, uint256 _goalAmount) internal { uint256 percentageAmount = _calculatePercentage(_goalAmount, _percentage); uint256 depositAmount = 0; if (_proposer == getRoleMember(ORIGINATOR_ROLE, 0)) { depositAmount = _calculateDepositAmount(ORIGINATOR_ROLE, percentageAmount); proposerBalances[ORIGINATOR_ROLE] = proposerBalances[ORIGINATOR_ROLE].add(depositAmount); } else if (_proposer == getRoleMember(AUDITOR_ROLE, 0)) { depositAmount = _calculateDepositAmount(AUDITOR_ROLE, percentageAmount); proposerBalances[AUDITOR_ROLE] = proposerBalances[AUDITOR_ROLE].add(depositAmount); } IERC20Upgradeable(STAKED_TOKEN).safeTransferFrom(_proposer, address(this), depositAmount); } /** * @dev Internal ERC20 _transfer of the tokenized staked tokens * @param _from Address to transfer from * @param _to Address to transfer to * @param _amount Amount to transfer **/ function _transfer( address _from, address _to, uint256 _amount ) internal override { uint256 balanceOfFrom = balanceOf(_from); // Sender _updateCurrentUnclaimedRewards(_from, balanceOfFrom, true); // Recipient if (_from != _to) { uint256 balanceOfTo = balanceOf(_to); _updateCurrentUnclaimedRewards(_to, balanceOfTo, true); } super._transfer(_from, _to, _amount); } /** * @dev Check if the state of contract is suitable to redeem */ function _checkRedeemEligibilityState() internal view returns (bool) { if (state == OriginatorStakingState.STAKING_END) { return true; } else if (state == OriginatorStakingState.DEFAULT && defaultedAmount <= proposerBalances[ORIGINATOR_ROLE].add(proposerBalances[AUDITOR_ROLE])) { return true; } else { return false; } } /** * @dev Updates the user state related with his accrued rewards * @param _user Address of the user * @param _userBalance The current balance of the user * @param _updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user * @return The unclaimed rewards that were added to the total accrued **/ function _updateCurrentUnclaimedRewards( address _user, uint256 _userBalance, bool _updateStorage ) internal returns (uint256) { uint256 accruedRewards = _updateUserAssetInternal(_user, address(this), _userBalance, totalSupply()); uint256 unclaimedRewards = stakerRewardsToClaim[_user].add(accruedRewards); if (accruedRewards != 0) { if (_updateStorage) { stakerRewardsToClaim[_user] = unclaimedRewards; } emit RewardsAccrued(_user, accruedRewards); } return unclaimedRewards; } /** * @notice Function to calculate a percentage of an amount * @param _amount Amount to calculate the percentage of * @param _percentage Percentage to calculate of this amount * @return (amount) */ function _calculatePercentage(uint256 _amount, uint256 _percentage) internal pure returns (uint256) { return uint256(_amount.mul(_percentage).div(10000)); } /** * @notice Function to get the actual participation amount * of proposers according the amount that already exists in the contract * @param _role Auditor or originator role * @param _percentageAmount Percentage of staking goal amount * Note _percentageAmount SHOULD BE GREATER than the previously existing amount */ function _calculateDepositAmount(bytes32 _role, uint256 _percentageAmount) internal view returns (uint256){ return uint256(_percentageAmount.sub(proposerBalances[_role])); } /** * @notice Function to change contract state * @param _newState New contract state **/ function _changeState(OriginatorStakingState _newState) internal { state = _newState; emit StateChange(uint256(_newState)); } /** * @notice Function to change DISTRIBUTION_END if timestamp is less than the initial one **/ function _endDistributionIfNeeded() internal { if (block.timestamp <= DISTRIBUTION_END) { _changeDistributionEndDate(block.timestamp); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import './lib/DistributionTypes.sol'; import './interfaces/IStakingRewards.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '../../../utils/SafeMathUint128.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; /** * @title StakingRewards * @notice Accounting contract to manage multiple staking distributions * @author Aave / Ethichub **/ contract StakingRewards is Initializable, IStakingRewards, AccessControlUpgradeable { bytes32 public constant EMISSION_MANAGER_ROLE = keccak256('EMISSION_MANAGER'); using SafeMathUpgradeable for uint256; using SafeMathUint128 for uint128; struct AssetData { uint128 emissionPerSecond; uint128 lastUpdateTimestamp; uint256 index; mapping(address => uint256) users; } uint256 public DISTRIBUTION_END; uint8 constant public PRECISION = 18; mapping(address => AssetData) public assets; event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); event DistributionEndChanged(uint256 distributionEnd); function __StakingRewards_init(address emissionManager, uint256 distributionDuration) public initializer { __AccessControl_init_unchained(); DISTRIBUTION_END = block.timestamp.add(distributionDuration); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(EMISSION_MANAGER_ROLE, emissionManager); } /** * @dev Configures the distribution of rewards for a list of assets * @param assetsConfigInput The list of configurations to apply **/ function configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) public override { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset]; _updateAssetStateInternal( assetsConfigInput[i].underlyingAsset, assetConfig, assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond; emit AssetConfigUpdated( assetsConfigInput[i].underlyingAsset, assetsConfigInput[i].emissionPerSecond ); } } /** * @notice Change distribution end datetime * @param _distributionEndDate new distribution end datetime (UNIX Timestamp) */ function changeDistributionEndDate(uint256 _distributionEndDate) public override { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); return _changeDistributionEndDate(_distributionEndDate); } /** * @notice Change distribution end datetime internal function * @param _distributionEndDate new distribution end datetime (UNIX Timestamp) */ function _changeDistributionEndDate(uint256 _distributionEndDate) internal { DISTRIBUTION_END = _distributionEndDate; emit DistributionEndChanged(DISTRIBUTION_END); } /** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param underlyingAsset The address used as key in the distribution * @param assetConfig Storage pointer to the distribution's config * @param totalStaked Current total of staked assets for this distribution * @return The new distribution index **/ function _updateAssetStateInternal( address underlyingAsset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex( oldIndex, assetConfig.emissionPerSecond, lastUpdateTimestamp, totalStaked ); if (newIndex != oldIndex) { assetConfig.index = newIndex; emit AssetIndexUpdated(underlyingAsset, newIndex); } assetConfig.lastUpdateTimestamp = uint128(block.timestamp); return newIndex; } /** * @dev Updates the state of an user in a distribution * @param user The user's address * @param asset The address of the reference asset of the distribution * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param totalStaked Total tokens staked in the distribution * @return The accrued rewards for the user until the moment **/ function _updateUserAssetInternal( address user, address asset, uint256 stakedByUser, uint256 totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[asset]; uint256 userIndex = assetData.users[user]; uint256 accruedRewards = 0; uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked); if (userIndex != newIndex) { if (stakedByUser != 0) { accruedRewards = _getRewards(stakedByUser, newIndex, userIndex); } assetData.users[user] = newIndex; emit UserIndexUpdated(user, asset, newIndex); } return accruedRewards; } /** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _claimRewards(address payable user, DistributionTypes.UserStakeInput[] memory stakes) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( user, stakes[i].underlyingAsset, stakes[i].stakedByUser, stakes[i].totalStaked ) ); } return accruedRewards; } /** * @dev Return the accrued rewards for an user over a list of distribution * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { AssetData storage assetConfig = assets[stakes[i].underlyingAsset]; uint256 assetIndex = _getAssetIndex( assetConfig.index, assetConfig.emissionPerSecond, assetConfig.lastUpdateTimestamp, stakes[i].totalStaked ); accruedRewards = accruedRewards.add( _getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user]) ); } return accruedRewards; } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param principalUserBalance Amount staked by the user on a distribution * @param reserveIndex Current index of the distribution * @param userIndex Index stored for the user, representation his staking moment * @return The rewards **/ function _getRewards( uint256 principalUserBalance, uint256 reserveIndex, uint256 userIndex ) internal view returns (uint256) { return principalUserBalance.mul(reserveIndex.sub(userIndex)).div(10**uint256(PRECISION)); } /** * @dev Calculates the next value of an specific distribution index, with validations * @param currentIndex Current index of the distribution * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param lastUpdateTimestamp Last moment this distribution was updated * @param totalBalance of tokens considered for the distribution * @return The new index. **/ function _getAssetIndex( uint256 currentIndex, uint256 emissionPerSecond, uint128 lastUpdateTimestamp, uint256 totalBalance ) internal view returns (uint256) { if ( emissionPerSecond == 0 || totalBalance == 0 || lastUpdateTimestamp == block.timestamp || lastUpdateTimestamp >= DISTRIBUTION_END ) { return currentIndex; } uint256 currentTimestamp = block.timestamp > DISTRIBUTION_END ? DISTRIBUTION_END : block.timestamp; uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp); return emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add( currentIndex ); } /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) public view returns (uint256) { return assets[asset].users[user]; } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import '../ERCs/ERC677/ERC677Upgradeable.sol'; import '../ERCs/ERC2612/ERC2612Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import 'hardhat/console.sol'; contract BaseTokenUpgradeable is Initializable, ERC677Upgradeable, ERC2612Upgradeable { function __BaseTokenUpgradeable_init( address _initialAccount, uint256 _initialBalance, string memory _name, string memory _symbol, string memory _EIP712Name ) public initializer { __ERC677_init(_initialAccount, _initialBalance, _name, _symbol); __ERC2612_init(_EIP712Name); } function permit( address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, uint8 _v, bytes32 _r, bytes32 _s ) public override { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256( abi.encode(PERMIT_TYPEHASH, _holder, _spender, _nonce, _expiry, _allowed) ) ) ); require(_holder != address(0), 'Token: invalid-address-0'); require(_holder == ecrecover(digest, _v, _r, _s), 'Token: invalid-permit'); require(_expiry == 0 || block.timestamp <= _expiry, 'Token: permit-expired'); require(_nonce == nonces[_holder]++, 'Token: invalid-nonce'); uint256 _amount = _allowed ? 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff : 0; _approve(_holder, _spender, _amount); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface IOriginatorManager { function setUpTerms( address auditor, address originator, address governance, uint256 auditorPercentage, uint256 originatorPercentage, uint256 stakingGoal, uint256 defaultDelay ) external; function renewTerms( uint256 newAuditorPercentage, uint256 newOriginatorPercentage, uint256 newStakingGoal, uint128 newDistributionDuration, uint256 newDefaultDelay ) external; function declareDefault(uint256 defaultedAmount) external; function liquidateProposerStake(uint256 amount, bytes32 role) external; function declareStakingEnd() external; function hasReachedGoal() external view returns (bool); } interface IProjectFundedRewards { function startProjectFundedRewards(uint128 extraEmissionsPerSecond, address lendingContractAddress) external; function endProjectFundedRewards(uint128 extraEmissionsPerSecond, address lendingContractAddress) external; } interface IStaking { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function claimRewards(address payable to, uint256 amount) external; function withdrawProposerStake(uint256 amount) external; function getTotalRewardsBalance(address staker) external view returns (uint256); } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IReserve { event Transfer(address indexed to, uint256 amount); event RescueFunds(address token, address indexed to, uint256 amount); function balance() external view returns (uint256); function transfer(address payable _to, uint256 _value) external returns (bool); function rescueFunds( address _tokenToRescue, address _to, uint256 _amount ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUint128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // 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 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) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _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 !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; library DistributionTypes { struct AssetConfigInput { uint128 emissionPerSecond; uint256 totalStaked; address underlyingAsset; } struct UserStakeInput { address underlyingAsset; uint256 stakedByUser; uint256 totalStaked; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import '../lib/DistributionTypes.sol'; interface IStakingRewards { function changeDistributionEndDate(uint256 date) external; function configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.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()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // 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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import './IERC677.sol'; import './IERC677Receiver.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; contract ERC677Upgradeable is Initializable, IERC677, ERC20Upgradeable { /** * @dev Sets the values for {_name} and {_symbol}, initializes {_decimals} with * a default value of 18. And mints {_initialBalance} to address {_initialAccount} * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC677_init( address _initialAccount, uint256 _initialBalance, string memory _name, string memory _symbol ) internal initializer { __ERC20_init(_name, _symbol); if (_initialBalance != 0) { _mint(_initialAccount, _initialBalance); } } /** * @dev check if an address is a contract. * @param _addr The address to check. */ function isContract(address _addr) private view returns (bool hasCode) { uint256 length; assembly { length := extcodesize(_addr) } return length > 0; } /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall( address _to, uint256 _value, bytes memory _data ) public virtual override returns (bool success) { require(super.transfer(_to, _value), 'ERC677Upgradeable: transfer failed'); if (isContract(_to)) { IERC677Receiver(_to).onTokenTransfer(msg.sender, _value, _data); } return true; } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; abstract contract ERC2612Upgradeable is Initializable { // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public PERMIT_TYPEHASH; string public version; mapping(address => uint256) public nonces; function __ERC2612_init(string memory _EIP712Name) internal initializer { version = '1'; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ), keccak256(bytes(_EIP712Name)), keccak256(bytes(version)), getChainId(), address(this) ) ); PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; } function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) public virtual; function getChainId() public pure returns (uint256 chainId) { // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IERC677 { function transferAndCall( address to, uint256 value, bytes memory data ) external returns (bool ok); event Transfer(address indexed from, address indexed to, uint256 value, bytes data); } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IERC677Receiver { function onTokenTransfer( address from, uint256 amount, bytes calldata data ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_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 virtual returns (uint8) { return _decimals; } /** * @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); _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 virtual { _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 { } uint256[44] private __gap; }
Function to calculate a percentage of an amount _amount Amount to calculate the percentage of _percentage Percentage to calculate of this amount return (amount)/
function _calculatePercentage(uint256 _amount, uint256 _percentage) internal pure returns (uint256) { return uint256(_amount.mul(_percentage).div(10000)); }
142,861
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "../LQTY/PLQTYToken.sol"; contract LQTYTokenTester is PLQTYToken { constructor ( address _communityIssuanceAddress, address _lqtyStakingAddress, address _lockupFactoryAddress, address _bountyAddress, address _lpRewardsAddress, address _multisigAddress ) public PLQTYToken ( _communityIssuanceAddress, _lqtyStakingAddress, _lockupFactoryAddress, _bountyAddress, _lpRewardsAddress, _multisigAddress ) {} function unprotectedMint(address account, uint256 amount) external { // No check for the caller here _mint(account, amount); } function unprotectedSendToLQTYStaking(address _sender, uint256 _amount) external { // No check for the caller here if (_isFirstYear()) {_requireSenderIsNotMultisig(_sender);} _transfer(_sender, lqtyStakingAddress, _amount); } function callInternalApprove(address owner, address spender, uint256 amount) external returns (bool) { _approve(owner, spender, amount); } function callInternalTransfer(address sender, address recipient, uint256 amount) external returns (bool) { _transfer(sender, recipient, amount); } function getChainId() external pure returns (uint256 chainID) { //return _chainID(); // it’s private assembly { chainID := chainid() } } }
No check for the caller here
function unprotectedSendToLQTYStaking(address _sender, uint256 _amount) external { _transfer(_sender, lqtyStakingAddress, _amount); }
988,323
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _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 !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: 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; 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.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); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ILiquidator { function liquidate( address recipient, address from, address to, uint256 amount, uint256 minOut ) external returns (uint256); function getSwapInfo(address from, address to) external view returns (address router, address[] memory path); function sushiswapRouter() external view returns (address); function uniswapRouter() external view returns (address); function weth() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IManager { function token() external view returns (address); function buybackFee() external view returns (uint256); function managementFee() external view returns (uint256); function liquidators(address from, address to) external view returns (address); function whitelisted(address _contract) external view returns (bool); function banks(uint256 i) external view returns (address); function totalBanks() external view returns (uint256); function strategies(address bank, uint256 i) external view returns (address); function totalStrategies(address bank) external view returns (uint256); function withdrawIndex(address bank) external view returns (uint256); function setWithdrawIndex(uint256 i) external; function rebalance(address bank) external; function finance(address bank) external; function financeAll(address bank) external; function buyback(address from) external; function accrueRevenue( address bank, address underlying, uint256 amount ) external; function exitAll(address bank) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IRegistry { function governance() external view returns (address); function manager() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ISubscriber { function registry() external view returns (address); function governance() external view returns (address); function manager() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IBankStorage} from "./IBankStorage.sol"; interface IBank is IBankStorage { function strategies(uint256 i) external view returns (address); function totalStrategies() external view returns (uint256); function underlyingBalance() external view returns (uint256); function strategyBalance(uint256 i) external view returns (uint256); function investedBalance() external view returns (uint256); function virtualBalance() external view returns (uint256); function virtualPrice() external view returns (uint256); function pause() external; function unpause() external; function invest(address strategy, uint256 amount) external; function investAll(address strategy) external; function exit(address strategy, uint256 amount) external; function exitAll(address strategy) external; function deposit(uint256 amount) external; function depositFor(uint256 amount, address recipient) external; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IBankStorage { function paused() external view returns (bool); function underlying() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IStrategyBase} from "./IStrategyBase.sol"; interface IStrategy is IStrategyBase { function investedBalance() external view returns (uint256); function invest() external; function withdraw(uint256 amount) external returns (uint256); function withdrawAll() external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IStrategyStorage} from "./IStrategyStorage.sol"; interface IStrategyBase is IStrategyStorage { function underlyingBalance() external view returns (uint256); function derivativeBalance() external view returns (uint256); function rewardBalance() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IStrategyStorage { function bank() external view returns (address); function underlying() external view returns (address); function derivative() external view returns (address); function reward() external view returns (address); // function investedBalance() external view returns (uint256); // function invest() external; // function withdraw(uint256 amount) external returns (uint256); // function withdrawAll() external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ICurve3PoolStrategyStorage { function pool() external view returns (address); function gauge() external view returns (address); function mintr() external view returns (address); function index() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library TransferHelper { using SafeERC20 for IERC20; // safely transfer tokens without underflowing function safeTokenTransfer( address recipient, address token, uint256 amount ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 balance = IERC20(token).balanceOf(address(this)); if (balance < amount) { IERC20(token).safeTransfer(recipient, balance); return balance; } else { IERC20(token).safeTransfer(recipient, amount); return amount; } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /// @title Oh! Finance Base Upgradeable /// @notice Contains internal functions to get/set primitive data types used by a proxy contract abstract contract OhUpgradeable { function getAddress(bytes32 slot) internal view returns (address _address) { // solhint-disable-next-line no-inline-assembly assembly { _address := sload(slot) } } function getBoolean(bytes32 slot) internal view returns (bool _bool) { uint256 bool_; // solhint-disable-next-line no-inline-assembly assembly { bool_ := sload(slot) } _bool = bool_ == 1; } function getBytes32(bytes32 slot) internal view returns (bytes32 _bytes32) { // solhint-disable-next-line no-inline-assembly assembly { _bytes32 := sload(slot) } } function getUInt256(bytes32 slot) internal view returns (uint256 _uint) { // solhint-disable-next-line no-inline-assembly assembly { _uint := sload(slot) } } function setAddress(bytes32 slot, address _address) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _address) } } function setBytes32(bytes32 slot, bytes32 _bytes32) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _bytes32) } } /// @dev Set a boolean storage variable in a given slot /// @dev Convert to a uint to take up an entire contract storage slot function setBoolean(bytes32 slot, bool _bool) internal { uint256 bool_ = _bool ? 1 : 0; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, bool_) } } function setUInt256(bytes32 slot, uint256 _uint) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _uint) } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {ISubscriber} from "../interfaces/ISubscriber.sol"; import {IRegistry} from "../interfaces/IRegistry.sol"; import {OhUpgradeable} from "../proxy/OhUpgradeable.sol"; /// @title Oh! Finance Subscriber Upgradeable /// @notice Base Oh! Finance upgradeable contract used to control access throughout the protocol abstract contract OhSubscriberUpgradeable is Initializable, OhUpgradeable, ISubscriber { bytes32 private constant _REGISTRY_SLOT = 0x1b5717851286d5e98a28354be764b8c0a20eb2fbd059120090ee8bcfe1a9bf6c; /// @notice Only allow authorized addresses (governance or manager) to execute a function modifier onlyAuthorized { require(msg.sender == governance() || msg.sender == manager(), "Subscriber: Only Authorized"); _; } /// @notice Only allow the governance address to execute a function modifier onlyGovernance { require(msg.sender == governance(), "Subscriber: Only Governance"); _; } /// @notice Verify the registry storage slot is correct constructor() { assert(_REGISTRY_SLOT == bytes32(uint256(keccak256("eip1967.subscriber.registry")) - 1)); } /// @notice Initialize the Subscriber /// @param registry_ The Registry contract address /// @dev Always call this method in the initializer function for any derived classes function initializeSubscriber(address registry_) internal initializer { require(Address.isContract(registry_), "Subscriber: Invalid Registry"); _setRegistry(registry_); } /// @notice Set the Registry for the contract. Only callable by Governance. /// @param registry_ The new registry /// @dev Requires sender to be Governance of the new Registry to avoid bricking. /// @dev Ideally should not be used function setRegistry(address registry_) external onlyGovernance { _setRegistry(registry_); require(msg.sender == governance(), "Subscriber: Bad Governance"); } /// @notice Get the Governance address /// @return The current Governance address function governance() public view override returns (address) { return IRegistry(registry()).governance(); } /// @notice Get the Manager address /// @return The current Manager address function manager() public view override returns (address) { return IRegistry(registry()).manager(); } /// @notice Get the Registry address /// @return The current Registry address function registry() public view override returns (address) { return getAddress(_REGISTRY_SLOT); } function _setRegistry(address registry_) private { setAddress(_REGISTRY_SLOT, registry_); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {IBank} from "../interfaces/bank/IBank.sol"; import {IStrategyBase} from "../interfaces/strategies/IStrategyBase.sol"; import {ILiquidator} from "../interfaces/ILiquidator.sol"; import {IManager} from "../interfaces/IManager.sol"; import {TransferHelper} from "../libraries/TransferHelper.sol"; import {OhSubscriberUpgradeable} from "../registry/OhSubscriberUpgradeable.sol"; import {OhStrategyStorage} from "./OhStrategyStorage.sol"; /// @title Oh! Finance Strategy /// @notice Base Upgradeable Strategy Contract to build strategies on contract OhStrategy is OhSubscriberUpgradeable, OhStrategyStorage, IStrategyBase { using SafeERC20 for IERC20; event Liquidate(address indexed router, address indexed token, uint256 amount); event Sweep(address indexed token, uint256 amount, address recipient); /// @notice Only the Bank can execute these functions modifier onlyBank() { require(msg.sender == bank(), "Strategy: Only Bank"); _; } /// @notice Initialize the base Strategy /// @param registry_ Address of the Registry /// @param bank_ Address of Bank /// @param underlying_ Underying token that is deposited /// @param derivative_ Derivative token received from protocol, or address(0) /// @param reward_ Reward token received from protocol, or address(0) function initializeStrategy( address registry_, address bank_, address underlying_, address derivative_, address reward_ ) internal initializer { initializeSubscriber(registry_); initializeStorage(bank_, underlying_, derivative_, reward_); } /// @dev Balance of underlying awaiting Strategy investment function underlyingBalance() public view override returns (uint256) { return IERC20(underlying()).balanceOf(address(this)); } /// @dev Balance of derivative tokens received from Strategy, if applicable /// @return The balance of derivative tokens function derivativeBalance() public view override returns (uint256) { if (derivative() == address(0)) { return 0; } return IERC20(derivative()).balanceOf(address(this)); } /// @dev Balance of reward tokens awaiting liquidation, if applicable function rewardBalance() public view override returns (uint256) { if (reward() == address(0)) { return 0; } return IERC20(reward()).balanceOf(address(this)); } /// @notice Governance function to sweep any stuck / airdrop tokens to a given recipient /// @param token The address of the token to sweep /// @param amount The amount of tokens to sweep /// @param recipient The address to send the sweeped tokens to function sweep( address token, uint256 amount, address recipient ) external onlyGovernance { // require(!_protected[token], "Strategy: Cannot sweep"); TransferHelper.safeTokenTransfer(recipient, token, amount); emit Sweep(token, amount, recipient); } /// @dev Liquidation function to swap rewards for underlying function liquidate( address from, address to, uint256 amount ) internal { // if (amount > minimumSell()) // find the liquidator to use address manager = manager(); address liquidator = IManager(manager).liquidators(from, to); // increase allowance and liquidate to the manager TransferHelper.safeTokenTransfer(liquidator, from, amount); uint256 received = ILiquidator(liquidator).liquidate(manager, from, to, amount, 1); // notify revenue and transfer proceeds back to strategy IManager(manager).accrueRevenue(bank(), to, received); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {IStrategyStorage} from "../interfaces/strategies/IStrategyStorage.sol"; import {OhUpgradeable} from "../proxy/OhUpgradeable.sol"; contract OhStrategyStorage is Initializable, OhUpgradeable, IStrategyStorage { bytes32 internal constant _BANK_SLOT = 0xd2eff96e29993ca5431993c3a205e12e198965c0e1fdd87b4899b57f1e611c74; bytes32 internal constant _UNDERLYING_SLOT = 0x0fad97fe3ec7d6c1e9191a09a0c4ccb7a831b6605392e57d2fedb8501a4dc812; bytes32 internal constant _DERIVATIVE_SLOT = 0x4ff4c9b81c0bf267e01129f4817e03efc0163ee7133b87bd58118a96bbce43d3; bytes32 internal constant _REWARD_SLOT = 0xaeb865605058f37eedb4467ee2609ddec592b0c9a6f7f7cb0db3feabe544c71c; constructor() { assert(_BANK_SLOT == bytes32(uint256(keccak256("eip1967.strategy.bank")) - 1)); assert(_UNDERLYING_SLOT == bytes32(uint256(keccak256("eip1967.strategy.underlying")) - 1)); assert(_DERIVATIVE_SLOT == bytes32(uint256(keccak256("eip1967.strategy.derivative")) - 1)); assert(_REWARD_SLOT == bytes32(uint256(keccak256("eip1967.strategy.reward")) - 1)); } function initializeStorage( address bank_, address underlying_, address derivative_, address reward_ ) internal initializer { _setBank(bank_); _setUnderlying(underlying_); _setDerivative(derivative_); _setReward(reward_); } /// @notice The Bank that the Strategy is associated with function bank() public view override returns (address) { return getAddress(_BANK_SLOT); } /// @notice The underlying token the Strategy invests in AaveV2 function underlying() public view override returns (address) { return getAddress(_UNDERLYING_SLOT); } /// @notice The derivative token received from AaveV2 (aToken) function derivative() public view override returns (address) { return getAddress(_DERIVATIVE_SLOT); } /// @notice The reward token received from AaveV2 (stkAave) function reward() public view override returns (address) { return getAddress(_REWARD_SLOT); } function _setBank(address _address) internal { setAddress(_BANK_SLOT, _address); } function _setUnderlying(address _address) internal { setAddress(_UNDERLYING_SLOT, _address); } function _setDerivative(address _address) internal { setAddress(_DERIVATIVE_SLOT, _address); } function _setReward(address _address) internal { setAddress(_REWARD_SLOT, _address); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {ICurve3Pool} from "./interfaces/ICurve3Pool.sol"; import {IGauge} from "./interfaces/IGauge.sol"; import {IMintr} from "./interfaces/IMintr.sol"; /// @title Oh! Finance Curve 3Pool Helper /// @notice Helper functions for Curve 3Pool Strategies abstract contract OhCurve3PoolHelper { using SafeERC20 for IERC20; /// @notice Add liquidity to Curve's 3Pool, receiving 3CRV in return /// @param pool The address of Curve 3Pool /// @param underlying The underlying we want to deposit /// @param index The index of the underlying /// @param amount The amount of underlying to deposit /// @param minMint The min LP tokens to mint before tx reverts (slippage) function addLiquidity( address pool, address underlying, uint256 index, uint256 amount, uint256 minMint ) internal { uint256[3] memory amounts = [uint256(0), uint256(0), uint256(0)]; amounts[index] = amount; IERC20(underlying).safeIncreaseAllowance(pool, amount); ICurve3Pool(pool).add_liquidity(amounts, minMint); } /// @notice Remove liquidity from Curve 3Pool, receiving a single underlying /// @param pool The Curve 3Pool /// @param index The index of underlying we want to withdraw /// @param amount The amount to withdraw /// @param maxBurn The max LP tokens to burn before the tx reverts (slippage) function removeLiquidity( address pool, uint256 index, uint256 amount, uint256 maxBurn ) internal { uint256[3] memory amounts = [uint256(0), uint256(0), uint256(0)]; amounts[index] = amount; ICurve3Pool(pool).remove_liquidity_imbalance(amounts, maxBurn); } /// @notice Claim CRV rewards from the Mintr for a given Gauge /// @param mintr The CRV Mintr (Rewards Contract) /// @param gauge The Gauge (Staking Contract) to claim from function claim(address mintr, address gauge) internal { IMintr(mintr).mint(gauge); } /// @notice Calculate the max withdrawal amount to a single underlying /// @param pool The Curve LP Pool /// @param amount The amount of underlying to deposit /// @param index The index of the underlying in the LP Pool function calcWithdraw( address pool, uint256 amount, int128 index ) internal view returns (uint256) { return ICurve3Pool(pool).calc_withdraw_one_coin(amount, index); } /// @notice Get the balance of staked tokens in a given Gauge /// @param gauge The Curve Gauge to check function staked(address gauge) internal view returns (uint256) { return IGauge(gauge).balanceOf(address(this)); } /// @notice Stake crvUnderlying into the Gauge to earn CRV /// @param gauge The Curve Gauge to stake into /// @param crvUnderlying The Curve LP Token to stake /// @param amount The amount of LP Tokens to stake function stake( address gauge, address crvUnderlying, uint256 amount ) internal { IERC20(crvUnderlying).safeIncreaseAllowance(gauge, amount); IGauge(gauge).deposit(amount); } /// @notice Unstake crvUnderlying funds from the Curve Gauge /// @param gauge The Curve Gauge to unstake from /// @param amount The amount of LP Tokens to withdraw function unstake(address gauge, uint256 amount) internal { IGauge(gauge).withdraw(amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {IStrategy} from "../../interfaces/strategies/IStrategy.sol"; import {TransferHelper} from "../../libraries/TransferHelper.sol"; import {OhStrategy} from "../OhStrategy.sol"; import {OhCurve3PoolHelper} from "./OhCurve3PoolHelper.sol"; import {OhCurve3PoolStrategyStorage} from "./OhCurve3PoolStrategyStorage.sol"; /// @title Oh! Finance Curve 3Pool Strategy /// @notice Standard Curve 3Pool LP + Gauge Single Underlying Strategy /// @notice 3Pool Underlying, in order: (DAI, USDC, USDT) contract OhCurve3PoolStrategy is OhStrategy, OhCurve3PoolStrategyStorage, OhCurve3PoolHelper, IStrategy { using SafeERC20 for IERC20; using SafeMath for uint256; /// @notice Initialize the Curve 3Pool Strategy Logic constructor() initializer { assert(registry() == address(0)); assert(bank() == address(0)); assert(underlying() == address(0)); assert(reward() == address(0)); } /// @notice Initialize the Curve 3Pool Strategy Proxy /// @param registry_ Address of the Registry /// @param bank_ Address of the Bank /// @param underlying_ Underlying (DAI, USDC, USDT) /// @param derivative_ 3CRV LP Token /// @param reward_ CRV Gov Token /// @param pool_ Address of the Curve 3Pool /// @param gauge_ Curve Gauge, Staking Contract /// @param mintr_ Curve Mintr, Rewards Contract /// @param index_ Underlying 3Pool Index function initializeCurve3PoolStrategy( address registry_, address bank_, address underlying_, address derivative_, address reward_, address pool_, address gauge_, address mintr_, uint256 index_ ) public initializer { initializeStrategy(registry_, bank_, underlying_, derivative_, reward_); initializeCurve3PoolStorage(pool_, gauge_, mintr_, index_); } // calculate the total underlying balance function investedBalance() public view override returns (uint256) { return calcWithdraw(pool(), stakedBalance(), int128(index())); } // amount of 3CRV staked in the Gauge function stakedBalance() public view returns (uint256) { return staked(gauge()); } /// @notice Execute the Curve 3Pool Strategy /// @dev Compound CRV Yield, Add Liquidity, Stake into Gauge function invest() external override onlyBank { _compound(); _deposit(); } /// @notice Withdraw an amount of underlying from Curve 3Pool Strategy /// @param amount Amount of Underlying tokens to withdraw /// @dev Unstake from Gauge, Remove Liquidity function withdraw(uint256 amount) external override onlyBank returns (uint256) { uint256 withdrawn = _withdraw(msg.sender, amount); return withdrawn; } /// @notice Withdraw all underlying from Curve 3Pool Strategy /// @dev Unstake from Gauge, Remove Liquidity function withdrawAll() external override onlyBank { uint256 invested = investedBalance(); _withdraw(msg.sender, invested); } /// @dev Compound rewards into underlying through liquidation /// @dev Claim Rewards from Mintr, sell CRV for USDC function _compound() internal { // claim available CRV rewards claim(mintr(), gauge()); uint256 rewardAmount = rewardBalance(); if (rewardAmount > 0) { liquidate(reward(), underlying(), rewardAmount); } } // deposit underlying into 3Pool to get 3CRV and stake into Gauge function _deposit() internal { uint256 amount = underlyingBalance(); if (amount > 0) { // add liquidity to 3Pool to receive 3CRV addLiquidity(pool(), underlying(), index(), amount, 1); // stake all received in the 3CRV gauge stake(gauge(), derivative(), derivativeBalance()); } } // withdraw underlying tokens from the protocol // TODO: Double check withdrawGauge math, TransferHelper function _withdraw(address recipient, uint256 amount) internal returns (uint256) { if (amount == 0) { return 0; } uint256 invested = investedBalance(); uint256 staked = stakedBalance(); // calculate % of supply ownership uint256 supplyShare = amount.mul(1e18).div(invested); // find amount to unstake in 3CRV uint256 unstakeAmount = Math.min(staked, supplyShare.mul(staked).div(1e18)); // find amount to redeem in underlying uint256 redeemAmount = Math.min(invested, supplyShare.mul(invested).div(1e18)); // unstake from Gauge & remove liquidity from Pool unstake(gauge(), unstakeAmount); removeLiquidity(pool(), index(), redeemAmount, unstakeAmount); // withdraw to bank uint256 withdrawn = TransferHelper.safeTokenTransfer(recipient, underlying(), amount); return withdrawn; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {ICurve3PoolStrategyStorage} from "../../interfaces/strategies/curve/ICurve3PoolStrategyStorage.sol"; import {OhUpgradeable} from "../../proxy/OhUpgradeable.sol"; contract OhCurve3PoolStrategyStorage is Initializable, OhUpgradeable, ICurve3PoolStrategyStorage { bytes32 internal constant _POOL_SLOT = 0x6c9960513c6769ea8f48802ea7b637e9ce937cc3d022135cc43626003296fc46; bytes32 internal constant _GAUGE_SLOT = 0x85c79ab2dc779eb860ec993658b7f7a753e59bdfda156c7391620a5f513311e6; bytes32 internal constant _MINTR_SLOT = 0x3e7777dca2f9f31e4c2d62ce76af8def0f69b868d665539787b25b39a9f7224f; bytes32 internal constant _INDEX_SLOT = 0xd5700a843c20bfe827ca47a7c73f83287e1b32b3cd4ac659d79f800228d617fd; constructor() { assert(_POOL_SLOT == bytes32(uint256(keccak256("eip1967.curve3PoolStrategy.pool")) - 1)); assert(_GAUGE_SLOT == bytes32(uint256(keccak256("eip1967.curve3PoolStrategy.gauge")) - 1)); assert(_MINTR_SLOT == bytes32(uint256(keccak256("eip1967.curve3PoolStrategy.mintr")) - 1)); assert(_INDEX_SLOT == bytes32(uint256(keccak256("eip1967.curve3PoolStrategy.index")) - 1)); } function initializeCurve3PoolStorage( address pool_, address gauge_, address mintr_, uint256 index_ ) internal initializer { _setPool(pool_); _setGauge(gauge_); _setMintr(mintr_); _setIndex(index_); } function pool() public view override returns (address) { return getAddress(_POOL_SLOT); } function gauge() public view override returns (address) { return getAddress(_GAUGE_SLOT); } function mintr() public view override returns (address) { return getAddress(_MINTR_SLOT); } function index() public view override returns (uint256) { return getUInt256(_INDEX_SLOT); } function _setPool(address pool_) internal { setAddress(_POOL_SLOT, pool_); } function _setGauge(address gauge_) internal { setAddress(_GAUGE_SLOT, gauge_); } function _setMintr(address mintr_) internal { setAddress(_MINTR_SLOT, mintr_); } function _setIndex(uint256 index_) internal { setUInt256(_INDEX_SLOT, index_); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ICurve3Pool { function calc_token_amount(uint256[3] calldata amounts, bool deposit) external view returns (uint256); function calc_withdraw_one_coin(uint256, int128) external view returns (uint256); function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IGauge { function deposit(uint256) external; function balanceOf(address) external view returns (uint256); function withdraw(uint256) external; function user_checkpoint(address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IMintr { function mint(address) external; }
withdraw underlying tokens from the protocol TODO: Double check withdrawGauge math, TransferHelper
function _withdraw(address recipient, uint256 amount) internal returns (uint256) { if (amount == 0) { return 0; } uint256 invested = investedBalance(); uint256 staked = stakedBalance(); removeLiquidity(pool(), index(), redeemAmount, unstakeAmount); return withdrawn; }
273,992
./full_match/43113/0x3a7D90487F8E6c8631317E1B812d020CE5bB1288/sources/src/libraries/math/PackedUint128Math.sol
Returns whether any of the uint128 of x is strictly greater than the corresponding uint128 of y x The first bytes32 encoded as follows: [0 - 128[: x1 [128 - 256[: x2 y The second bytes32 encoded as follows: [0 - 128[: y1 [128 - 256[: y2 return x1 < y1 || x2 < y2/
function lt(bytes32 x, bytes32 y) internal pure returns (bool) { (uint128 x1, uint128 x2) = decode(x); (uint128 y1, uint128 y2) = decode(y); return x1 < y1 || x2 < y2; }
7,117,662
./partial_match/3/0xBE35EF1f624410945cdBf53b1E838ecd269Aebf1/sources/TrokeraCoin.sol
Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./
function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "Trokera Coin: approve from the zero address"); require(spender != address(0), "Trokera Coin: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
5,297,647
./full_match/4/0x3B8d0ef84b6a4bE7d6a43293b9D63746acB35400/sources/StakingContract.sol
Calculate rewards for the msg.sender, check if there are any rewards claim, set unclaimedRewards to 0 and transfer the ERC20 Reward token to the user.
function claimRewards() external { uint256 rewards = calculateRewards(msg.sender) + stakers[msg.sender].unclaimedRewards; require(rewards > 0, "You have no rewards to claim"); stakers[msg.sender].timeOfLastUpdate = block.timestamp; stakers[msg.sender].unclaimedRewards = 0; rewardsToken.safeTransfer(msg.sender, rewards); }
692,427
./full_match/80001/0x8337bC521242bf811771148876b82ebc8a2f80A4/sources/contracts/PercentageWinnerERC20Pool.sol
transfer to owner so that we can manually resolve this issue
function claimFor(address _addr) external { uint256 balance = balances[_addr]; require(balance > 0, "no balance"); balances[_addr] = 0; bool claimed = token.transfer(_addr, balance); if (!claimed) { token.safeTransfer(owner, balance); emit ClaimFailure(_addr, balance); } }
5,568,636
/** *Submitted for verification at Etherscan.io on 2021-07-07 */ /** *Submitted for verification at Etherscan.io on 2021-06-27 */ /** *Submitted for verification at BscScan.com on 2021-06-26 */ /** *Submitted for verification at BscScan.com on 2021-05-05 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} 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 which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public 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; } } // 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 amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 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 * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, 'Address: low-level call with value failed'); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, 'Address: insufficient balance for call'); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), 'Address: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // /** * @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}. */ contract BEP20 is Context, IBEP20 { 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 token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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 override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero') ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), 'BEP20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance') ); } } contract TeamToken is BEP20 { constructor( string memory _name, string memory _symbol, uint8 _decimals, uint256 _supply, address _owner, address _feeWallet ) public BEP20(_name, _symbol) { _setupDecimals(_decimals); _mint(_owner, _supply * 95/100); _mint(_feeWallet, _supply * 5/100); } }
Sets `amount` as the allowance of `spender` over the `owner`s tokens. This is internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./
function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
2,290,063
./full_match/42220/0x050CBccf11F1403787b5AC34fb5144162EAD3340/sources/project:/contracts/ReserveController.sol
This function is used for pools containing two tokens. It takes in a collateral token such as BPT, calculates an equal value amount of the reserve token such as G$ then mints and returns it. tokenIn - Address of collateral token amountIn - The amount being traded recipient - Address of person to receive the reserve tokens/ Retrieve a list of tokens, balances and normalised weights for the pool Transfer the input tokens from the sender to this contract Calculate the buyers share of the pool Calculate token prices using Chainlink. All prices are to 8 decimal places.
function buyReserveToken( address tokenIn, uint256 amountIn, address recipient ) public nonReentrant checkPoolSupported(tokenIn) { TradeValues memory tradeValues; tradeValues.collateral = IManagedPool(tokenIn); IERC20 collateral = IERC20(tokenIn); require( collateral.transferFrom(msg.sender, address(this), amountIn), "Transfer of input tokens failed" ); uint256 totalSupply = collateral.totalSupply(); uint256 buyersShare = amountIn / totalSupply; tradeValues.poolId = tradeValues.collateral.getPoolId(); vault.getPool(tradeValues.poolId); tradeValues.normalizedWeights = tradeValues .collateral .getNormalizedWeights(); (tradeValues.tokens, tradeValues.balances, ) = vault.getPoolTokens( tradeValues.poolId ); tradeValues.assets = SupportLib._convertERC20sToAssets( tradeValues.tokens ); for (uint256 i = 0; i < tradeValues.tokens.length; i++) { if (tradeValues.balances [i] > 0) { tradeValues.tokenPrices [i] = getTokenPrice(address(tradeValues.tokens [i])); } } for (uint256 i = 0; i < tradeValues.tokens.length; i++) { totalPoolValue = totalPoolValue + (tradeValues.balances [i] * uint256(tradeValues.tokenPrices [i])); } ReserveToken reserveToken = ReserveToken( RESERVE_TOKEN ); }
16,319,045
pragma solidity 0.4.20; 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); } // ---------------------------------------------------------------------------- // VIOLET ERC20 Standard Token // ---------------------------------------------------------------------------- contract VLTToken is ERC20Interface { using SafeMath for uint256; address public owner = msg.sender; bytes32 public symbol; bytes32 public name; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) internal allowed; modifier onlyOwner() { require(msg.sender == owner); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function VLTToken() public { symbol = "VAI"; name = "VIOLET"; decimals = 18; _totalSupply = 250000000 * 10**uint256(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @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) { // allow sending 0 tokens if (_value == 0) { Transfer(msg.sender, _to, _value); // Follow the spec to louch the event when transfer 0 return; } require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev 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 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) { // allow sending 0 tokens if (_value == 0) { Transfer(_from, _to, _value); // Follow the spec to louch the event when transfer 0 return; } require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); _totalSupply = _totalSupply.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } /** * Destroy tokens from other account * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool) { require(_value <= balances[_from]); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowed allowance balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance _totalSupply = _totalSupply.sub(_value); // Update totalSupply Burn(_from, _value); Transfer(_from, address(0), _value); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } } contract ERC20Basic { uint256 public totalSupply; 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); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ViolaCrowdsale * @dev ViolaCrowdsale reserves token from supply when eth is received * funds will be forwarded after the end of crowdsale. Tokens will be claimable * within 7 days after crowdsale ends. */ contract ViolaCrowdsale is Ownable { using SafeMath for uint256; enum State { Deployed, PendingStart, Active, Paused, Ended, Completed } //Status of contract State public status = State.Deployed; // The token being sold VLTToken public violaToken; //For keeping track of whitelist address. cap >0 = whitelisted mapping(address=>uint) public maxBuyCap; //For checking if address passed KYC mapping(address => bool)public addressKYC; //Total wei sum an address has invested mapping(address=>uint) public investedSum; //Total violaToken an address is allocated mapping(address=>uint) public tokensAllocated; //Total violaToken an address purchased externally is allocated mapping(address=>uint) public externalTokensAllocated; //Total bonus violaToken an address is entitled after vesting mapping(address=>uint) public bonusTokensAllocated; //Total bonus violaToken an address purchased externally is entitled after vesting mapping(address=>uint) public externalBonusTokensAllocated; //Store addresses that has registered for crowdsale before (pushed via setWhitelist) //Does not mean whitelisted as it can be revoked. Just to track address for loop address[] public registeredAddress; //Total amount not approved for withdrawal uint256 public totalApprovedAmount = 0; //Start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; uint256 public bonusVestingPeriod = 60 days; /** * Note all values are calculated in wei(uint256) including token amount * 1 ether = 1000000000000000000 wei * 1 viola = 1000000000000000000 vi lawei */ //Address where funds are collected address public wallet; //Min amount investor can purchase uint256 public minWeiToPurchase; // how many token units *in wei* a buyer gets *per wei* uint256 public rate; //Extra bonus token to give *in percentage* uint public bonusTokenRateLevelOne = 20; uint public bonusTokenRateLevelTwo = 15; uint public bonusTokenRateLevelThree = 10; uint public bonusTokenRateLevelFour = 0; //Total amount of tokens allocated for crowdsale uint256 public totalTokensAllocated; //Total amount of tokens reserved from external sources //Sub set of totalTokensAllocated ( totalTokensAllocated - totalReservedTokenAllocated = total tokens allocated for purchases using ether ) uint256 public totalReservedTokenAllocated; //Numbers of token left above 0 to still be considered sold uint256 public leftoverTokensBuffer; /** * event for front end logging */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount, uint256 bonusAmount); event ExternalTokenPurchase(address indexed purchaser, uint256 amount, uint256 bonusAmount); event ExternalPurchaseRefunded(address indexed purchaser, uint256 amount, uint256 bonusAmount); event TokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event BonusTokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event TopupTokenAllocated(address indexed tokenReceiver, uint256 amount, uint256 bonusAmount); event CrowdsalePending(); event CrowdsaleStarted(); event CrowdsaleEnded(); event BonusRateChanged(); event Refunded(address indexed beneficiary, uint256 weiAmount); //Set inital arguments of the crowdsale function initialiseCrowdsale (uint256 _startTime, uint256 _rate, address _tokenAddress, address _wallet) onlyOwner external { require(status == State.Deployed); require(_startTime >= now); require(_rate > 0); require(address(_tokenAddress) != address(0)); require(_wallet != address(0)); startTime = _startTime; endTime = _startTime + 30 days; rate = _rate; wallet = _wallet; violaToken = VLTToken(_tokenAddress); status = State.PendingStart; CrowdsalePending(); } /** * Crowdsale state functions * To track state of current crowdsale */ // To be called by Ethereum alarm clock or anyone //Can only be called successfully when time is valid function startCrowdsale() external { require(withinPeriod()); require(violaToken != address(0)); require(getTokensLeft() > 0); require(status == State.PendingStart); status = State.Active; CrowdsaleStarted(); } //To be called by owner or contract //Ends the crowdsale when tokens are sold out function endCrowdsale() public { if (!tokensHasSoldOut()) { require(msg.sender == owner); } require(status == State.Active); bonusVestingPeriod = now + 60 days; status = State.Ended; CrowdsaleEnded(); } //Emergency pause function pauseCrowdsale() onlyOwner external { require(status == State.Active); status = State.Paused; } //Resume paused crowdsale function unpauseCrowdsale() onlyOwner external { require(status == State.Paused); status = State.Active; } function completeCrowdsale() onlyOwner external { require(hasEnded()); require(violaToken.allowance(owner, this) == 0); status = State.Completed; _forwardFunds(); assert(this.balance == 0); } function burnExtraTokens() onlyOwner external { require(hasEnded()); uint256 extraTokensToBurn = violaToken.allowance(owner, this); violaToken.burnFrom(owner, extraTokensToBurn); assert(violaToken.allowance(owner, this) == 0); } // send ether to the fund collection wallet function _forwardFunds() internal { wallet.transfer(this.balance); } function partialForwardFunds(uint _amountToTransfer) onlyOwner external { require(status == State.Ended); require(_amountToTransfer < totalApprovedAmount); totalApprovedAmount = totalApprovedAmount.sub(_amountToTransfer); wallet.transfer(_amountToTransfer); } /** * Setter functions for crowdsale parameters * Only owner can set values */ function setLeftoverTokensBuffer(uint256 _tokenBuffer) onlyOwner external { require(_tokenBuffer > 0); require(getTokensLeft() >= _tokenBuffer); leftoverTokensBuffer = _tokenBuffer; } //Set the ether to token rate function setRate(uint _rate) onlyOwner external { require(_rate > 0); rate = _rate; } function setBonusTokenRateLevelOne(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelOne = _rate; BonusRateChanged(); } function setBonusTokenRateLevelTwo(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelTwo = _rate; BonusRateChanged(); } function setBonusTokenRateLevelThree(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelThree = _rate; BonusRateChanged(); } function setBonusTokenRateLevelFour(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelFour = _rate; BonusRateChanged(); } function setMinWeiToPurchase(uint _minWeiToPurchase) onlyOwner external { minWeiToPurchase = _minWeiToPurchase; } /** * Whitelisting and KYC functions * Whitelisted address can buy tokens, KYC successful purchaser can claim token. Refund if fail KYC */ //Set the amount of wei an address can purchase up to //@dev Value of 0 = not whitelisted //@dev cap is in *18 decimals* ( 1 token = 1*10^18) function setWhitelistAddress( address _investor, uint _cap ) onlyOwner external { require(_cap > 0); require(_investor != address(0)); maxBuyCap[_investor] = _cap; registeredAddress.push(_investor); //add event } //Remove the address from whitelist function removeWhitelistAddress(address _investor) onlyOwner external { require(_investor != address(0)); maxBuyCap[_investor] = 0; uint256 weiAmount = investedSum[_investor]; if (weiAmount > 0) { _refund(_investor); } } //Flag address as KYC approved. Address is now approved to claim tokens function approveKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = true; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.add(weiAmount); } //Set KYC status as failed. Refund any eth back to address function revokeKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = false; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.sub(weiAmount); if (weiAmount > 0) { _refund(_kycAddress); } } /** * Getter functions for crowdsale parameters * Does not use gas */ //Checks if token has been sold out function tokensHasSoldOut() view internal returns (bool) { if (getTokensLeft() <= leftoverTokensBuffer) { return true; } else { return false; } } // @return true if the transaction can buy tokens function withinPeriod() public view returns (bool) { return now >= startTime && now <= endTime; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { if (status == State.Ended) { return true; } return now > endTime; } function getTokensLeft() public view returns (uint) { return violaToken.allowance(owner, this).sub(totalTokensAllocated); } function transferTokens (address receiver, uint tokenAmount) internal { require(violaToken.transferFrom(owner, receiver, tokenAmount)); } function getTimeBasedBonusRate() public view returns(uint) { bool bonusDuration1 = now >= startTime && now <= (startTime + 1 days); //First 24hr bool bonusDuration2 = now > (startTime + 1 days) && now <= (startTime + 3 days);//Next 48 hr bool bonusDuration3 = now > (startTime + 3 days) && now <= (startTime + 10 days);//4th to 10th day bool bonusDuration4 = now > (startTime + 10 days) && now <= endTime;//11th day onwards if (bonusDuration1) { return bonusTokenRateLevelOne; } else if (bonusDuration2) { return bonusTokenRateLevelTwo; } else if (bonusDuration3) { return bonusTokenRateLevelThree; } else if (bonusDuration4) { return bonusTokenRateLevelFour; } else { return 0; } } function getTotalTokensByAddress(address _investor) public view returns(uint) { return getTotalNormalTokensByAddress(_investor).add(getTotalBonusTokensByAddress(_investor)); } function getTotalNormalTokensByAddress(address _investor) public view returns(uint) { return tokensAllocated[_investor].add(externalTokensAllocated[_investor]); } function getTotalBonusTokensByAddress(address _investor) public view returns(uint) { return bonusTokensAllocated[_investor].add(externalBonusTokensAllocated[_investor]); } function _clearTotalNormalTokensByAddress(address _investor) internal { tokensAllocated[_investor] = 0; externalTokensAllocated[_investor] = 0; } function _clearTotalBonusTokensByAddress(address _investor) internal { bonusTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; } /** * Functions to handle buy tokens * Fallback function as entry point for eth */ // Called when ether is sent to contract function () external payable { buyTokens(msg.sender); } //Used to buy tokens function buyTokens(address investor) internal { require(status == State.Active); require(msg.value >= minWeiToPurchase); uint weiAmount = msg.value; checkCapAndRecord(investor,weiAmount); allocateToken(investor,weiAmount); } //Internal call to check max user cap function checkCapAndRecord(address investor, uint weiAmount) internal { uint remaindingCap = maxBuyCap[investor]; require(remaindingCap >= weiAmount); maxBuyCap[investor] = remaindingCap.sub(weiAmount); investedSum[investor] = investedSum[investor].add(weiAmount); } //Internal call to allocated tokens purchased function allocateToken(address investor, uint weiAmount) internal { // calculate token amount to be created uint tokens = weiAmount.mul(rate); uint bonusTokens = tokens.mul(getTimeBasedBonusRate()).div(100); uint tokensToAllocate = tokens.add(bonusTokens); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(tokensToAllocate); tokensAllocated[investor] = tokensAllocated[investor].add(tokens); bonusTokensAllocated[investor] = bonusTokensAllocated[investor].add(bonusTokens); if (tokensHasSoldOut()) { endCrowdsale(); } TokenPurchase(investor, weiAmount, tokens, bonusTokens); } /** * Functions for refunds & claim tokens * */ //Refund users in case of unsuccessful crowdsale function _refund(address _investor) internal { uint256 investedAmt = investedSum[_investor]; require(investedAmt > 0); uint totalInvestorTokens = tokensAllocated[_investor].add(bonusTokensAllocated[_investor]); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); } _clearAddressFromCrowdsale(_investor); _investor.transfer(investedAmt); Refunded(_investor, investedAmt); } //Partial refund users function refundPartial(address _investor, uint _refundAmt, uint _tokenAmt, uint _bonusTokenAmt) onlyOwner external { uint investedAmt = investedSum[_investor]; require(investedAmt > _refundAmt); require(tokensAllocated[_investor] > _tokenAmt); require(bonusTokensAllocated[_investor] > _bonusTokenAmt); investedSum[_investor] = investedSum[_investor].sub(_refundAmt); tokensAllocated[_investor] = tokensAllocated[_investor].sub(_tokenAmt); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].sub(_bonusTokenAmt); uint totalRefundTokens = _tokenAmt.add(_bonusTokenAmt); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalRefundTokens); } _investor.transfer(_refundAmt); Refunded(_investor, _refundAmt); } //Used by investor to claim token function claimTokens() external { require(hasEnded()); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver, tokensToClaim); } //Used by investor to claim bonus token function claimBonusTokens() external { require(hasEnded()); require(now >= bonusVestingPeriod); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver, tokensToClaim); } //Used by owner to distribute bonus token function distributeBonusTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); require(now >= bonusVestingPeriod); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver,tokensToClaim); } //Used by owner to distribute token function distributeICOTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver,tokensToClaim); } //For owner to reserve token for presale // function reserveTokens(uint _amount) onlyOwner external { // require(getTokensLeft() >= _amount); // totalTokensAllocated = totalTokensAllocated.add(_amount); // totalReservedTokenAllocated = totalReservedTokenAllocated.add(_amount); // } // //To distribute tokens not allocated by crowdsale contract // function distributePresaleTokens(address _tokenReceiver, uint _amount) onlyOwner external { // require(hasEnded()); // require(_tokenReceiver != address(0)); // require(_amount > 0); // violaToken.transferFrom(owner, _tokenReceiver, _amount); // TokenDistributed(_tokenReceiver,_amount); // } //For external purchases & pre-sale via btc/fiat function externalPurchaseTokens(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(_amount > 0); uint256 totalTokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= totalTokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(totalTokensToAllocate); totalReservedTokenAllocated = totalReservedTokenAllocated.add(totalTokensToAllocate); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].add(_amount); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].add(_bonusAmount); ExternalTokenPurchase(_investor, _amount, _bonusAmount); } function refundAllExternalPurchase(address _investor) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] > 0); uint externalTokens = externalTokensAllocated[_investor]; uint externalBonusTokens = externalBonusTokensAllocated[_investor]; externalTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; uint totalInvestorTokens = externalTokens.add(externalBonusTokens); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalInvestorTokens); totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); ExternalPurchaseRefunded(_investor,externalTokens,externalBonusTokens); } function refundExternalPurchase(address _investor, uint _amountToRefund, uint _bonusAmountToRefund) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] >= _amountToRefund); require(externalBonusTokensAllocated[_investor] >= _bonusAmountToRefund); uint totalTokensToRefund = _amountToRefund.add(_bonusAmountToRefund); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].sub(_amountToRefund); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].sub(_bonusAmountToRefund); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalTokensToRefund); totalTokensAllocated = totalTokensAllocated.sub(totalTokensToRefund); ExternalPurchaseRefunded(_investor,_amountToRefund,_bonusAmountToRefund); } function _clearAddressFromCrowdsale(address _investor) internal { tokensAllocated[_investor] = 0; bonusTokensAllocated[_investor] = 0; investedSum[_investor] = 0; maxBuyCap[_investor] = 0; } function allocateTopupToken(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(hasEnded()); require(_amount > 0); uint256 tokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(_amount); tokensAllocated[_investor] = tokensAllocated[_investor].add(_amount); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].add(_bonusAmount); TopupTokenAllocated(_investor, _amount, _bonusAmount); } //For cases where token are mistakenly sent / airdrops function emergencyERC20Drain( ERC20 token, uint amount ) external onlyOwner { require(status == State.Completed); token.transfer(owner,amount); } }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/ allow sending 0 tokens
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (_value == 0) { return; } require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; }
5,343,199
./full_match/7700/0x6eA48824253f64662945Ae77A790331D7183f8c0/sources/project_/contracts/access/MaxAccess.sol
: This accepts the push-pull method of onlyDev()
function acceptDeveloper() external virtual override onlyRole(PENDING_DEVS) { address user = msg.sender; _revokeRole(PENDING_DEVS, user); _grantRole(DEVS, user); }
4,661,782
./full_match/1/0xD7E757Daf1ad562b01C35CC28B65876641CCAd39/sources/contracts/recipes/Deed.sol
See {IDeed-getUserContributions}/
{ contributions = new ContributionInfo[](_resources.length()); function getContributionState( uint256 resourceId } function getUserContributions( address user ) public view override returns ( ContributionInfo[] memory contributions, uint256 totalContributions ) for (uint i; i < _resources.length(); ) { uint256 resourceId = _resources.at(i); ContributionState memory contribution = _contribution[resourceId]; uint256 units = _userContributionCount[user][resourceId]; contributions[i] = ContributionInfo({ resourceId: resourceId, resourceName: contribution.name, units: units, perUnit: contribution.perUnit }); totalContributions += units; unchecked { ++i; } } function getContributionState( uint256 resourceId } function getUserContributions( address user ) public view override returns ( ContributionInfo[] memory contributions, uint256 totalContributions ) for (uint i; i < _resources.length(); ) { uint256 resourceId = _resources.at(i); ContributionState memory contribution = _contribution[resourceId]; uint256 units = _userContributionCount[user][resourceId]; contributions[i] = ContributionInfo({ resourceId: resourceId, resourceName: contribution.name, units: units, perUnit: contribution.perUnit }); totalContributions += units; unchecked { ++i; } } function getContributionState( uint256 resourceId } function getUserContributions( address user ) public view override returns ( ContributionInfo[] memory contributions, uint256 totalContributions ) for (uint i; i < _resources.length(); ) { uint256 resourceId = _resources.at(i); ContributionState memory contribution = _contribution[resourceId]; uint256 units = _userContributionCount[user][resourceId]; contributions[i] = ContributionInfo({ resourceId: resourceId, resourceName: contribution.name, units: units, perUnit: contribution.perUnit }); totalContributions += units; unchecked { ++i; } } }
17,177,495
pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. * * Subtraction and addition only here. */ library SafeMath { /** * @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; } } /** * @title A contract for generating unique identifiers for any requests. * @dev Any contract that supports requesting inherits this contract to * ensure request to be unique. */ contract RequestUid { /** * MEMBER: counter for request. */ uint256 public requestCount; /** * CONSTRUCTOR: initial counter with 0. */ constructor() public { requestCount = 0; } /** * METHOD: generate a new identifier. * @dev 3 parameters as inputs: * 1. blockhash of previous block; * 2. the address of the initialized contract which is requested; * 3. the value of counter. * @return a 32-byte uid. */ function generateRequestUid() internal returns (bytes32 uid) { return keccak256(abi.encodePacked(blockhash(block.number - uint256(1)), address(this), ++requestCount)); } } /** * @dev This contract makes the inheritor have the functionality if the * inheritor authorize the admin. */ contract AdminUpgradeable is RequestUid { /** * Event * @dev After requesting of admin change, emit an event. */ event AdminChangeRequested(bytes32 _uid, address _msgSender, address _newAdmin); /** * Event * @dev After confirming a request of admin change, emit an event. */ event AdminChangeConfirmed(bytes32 _uid, address _newAdmin); /** * STRUCT: A struct defined to store an request of admin change. */ struct AdminChangeRequest { address newAdminAddress; } /** * MEMBER: admin address(account address or contract address) which * is authorize by the inheritor. */ address public admin; /** * MEMBER: a list of requests submitted. */ mapping (bytes32 => AdminChangeRequest) public adminChangeReqs; /** * MODIFIER: The operations from admin is allowed only. */ modifier adminOperations { require(msg.sender == admin, "admin can call this method only"); _; } /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public RequestUid() { admin = _admin; } /** * METHOD: Upgrade the admin ---- request. * @dev Request changing the admin address authorized. * Anyone can call this method to submit a request to change * the admin address. It will be pending until admin address * comfirming the request, and the admin changes. * @param _newAdmin The address of new admin, account or contract. * @return uid The unique id of the request. */ function requestAdminChange(address _newAdmin) public returns (bytes32 uid) { require(_newAdmin != address(0), "admin is not 0 address"); uid = generateRequestUid(); adminChangeReqs[uid] = AdminChangeRequest({ newAdminAddress: _newAdmin }); emit AdminChangeRequested(uid, msg.sender, _newAdmin); } /** * METHOD: Upgrade the admin ---- confirm. * @dev Confirm a reqeust of admin change storing in the mapping * of `adminChangeReqs`. The operation is authorized to the old * admin only. The new admin will be authorized after the method * called successfully. * @param _uid The uid of request to change admin. */ function confirmAdminChange(bytes32 _uid) public adminOperations { admin = getAdminChangeReq(_uid); delete adminChangeReqs[_uid]; emit AdminChangeConfirmed(_uid, admin); } /** * METHOD: Get the address of an admin request by uid. * @dev It is a private method which gets address of an admin * in the mapping `adminChangeReqs` * @param _uid The uid of request to change admin. * @return _newAdminAddress The address of new admin in the pending requests */ function getAdminChangeReq(bytes32 _uid) private view returns (address _newAdminAddress) { AdminChangeRequest storage changeRequest = adminChangeReqs[_uid]; require(changeRequest.newAdminAddress != address(0)); return changeRequest.newAdminAddress; } } /** * @dev This is a contract which will be inherited by BICAProxy and BICALedger. */ contract BICALogicUpgradeable is AdminUpgradeable { /** * Event * @dev After requesting of logic contract address change, emit an event. */ event LogicChangeRequested(bytes32 _uid, address _msgSender, address _newLogic); /** * Event * @dev After confirming a request of logic contract address change, emit an event. */ event LogicChangeConfirmed(bytes32 _uid, address _newLogic); /** * STRUCT: A struct defined to store an request of Logic contract address change. */ struct LogicChangeRequest { address newLogicAddress; } /** * MEMBER: BICALogic address(a contract address) which implements logics of token. */ BICALogic public bicaLogic; /** * MEMBER: a list of requests of logic change submitted */ mapping (bytes32 => LogicChangeRequest) public logicChangeReqs; /** * MODIFIER: The call from bicaLogic is allowed only. */ modifier onlyLogic { require(msg.sender == address(bicaLogic), "only logic contract is authorized"); _; } /** * CONSTRUCTOR: Initialize with an admin address which is authorized to change * the value of bicaLogic. */ constructor (address _admin) public AdminUpgradeable(_admin) { bicaLogic = BICALogic(0x0); } /** * METHOD: Upgrade the logic contract ---- request. * @dev Request changing the logic contract address authorized. * Anyone can call this method to submit a request to change * the logic address. It will be pending until admin address * comfirming the request, and the logic contract address changes, i.e. * the value of bicaLogic changes. * @param _newLogic The address of new logic contract. * @return uid The unique id of the request. */ function requestLogicChange(address _newLogic) public returns (bytes32 uid) { require(_newLogic != address(0), "new logic address can not be 0"); uid = generateRequestUid(); logicChangeReqs[uid] = LogicChangeRequest({ newLogicAddress: _newLogic }); emit LogicChangeRequested(uid, msg.sender, _newLogic); } /** * METHOD: Upgrade the logic contract ---- confirm. * @dev Confirm a reqeust of logic contract change storing in the * mapping of `logicChangeReqs`. The operation is authorized to * the admin only. * @param _uid The uid of request to change logic contract. */ function confirmLogicChange(bytes32 _uid) public adminOperations { bicaLogic = getLogicChangeReq(_uid); delete logicChangeReqs[_uid]; emit LogicChangeConfirmed(_uid, address(bicaLogic)); } /** * METHOD: Get the address of an logic contract address request by uid. * @dev It is a private method which gets address of an address * in the mapping `adminChangeReqs` * @param _uid The uid of request to change logic contract address. * @return _newLogicAddress The address of new logic contract address * in the pending requests */ function getLogicChangeReq(bytes32 _uid) private view returns (BICALogic _newLogicAddress) { LogicChangeRequest storage changeRequest = logicChangeReqs[_uid]; require(changeRequest.newLogicAddress != address(0)); return BICALogic(changeRequest.newLogicAddress); } } /** * @dev This contract is the core contract of all logic. It links `bicaProxy` * and `bicaLedger`. It implements the issue of new amount of token, burn some * value of someone's token. */ contract BICALogic is AdminUpgradeable { using SafeMath for uint256; /** * Event * @dev After issuing an ammout of BICA, emit an event for the value of requester. */ event Requester(address _supplyAddress, address _receiver, uint256 _valueRequested); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying margin. */ event PayMargin(address _supplyAddress, address _marginAddress, uint256 _marginValue); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying interest. */ event PayInterest(address _supplyAddress, address _interestAddress, uint256 _interestValue); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying multi fee. */ event PayMultiFee(address _supplyAddress, address _feeAddress, uint256 _feeValue); /** * Event * @dev After freezing a user address, emit an event in logic contract. */ event AddressFrozenInLogic(address indexed addr); /** * Event * @dev After unfreezing a user address, emit an event in logic contract. */ event AddressUnfrozenInLogic(address indexed addr); /** * MEMBER: A reference to the proxy contract. * It links the proxy contract in one direction. */ BICAProxy public bicaProxy; /** * MEMBER: A reference to the ledger contract. * It links the ledger contract in one direction. */ BICALedger public bicaLedger; /** * MODIFIER: The call from bicaProxy is allowed only. */ modifier onlyProxy { require(msg.sender == address(bicaProxy), "only the proxy contract allowed only"); _; } /** * CONSTRUCTOR: Initialize with the proxy contract address, the ledger * contract and an admin address. */ constructor (address _bicaProxy, address _bicaLedger, address _admin) public AdminUpgradeable(_admin) { bicaProxy = BICAProxy(_bicaProxy); bicaLedger = BICALedger(_bicaLedger); } /** * METHOD: `approve` operation in logic contract. * @dev Receive the call request of `approve` from proxy contract and * request approve operation to ledger contract. Need to check the sender * and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function approveWithSender(address _sender, address _spender, uint256 _value) public onlyProxy returns (bool success){ require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); bicaLedger.setAllowance(_sender, _spender, _value); bicaProxy.emitApproval(_sender, _spender, _value); return true; } /** * METHOD: Core logic of the `increaseApproval` method in proxy contract. * @dev Receive the call request of `increaseApproval` from proxy contract * and request increasing value of allownce to ledger contract. Need to * check the sender * and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function increaseApprovalWithSender(address _sender, address _spender, uint256 _addedValue) public onlyProxy returns (bool success) { require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); uint256 currentAllowance = bicaLedger.allowed(_sender, _spender); uint256 newAllowance = currentAllowance.add(_addedValue); require(newAllowance >= currentAllowance); bicaLedger.setAllowance(_sender, _spender, newAllowance); bicaProxy.emitApproval(_sender, _spender, newAllowance); return true; } /** * METHOD: Core logic of the `decreaseApproval` method in proxy contract. * @dev Receive the call request of `decreaseApproval` from proxy contract * and request decreasing value of allownce to ledger contract. Need to * check the sender and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function decreaseApprovalWithSender(address _sender, address _spender, uint256 _subtractedValue) public onlyProxy returns (bool success) { require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); uint256 currentAllowance = bicaLedger.allowed(_sender, _spender); uint256 newAllowance = currentAllowance.sub(_subtractedValue); require(newAllowance <= currentAllowance); bicaLedger.setAllowance(_sender, _spender, newAllowance); bicaProxy.emitApproval(_sender, _spender, newAllowance); return true; } /** * METHOD: Core logic of comfirming request of issuetoken to a specified receiver. * @dev Admin can issue an ammout of BICA only. * @param _requesterAccount The address of request account. * @param _requestValue The value of requester. * @param _marginAccount The address of margin account. * @param _marginValue The value of token to pay to margin account. * @param _interestAccount The address accepting interest. * @param _interestValue The value of interest. * @param _otherFeeAddress The address accepting multi fees. * @param _otherFeeValue The value of other fees. */ function issue(address _requesterAccount, uint256 _requestValue, address _marginAccount, uint256 _marginValue, address _interestAccount, uint256 _interestValue, address _otherFeeAddress, uint256 _otherFeeValue) public adminOperations { require(_requesterAccount != address(0)); require(_marginAccount != address(0)); require(_interestAccount != address(0)); require(_otherFeeAddress != address(0)); require(!bicaLedger.getFrozenByAddress(_requesterAccount), "Requester is frozen"); require(!bicaLedger.getFrozenByAddress(_marginAccount), "Margin account is frozen"); require(!bicaLedger.getFrozenByAddress(_interestAccount), "Interest account is frozen"); require(!bicaLedger.getFrozenByAddress(_otherFeeAddress), "Other fee account is frozen"); uint256 requestTotalValue = _marginValue.add(_interestValue).add(_otherFeeValue).add(_requestValue); uint256 supply = bicaLedger.totalSupply(); uint256 newSupply = supply.add(requestTotalValue); if (newSupply >= supply) { bicaLedger.setTotalSupply(newSupply); bicaLedger.addBalance(_marginAccount, _marginValue); bicaLedger.addBalance(_interestAccount, _interestValue); if ( _otherFeeValue > 0 ){ bicaLedger.addBalance(_otherFeeAddress, _otherFeeValue); } bicaLedger.addBalance(_requesterAccount, _requestValue); emit Requester(msg.sender, _requesterAccount, _requestValue); emit PayMargin(msg.sender, _marginAccount, _marginValue); emit PayInterest(msg.sender, _interestAccount, _interestValue); emit PayMultiFee(msg.sender, _otherFeeAddress, _otherFeeValue); bicaProxy.emitTransfer(address(0), _marginAccount, _marginValue); bicaProxy.emitTransfer(address(0), _interestAccount, _interestValue); bicaProxy.emitTransfer(address(0), _otherFeeAddress, _otherFeeValue); bicaProxy.emitTransfer(address(0), _requesterAccount, _requestValue); } } /** * METHOD: Burn the specified value of the message sender's balance. * @dev Admin can call this method to burn some amount of BICA. * @param _value The amount of token to be burned. * @return success or not. */ function burn(uint256 _value) public adminOperations returns (bool success) { bool burnerFrozen = bicaLedger.getFrozenByAddress(msg.sender); require(!burnerFrozen, "Burner is frozen"); uint256 balanceOfSender = bicaLedger.balances(msg.sender); require(_value <= balanceOfSender); bicaLedger.setBalance(msg.sender, balanceOfSender.sub(_value)); bicaLedger.setTotalSupply(bicaLedger.totalSupply().sub(_value)); bicaProxy.emitTransfer(msg.sender, address(0), _value); return true; } /** * METHOD: Freeze a user address. * @dev Admin can call this method to freeze a user account. * @param _user user address. */ function freeze(address _user) public adminOperations { require(_user != address(0), "the address to be frozen cannot be 0"); bicaLedger.freezeByAddress(_user); emit AddressFrozenInLogic(_user); } /** * METHOD: Unfreeze a user address. * @dev Admin can call this method to unfreeze a user account. * @param _user user address. */ function unfreeze(address _user) public adminOperations { require(_user != address(0), "the address to be unfrozen cannot be 0"); bicaLedger.unfreezeByAddress(_user); emit AddressUnfrozenInLogic(_user); } /** * METHOD: Core logic of `transferFrom` interface method in ERC20 token standard. * @dev It can only be called by the `bicaProxy` contract. * @param _sender The address initiating the approval in proxy. * @return success or not. */ function transferFromWithSender(address _sender, address _from, address _to, uint256 _value) public onlyProxy returns (bool success){ require(_to != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool fromFrozen = bicaLedger.getFrozenByAddress(_from); require(!fromFrozen, "`from` is frozen"); bool toFrozen = bicaLedger.getFrozenByAddress(_to); require(!toFrozen, "`to` is frozen"); uint256 balanceOfFrom = bicaLedger.balances(_from); require(_value <= balanceOfFrom); uint256 senderAllowance = bicaLedger.allowed(_from, _sender); require(_value <= senderAllowance); bicaLedger.setBalance(_from, balanceOfFrom.sub(_value)); bicaLedger.addBalance(_to, _value); bicaLedger.setAllowance(_from, _sender, senderAllowance.sub(_value)); bicaProxy.emitTransfer(_from, _to, _value); return true; } /** * METHOD: Core logic of `transfer` interface method in ERC20 token standard. * @dev It can only be called by the `bicaProxy` contract. * @param _sender The address initiating the approval in proxy. * @return success or not. */ function transferWithSender(address _sender, address _to, uint256 _value) public onlyProxy returns (bool success){ require(_to != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "sender is frozen"); bool toFrozen = bicaLedger.getFrozenByAddress(_to); require(!toFrozen, "to is frozen"); uint256 balanceOfSender = bicaLedger.balances(_sender); require(_value <= balanceOfSender); bicaLedger.setBalance(_sender, balanceOfSender.sub(_value)); bicaLedger.addBalance(_to, _value); bicaProxy.emitTransfer(_sender, _to, _value); return true; } /** * METHOD: Core logic of `totalSupply` interface method in ERC20 token standard. */ function totalSupply() public view returns (uint256) { return bicaLedger.totalSupply(); } /** * METHOD: Core logic of `balanceOf` interface method in ERC20 token standard. */ function balanceOf(address _owner) public view returns (uint256 balance) { return bicaLedger.balances(_owner); } /** * METHOD: Core logic of `allowance` interface method in ERC20 token standard. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return bicaLedger.allowed(_owner, _spender); } } /** * @dev This contract is the core storage contract of ERC20 token ledger. * It defines some operations of data in the storage. */ contract BICALedger is BICALogicUpgradeable { using SafeMath for uint256; /** * MEMBER: The total supply of the token. */ uint256 public totalSupply; /** * MEMBER: The mapping of balance of users. */ mapping (address => uint256) public balances; /** * MEMBER: The mapping of allowance of users. */ mapping (address => mapping (address => uint256)) public allowed; /** * MEMBER: The mapping of frozen addresses. */ mapping(address => bool) public frozen; /** * Event * @dev After freezing a user address, emit an event in ledger contract. */ event AddressFrozen(address indexed addr); /** * Event * @dev After unfreezing a user address, emit an event in ledger contract. */ event AddressUnfrozen(address indexed addr); /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public BICALogicUpgradeable(_admin) { totalSupply = 0; } /** * METHOD: Check an address is frozen or not. * @dev check an address is frozen or not. It can be call by logic contract only. * @param _user user addree. */ function getFrozenByAddress(address _user) public view onlyLogic returns (bool frozenOrNot) { // frozenOrNot = false; return frozen[_user]; } /** * METHOD: Freeze an address. * @dev Freeze an address. It can be called by logic contract only. * @param _user user addree. */ function freezeByAddress(address _user) public onlyLogic { require(!frozen[_user], "user already frozen"); frozen[_user] = true; emit AddressFrozen(_user); } /** * METHOD: Unfreeze an address. * @dev Unfreeze an address. It can be called by logic contract only. * @param _user user addree. */ function unfreezeByAddress(address _user) public onlyLogic { require(frozen[_user], "address already unfrozen"); frozen[_user] = false; emit AddressUnfrozen(_user); } /** * METHOD: Set `totalSupply` in the ledger contract. * @dev It will be called when a new issue is confirmed. It can be called * by logic contract only. * @param _newTotalSupply The value of new total supply. */ function setTotalSupply(uint256 _newTotalSupply) public onlyLogic { totalSupply = _newTotalSupply; } /** * METHOD: Set allowance for owner to a spender in the ledger contract. * @dev It will be called when the owner modify the allowance to the * spender. It can be called by logic contract only. * @param _owner The address allow spender to spend. * @param _spender The address allowed to spend. * @param _value The limit of how much can be spent by `_spender`. */ function setAllowance(address _owner, address _spender, uint256 _value) public onlyLogic { allowed[_owner][_spender] = _value; } /** * METHOD: Set balance of the owner in the ledger contract. * @dev It will be called when the owner modify the balance of owner * in logic. It can be called by logic contract only. * @param _owner The address who owns the balance. * @param _newBalance The balance to be set. */ function setBalance(address _owner, uint256 _newBalance) public onlyLogic { balances[_owner] = _newBalance; } /** * METHOD: Add balance of the owner in the ledger contract. * @dev It will be called when the balance of owner increases. * It can be called by logic contract only. * @param _owner The address who owns the balance. * @param _balanceIncrease The balance to be add. */ function addBalance(address _owner, uint256 _balanceIncrease) public onlyLogic { balances[_owner] = balances[_owner].add(_balanceIncrease); } } contract ERC20Interface { function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @dev This contract is a viewer of ERC20 token standard. * It includes no logic and data. */ contract BICAProxy is ERC20Interface, BICALogicUpgradeable { /** * MEMBER: The name of the token. */ string public name; /** * MEMBER: The symbol of the token. */ string public symbol; /** * MEMBER: The number of decimals of the token. */ uint public decimals; /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public BICALogicUpgradeable(_admin){ name = "BitCapital Coin"; symbol = 'BICA'; decimals = 2; } /** * METHOD: Get `totalSupply` of token. * @dev It is the standard method of ERC20. * @return The total token supply. */ function totalSupply() public view returns (uint256) { return bicaLogic.totalSupply(); } /** * METHOD: Get the balance of a owner. * @dev It is the standard method of ERC20. * @return The balance of a owner. */ function balanceOf(address _owner) public view returns (uint256 balance) { return bicaLogic.balanceOf(_owner); } /** * METHOD: Emit a Transfer event in proxy contract. */ function emitTransfer(address _from, address _to, uint256 _value) public onlyLogic { emit Transfer(_from, _to, _value); } /** * METHOD: The message sender sends some amount of token to receiver. * @dev It will call the logic contract to send some token to receiver. * It is the standard method of ERC20. * @return success or not */ function transfer(address _to, uint256 _value) public returns (bool success) { return bicaLogic.transferWithSender(msg.sender, _to, _value); } /** * METHOD: Transfer amount of tokens from `_from` to `_to`. * @dev It is the standard method of ERC20. * @return success or not */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return bicaLogic.transferFromWithSender(msg.sender, _from, _to, _value); } /** * METHOD: Emit a Approval event in proxy contract. */ function emitApproval(address _owner, address _spender, uint256 _value) public onlyLogic { emit Approval(_owner, _spender, _value); } /** * METHOD: Allow `_spender` to be able to spend `_value` token. * @dev It is the standard method of ERC20. * @return success or not */ function approve(address _spender, uint256 _value) public returns (bool success) { return bicaLogic.approveWithSender(msg.sender, _spender, _value); } /** * METHOD: Increase allowance value of message sender to `_spender`. * @return success or not */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return bicaLogic.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } /** * METHOD: Decrease allowance value of message sender to `_spender`. * @return success or not */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) { return bicaLogic.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } /** * METHOD: Return the allowance value of `_owner` to `_spender`. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return bicaLogic.allowance(_owner, _spender); } }
METHOD: Emit a Approval event in proxy contract./
function emitApproval(address _owner, address _spender, uint256 _value) public onlyLogic { emit Approval(_owner, _spender, _value); }
2,479,152
./full_match/1/0xd08481058399490B83a72676901d4e9dB70E75aC/sources/contracts/TIMEDividend.sol
This private function claims the dividend for `_msgSender()` recipient Account to receive dividend from account amount the amount to distribute - 0 is recognized as all return claimed true if the claim is successful, false otherwise if zero is passed for amount, all of the available tokens are released the account distributing to must be payable/ return if we can't claim anything
function claimDividend( address payable recipient, uint256 amount ) public returns (uint256) { address account = _msgSender(); uint256 claimable = clamp(amount, claimableDividendOf(account)); if (claimable == 0) { return 0; } cumulativeDividendClaimed[account] += claimable; recipient.sendValue(claimable); emit ClaimDividend(account, recipient, claimable); return claimable; }
2,934,260
// SPDX-License-Identifier: MIT pragma solidity =0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@sushiswap/core/contracts/uniswapv2/libraries/SafeMath.sol"; import "@sushiswap/core/contracts/uniswapv2/libraries/TransferHelper.sol"; import "@sushiswap/core/contracts/uniswapv2/libraries/UniswapV2Library.sol"; import "@sushiswap/core/contracts/uniswapv2/interfaces/IERC20.sol"; import "./interfaces/ISettlement.sol"; import "./interfaces/IOrderBook.sol"; import "./interfaces/IRouterWrapper.sol"; import "./libraries/Orders.sol"; import "./libraries/EIP712.sol"; contract Settlement is ISettlement, ReentrancyGuard, Ownable { using SafeMathUniswap for uint256; using Orders for Orders.Order; // solhint-disable-next-line var-name-mixedcase bytes32 public immutable DOMAIN_SEPARATOR; // Hash of an order => if canceled mapping(address => mapping(bytes32 => bool)) public canceledOfHash; // Hash of an order => filledAmountIn mapping(bytes32 => uint256) public filledAmountInOfHash; address public immutable factory; address public orderBookAddress; IRouterWrapper public router; constructor( uint256 orderBookChainId, address _orderBookAddress, address _factory, address _router ) public { DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256("OrderBook"), keccak256("1"), orderBookChainId, _orderBookAddress ) ); factory = _factory; orderBookAddress = _orderBookAddress; router = IRouterWrapper(_router); } fallback() external payable {} receive() external payable {} // Fills an order function fillOrder(FillOrderArgs memory args) public override nonReentrant returns (uint256 amountOut) { // voids flashloan attack vectors // solhint-disable-next-line avoid-tx-origin require(msg.sender == tx.origin, "called-by-contract"); // Check if the order is canceled / already fully filled bytes32 hash = args.order.hash(); _validateStatus(args, hash); // Check if the signature is valid address signer = EIP712.recover(DOMAIN_SEPARATOR, hash, args.order.v, args.order.r, args.order.s); require(signer != address(0) && signer == args.order.maker, "invalid-signature"); // Calculates amountOutMin uint256 amountOutMin = (args.order.amountOutMin.mul(args.amountToFillIn) / args.order.amountIn); // Calculates fee amount uint256 feeAmount = args.order.fee; if (args.amountToFillIn < args.order.amountIn) { feeAmount = (args.order.fee.mul(args.amountToFillIn) / args.order.amountIn); } IERC20Uniswap(args.order.fromToken).transferFrom( args.order.maker, address(this), args.amountToFillIn ); IERC20Uniswap(args.order.fromToken).approve( address(router), args.amountToFillIn ); uint256[] memory amounts = router.swapExactTokensForTokens( args.router, args.amountToFillIn, amountOutMin, args.path, args.order.recipient, now.add(60) ); amountOut = amounts[amounts.length - 1]; // This line is free from reentrancy issues since UniswapV2Pair prevents from them filledAmountInOfHash[hash] = filledAmountInOfHash[hash].add(args.amountToFillIn); if (feeAmount > 0) { msg.sender.transfer(feeAmount); emit FeeTransferred(hash, msg.sender, feeAmount); } emit OrderFilled(hash, args.amountToFillIn, amountOut); } // Checks if an order is canceled / already fully filled function _validateStatus(FillOrderArgs memory args, bytes32 hash) internal view { require(args.order.deadline >= block.timestamp, "order-expired"); require(!canceledOfHash[args.order.maker][hash], "order-canceled"); require(filledAmountInOfHash[hash].add(args.amountToFillIn) <= args.order.amountIn, "already-filled"); } // Cancels an order, has to been called by order maker function cancelOrder(bytes32 hash) public override { require(!canceledOfHash[msg.sender][hash], "already-cancelled"); canceledOfHash[msg.sender][hash] = true; Orders.Order memory order = IOrderBook(orderBookAddress).orderOfHash(hash); // refund fee if (order.fee > 0) { uint256 feeAmountDiscount = (order.fee.mul(filledAmountInOfHash[hash]) / order.amountIn); uint256 feeAmount = order.fee.sub(feeAmountDiscount); msg.sender.transfer(feeAmount); emit FeeTransferred(hash, msg.sender, feeAmount); } emit OrderCanceled(hash); } function setRouter(address _router) external onlyOwner { require(_router != address(0),"invalid-address"); require(_router != address(router), "same-value"); router = IRouterWrapper(_router); } }
Cancels an order, has to been called by order maker refund fee
function cancelOrder(bytes32 hash) public override { require(!canceledOfHash[msg.sender][hash], "already-cancelled"); canceledOfHash[msg.sender][hash] = true; Orders.Order memory order = IOrderBook(orderBookAddress).orderOfHash(hash); if (order.fee > 0) { uint256 feeAmountDiscount = (order.fee.mul(filledAmountInOfHash[hash]) / order.amountIn); uint256 feeAmount = order.fee.sub(feeAmountDiscount); msg.sender.transfer(feeAmount); emit FeeTransferred(hash, msg.sender, feeAmount); } emit OrderCanceled(hash); }
6,401,080
./full_match/4/0x6BE60E29FBb7559A5aF18D1e8F840767dd315359/sources/tellorcore/contracts/TellorGetters.sol
Gets balance of owner specified _user is the owner address used to look up the balance return Returns the balance associated with the passed in _user/
function balanceOf(address _user) external view returns (uint256) { return tellor.balanceOf(_user); }
817,625
./full_match/1/0xd446315C7e4fA5354d019970e1a4C6045bB133af/sources/contracts/Uniswap/UniswapAnchoredView.sol
Fetches the current eth/usd price from Uniswap, with 6 decimals of precision. Conversion factor is 1e18 for eth/usdc market, since we decode Uniswap price statically with 18 decimals./
function fetchEthPrice() internal view returns (uint256) { return fetchAnchorPrice( getTokenConfigBySymbolHash(ETH_HASH), ETH_BASE_UNIT ); }
3,182,771
//Address: 0x1f6e6af195376fb39bb7fede37aa5fb28ac12b44 //Contract name: RaindropClient //Balance: 0 Ether //Verification Date: 4/19/2018 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.21; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract 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 Withdrawable is Ownable { // Allows owner to withdraw ether from the contract function withdrawEther(address to) public onlyOwner { to.transfer(address(this).balance); } // Allows owner to withdraw ERC20 tokens from the contract function withdrawERC20Token(address tokenAddress, address to) public onlyOwner { ERC20Basic token = ERC20Basic(tokenAddress); token.transfer(to, token.balanceOf(address(this))); } } contract RaindropClient is Withdrawable { // Events for when a user signs up for Raindrop Client and when their account is deleted event UserSignUp(string userName, address userAddress, bool delegated); event UserDeleted(string userName); // Variables allowing this contract to interact with the Hydro token address public hydroTokenAddress; uint public minimumHydroStakeUser; uint public minimumHydroStakeDelegatedUser; // User account template struct User { string userName; address userAddress; bool delegated; bool _initialized; } // Mapping from hashed names to users (primary User directory) mapping (bytes32 => User) internal userDirectory; // Mapping from addresses to hashed names (secondary directory for account recovery based on address) mapping (address => bytes32) internal nameDirectory; // Requires an address to have a minimum number of Hydro modifier requireStake(address _address, uint stake) { ERC20Basic hydro = ERC20Basic(hydroTokenAddress); require(hydro.balanceOf(_address) >= stake); _; } // Allows applications to sign up users on their behalf iff users signed their permission function signUpDelegatedUser(string userName, address userAddress, uint8 v, bytes32 r, bytes32 s) public requireStake(msg.sender, minimumHydroStakeDelegatedUser) { require(isSigned(userAddress, keccak256("Create RaindropClient Hydro Account"), v, r, s)); _userSignUp(userName, userAddress, true); } // Allows users to sign up with their own address function signUpUser(string userName) public requireStake(msg.sender, minimumHydroStakeUser) { return _userSignUp(userName, msg.sender, false); } // Allows users to delete their accounts function deleteUser() public { bytes32 userNameHash = nameDirectory[msg.sender]; require(userDirectory[userNameHash]._initialized); string memory userName = userDirectory[userNameHash].userName; delete nameDirectory[msg.sender]; delete userDirectory[userNameHash]; emit UserDeleted(userName); } // Allows the Hydro API to link to the Hydro token function setHydroTokenAddress(address _hydroTokenAddress) public onlyOwner { hydroTokenAddress = _hydroTokenAddress; } // Allows the Hydro API to set minimum hydro balances required for sign ups function setMinimumHydroStakes(uint newMinimumHydroStakeUser, uint newMinimumHydroStakeDelegatedUser) public { ERC20Basic hydro = ERC20Basic(hydroTokenAddress); require(newMinimumHydroStakeUser <= (hydro.totalSupply() / 100 / 10)); // <= .1% of total supply require(newMinimumHydroStakeDelegatedUser <= (hydro.totalSupply() / 100)); // <= 1% of total supply minimumHydroStakeUser = newMinimumHydroStakeUser; minimumHydroStakeDelegatedUser = newMinimumHydroStakeDelegatedUser; } // Returns a bool indicated whether a given userName has been claimed function userNameTaken(string userName) public view returns (bool taken) { bytes32 userNameHash = keccak256(userName); return userDirectory[userNameHash]._initialized; } // Returns user details by user name function getUserByName(string userName) public view returns (address userAddress, bool delegated) { bytes32 userNameHash = keccak256(userName); User storage _user = userDirectory[userNameHash]; require(_user._initialized); return (_user.userAddress, _user.delegated); } // Returns user details by user address function getUserByAddress(address _address) public view returns (string userName, bool delegated) { bytes32 userNameHash = nameDirectory[_address]; User storage _user = userDirectory[userNameHash]; require(_user._initialized); return (_user.userName, _user.delegated); } // Checks whether the provided (v, r, s) signature was created by the private key associated with _address function isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return (_isSigned(_address, messageHash, v, r, s) || _isSignedPrefixed(_address, messageHash, v, r, s)); } // Checks unprefixed signatures function _isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (bool) { return ecrecover(messageHash, v, r, s) == _address; } // Checks prefixed signatures (e.g. those created with web3.eth.sign) function _isSignedPrefixed(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedMessageHash = keccak256(prefix, messageHash); return ecrecover(prefixedMessageHash, v, r, s) == _address; } // Common internal logic for all user signups function _userSignUp(string userName, address userAddress, bool delegated) internal { require(bytes(userName).length < 100); bytes32 userNameHash = keccak256(userName); require(!userDirectory[userNameHash]._initialized); userDirectory[userNameHash] = User(userName, userAddress, delegated, true); nameDirectory[userAddress] = userNameHash; emit UserSignUp(userName, userAddress, delegated); } }
Returns user details by user name
function getUserByName(string userName) public view returns (address userAddress, bool delegated) { bytes32 userNameHash = keccak256(userName); User storage _user = userDirectory[userNameHash]; require(_user._initialized); return (_user.userAddress, _user.delegated); }
14,074,085
./partial_match/83/0xB210c12DCBc5437620B562b848C1251de85EfF35/sources/contracts/AlgebraPool.sol
@inheritdoc IAlgebraPoolPermissionedActions
function setCommunityFee(uint8 communityFee0, uint8 communityFee1) external override lock onlyFactoryOwner { require((communityFee0 <= Constants.MAX_COMMUNITY_FEE) && (communityFee1 <= Constants.MAX_COMMUNITY_FEE)); (globalState.communityFeeToken0, globalState.communityFeeToken1) = (communityFee0, communityFee1); emit CommunityFee(communityFee0, communityFee1); }
8,828,011
./partial_match/1/0xBA4C1c4AeD5d664588557546F5090e45aae99394/sources/MeiMachina.sol
Converts to absolute value, and fails on overflow./
function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; }
15,980,720
// SPDX-License-Identifier: MIT /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; ////import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; ////import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; ////import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [////IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * ////IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; ////import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "@openzeppelin/contracts/access/Ownable.sol"; ////import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /** * @title Divinity Cell DivinityCellWhitelist Contract * @notice Part of the DivinityCellMinter * @author Apriorit */ contract DivinityCellWhitelist is Ownable { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet _whitelisted_users; /** * @notice Add toWhitelist address to the whitelist * @param toWhitelist The address of account to whitelist * @return Whether or not the transaction succeeded */ function whitelist(address toWhitelist) external onlyOwner returns(bool) { require(!_whitelisted_users.contains(toWhitelist), "Address is already in whitelist"); _whitelisted_users.add(toWhitelist); return true; } function getWhitelist() external view returns(address[] memory) { return _whitelisted_users.values(); } /** * @notice Remove toUnWhitelist address from whitelist * @param toUnWhitelist The address of account to remove from whitelist * @return Whether or not the transaction succeeded */ function unwhitelist(address toUnWhitelist) external onlyOwner returns(bool) { require(_whitelisted_users.contains(toUnWhitelist), "Address is not in whitelist"); _whitelisted_users.remove(toUnWhitelist); return true; } /** * @notice Add toWhitelist list of addresses into whitelist * @param toWhitelist The addresses of accounts to add to the whitelist * @return Whether or not the transaction succeeded */ function whitelistMany(address[] memory toWhitelist) external onlyOwner returns(bool) { for (uint i = 0; i < toWhitelist.length; i++) { _whitelisted_users.add(toWhitelist[i]); } return true; } /** * @notice Remove toUnWhitelist list of addresses from the whitelist * @param toUnWhitelist The addresses of accounts to remove from the whitelist * @return Whether or not the transaction succeeded */ function unwhitelistMany(address[] memory toUnWhitelist) external onlyOwner returns(bool) { for (uint i = 0; i < toUnWhitelist.length; i++) { _whitelisted_users.remove(toUnWhitelist[i]); } return true; } /** * @notice Check if account whitelisted or not * @param account Account that we want to check * @return Whether or not the account in the whitelist */ function is_whitelisted(address account) public view returns(bool) { return _whitelisted_users.contains(account); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; ////import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; ////import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; ////import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; ////import "@openzeppelin/contracts/utils/Address.sol"; ////import "@openzeppelin/contracts/utils/Context.sol"; ////import "@openzeppelin/contracts/utils/Strings.sol"; ////import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @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; event Premint(address indexed _to, uint256 indexed start_id, uint256 indexed count); /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } function _mint_many(address to, uint256 first_tokenId, uint256 count) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(first_tokenId), "ERC721: token already minted"); uint256 last_id = first_tokenId + count; for (uint256 i = first_tokenId; i < last_id; i++) { _mint(to, i); } } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "@openzeppelin/contracts/utils/math/SafeMath.sol"; ////import "@openzeppelin/contracts/utils/Counters.sol"; ////import "./utility/ERC721.sol"; ////import "./DivinityCellWhitelist.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title Divinity Cell DivinityCellNFT Contract * @author Apriorit */ contract DivinityCellNFT is ERC721, Ownable { using SafeMath for uint256; using Counters for Counters.Counter; string base_url; address burner; address _minter; address proxyRegistryAddress; Counters.Counter _nextTokenId; /** * @notice Ensures that sender has burn rights */ modifier onlyBurner { require(msg.sender == burner, "DivinityCellNFT: Sender must have burner role"); _; } /** * @notice Ensures that sender has mint rights */ modifier onlyMinter { require(msg.sender == _minter, "DivinityCellNFT: Sender is not auction"); _; } /** * @param _name Token name * @param _symbol Token syumbol * @param token_url Token base URI * @param _proxyRegistryAddress OpenSea existring proxy registry. On Mainnet it is 0xa5409ec958c83c3f309868babaca7c86dcb077c1 */ constructor( string memory _name, string memory _symbol, string memory token_url, address _proxyRegistryAddress ) ERC721(_name, _symbol) { base_url = token_url; proxyRegistryAddress = _proxyRegistryAddress; } /** * @notice Check if account is owner of tokenId * @param account The address of account that we want to check * @param tokenId ID that we are checking * @return Whether or not the account is owner of tokenId */ function isTokenOwner(uint256 tokenId, address account) external view returns(bool) { return ERC721.ownerOf(tokenId) == account; } /** * @notice Mint token for recipient. Can be called only by _minter * @param recipient The address of account that will recieve token * @return Minted token ID */ function mintTo(address recipient) external onlyMinter returns(uint256) { uint256 currentTokenId = _nextTokenId.current(); _nextTokenId.increment(); _safeMint(recipient, currentTokenId); return currentTokenId; } /** * @notice Mint count tokens for account. Can be called only by contract owner * @param account The address of account that will recieve tokens * @param count Count of tokens to mint * @return Whether or not the transaction succeeded */ function premint(address account, uint256 count) external onlyMinter returns(bool) { uint256 currentTokenId = _nextTokenId.current(); ERC721._mint_many(account, currentTokenId, count); _nextTokenId._value += count; return true; } /** * @notice Set new _minter. Only owner can call this. Can be called only by contract owner * @param minter The address of new minter * @return Whether or not the transaction succeeded */ function registerMinterContract(address minter) external onlyOwner returns(bool){ _minter = minter; return true; } /** * @notice Get current last token ID + 1.(total amount) * @return Current amount of tokens */ function totalSupply() external view returns (uint256) { return _nextTokenId.current(); } /** * @notice Set new token URI. Can be called only by contract owner * @param baseUrl New token URL * @return Whether or not the transaction succeeded */ function setURI(string memory baseUrl) external onlyOwner returns (bool) { base_url = baseUrl; return true; } /** * @notice Get token URI * @return Current token URI */ function URI() public view returns (string memory) { return base_url; } /** * @notice Get _tokenId URI * @param _tokenId Token for which we want to get URI * @return Token URI */ function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(URI(), Strings.toString(_tokenId))); } /** * @notice Set new token burner. Can be called only by contract owner * @param newBurner New burner account * @return Whether or not the transaction succeeded */ function setBurner(address newBurner) external onlyOwner returns(bool) { burner = newBurner; return true; } /** * @notice Set new token burner. Can be called only by contract burner * @param tokenId Token to be burned * @return Whether or not the transaction succeeded */ function burn(uint256 tokenId) external onlyBurner returns(bool) { _burn(tokenId); return true; } /** * @notice Checks if token with given id exists * @param tokenId Checked token * @return Whether or not the token exists */ function exists(uint256 tokenId) external view returns(bool) { return ERC721._exists(tokenId); } /** * @notice Checks if operator can perform actions for owner * @param owner Tokens owner * @param operator Account that want perform actions for owner * @return Whether or not the transaction succeeded */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; ////import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "@openzeppelin/contracts/access/Ownable.sol"; ////import "@openzeppelin/contracts/security/Pausable.sol"; ////import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; ////import "@openzeppelin/contracts/utils/math/SafeMath.sol"; ////import "@openzeppelin/contracts/utils/math/Math.sol"; ////import "./DivinityCellNFT.sol"; /** * @title Divinity Cell DivinityCellMinter Contract * @notice Used for token presales * @author Apriorit */ contract DivinityCellMinter is ReentrancyGuard, Ownable, Pausable, DivinityCellWhitelist { using SafeMath for uint256; uint256 public tokens_limit; uint256 public tokens_this_sale = 0; uint32 public buy_limit; uint32 current_sale_id = 0; uint256 public mint_price; uint256 public sale_end_timestamp = 0; uint256 public sale_start_timestamp = 0; bool public is_sell_private = true; mapping(uint => mapping(address => uint)) bought_current_sell; address nft_contract; address whitelist_contract; /** * @notice Return bought count for the current sale * @param account Account that we want to check * @return Count of bought tokens for the current sale */ function boughtCurrentSale(address account) public view returns(uint) { return bought_current_sell[current_sale_id][account]; } /** * @notice If current sale is private, ensures that it still continues and sender is whitelisted */ modifier minterAllowed { if (is_sell_private) { require(block.timestamp < sale_end_timestamp, "DivinityCellAuction: Sale ended"); if (mint_price == 0) { require(DivinityCellWhitelist(whitelist_contract).is_whitelisted(msg.sender), "DivinityCellAuction: Account is not whitelisted"); } else { require(is_whitelisted(msg.sender), "DivinityCellAuction: Account is not whitelisted"); } } _; } /** * @notice Ensures that there is no other sale. If last sale was public, ensures that all tokens sold */ modifier onlyIfNoSale { require(sale_start_timestamp < block.timestamp, "DivinityCellAuction: New sale is about to start"); if (tokens_this_sale != 0) { require(sale_end_timestamp < block.timestamp, "DivinityCellAuction: Private sale still continues"); } _; } /** * @notice Sets new mint price for token mint. Can be called only by contract owner * @param nft address of NFT tokens contract, used for minting * @param nft address of whitelist contract, used for free minting * @param tokens_count Amount of tokens to be minted * @param initial_mint_price Initial minting price */ constructor(address nft, address whitelist, uint32 tokens_count, uint256 initial_mint_price) { tokens_limit = tokens_count; nft_contract = nft; whitelist_contract = whitelist; mint_price = initial_mint_price; } /** * @notice Send all eth collected by contract to _to account. Can be called only by contract owner * @param _to The account that will receive contract ETH * @return Whether or not the transaction succeeded */ function collectETH(address payable _to) external onlyOwner payable returns(bool) { (bool sent,) = _to.call{value: address(this).balance}(""); require(sent, "DivinityCellAuction: Failed to send Ether"); return true; } /** * @notice Sets new mint price for token mint. Can be called only by contract owner * @param new_mint_price New mint price * @return Whether or not the transaction succeeded */ function setPrice(uint256 new_mint_price) external onlyOwner returns(bool) { mint_price = new_mint_price; return true; } /** * @notice Starts private token sale. Can be called only by contract owner and only if other sale is not running * @param per_user_limitation Number of tokens that be bought by accounts this sale * @param tokens_count Number of tokens that will be sold this sale * @param new_sale_end_timestamp Sale start timestamp * @param new_sale_start_timestamp Sale end timestamp * @return Whether or not the transaction succeeded */ function startPrivateSale(uint32 per_user_limitation, uint256 tokens_count, uint256 new_sale_start_timestamp, uint256 new_sale_end_timestamp) external onlyOwner onlyIfNoSale returns(bool) { require(tokens_limit >= tokens_count, "DivinityCellAuction: Cant sell that much tokens"); require(new_sale_end_timestamp > block.timestamp, "DivinityCellAuction: Wrong timestamp passed"); require(new_sale_start_timestamp < new_sale_end_timestamp, "DivinityCellAuction: Start date should be less than end date"); require(per_user_limitation > 0, "DivinityCellAuction: Wrong limitation passed"); require(tokens_count > 0, "DivinityCellAuction: Wrong token count passed"); tokens_this_sale = tokens_count; buy_limit = per_user_limitation; sale_end_timestamp = new_sale_end_timestamp; sale_start_timestamp = new_sale_start_timestamp; current_sale_id += 1; is_sell_private = true; return true; } /** * @notice Changes sale start and end timestamps. * @param new_sale_end_timestamp New sale start timestamp * @param new_sale_start_timestamp New sale end timestamp * @return Whether or not the transaction succeeded */ function reschedulePrivateSale(uint256 new_sale_start_timestamp, uint256 new_sale_end_timestamp) external onlyOwner returns(bool) { require(new_sale_start_timestamp < new_sale_end_timestamp, "DivinityCellAuction: Start date should be less than end date"); require(tokens_this_sale > 0, "DivinityCellAuction: No tokens left"); sale_end_timestamp = new_sale_end_timestamp; sale_start_timestamp = new_sale_start_timestamp; return true; } /** * @notice Starts public token sale. Can be called only by contract owner and only if other sale is not running. * Unlike private one, this will end only after all tokens are bought * @param per_user_limitation Number of tokens that be bought by accounts this sale * @param new_sale_start_timestamp Sale start timestamp * @return Whether or not the transaction succeeded */ function startPublicSale(uint32 per_user_limitation, uint256 tokens_count, uint256 new_sale_start_timestamp) external onlyOwner onlyIfNoSale returns(bool) { require(tokens_limit >= tokens_count, "DivinityCellAuction: Cant sell that much tokens"); require(tokens_limit > 0, "DivinityCellAuction: Cant sell that much tokens"); require(per_user_limitation > 0, "DivinityCellAuction: Wrong limitation passed"); tokens_this_sale = tokens_count; sale_start_timestamp = new_sale_start_timestamp; buy_limit = per_user_limitation; current_sale_id += 1; is_sell_private = false; return true; } /** * @notice Changes sale start timestamp. * @param new_sale_start_timestamp New start end timestamp * @return Whether or not the transaction succeeded */ function reschedulePublicSale(uint256 new_sale_start_timestamp) external onlyOwner returns(bool) { require(sale_end_timestamp < block.timestamp, "DivinityCellAuction: Private sale continues"); require(tokens_this_sale > 0, "DivinityCellAuction: No tokens left"); sale_start_timestamp = new_sale_start_timestamp; return true; } /** * @notice pause current sale. Emits pause event */ function pause() public onlyOwner { Pausable._pause(); } /** * @notice unpause current sale. Emits unpause event */ function unpause() public onlyOwner { Pausable._unpause(); } /** * @notice Mints token for transaction sender. Can't be called if sale is not started * @return ID of minted token */ function mint(uint256 amount) public payable whenNotPaused minterAllowed nonReentrant returns(bool) { uint256 userLimit = getMintLimit(); require(userLimit > 0, "DivinityCellAuction: This recipient cant buy more tokens this sale"); require(amount > 0, "DivinityCellAuction: Invalid amount"); require(block.timestamp >= sale_start_timestamp, "DivinityCellAuction: Sale hasn't started yet"); uint256 count = Math.min(amount, userLimit); require(msg.value == mint_price * count, "DivinityCellAuction: Wrong amount of eth sent"); require(tokens_this_sale >= count, "DivinityCellAuction: Nothing to sell"); require(tokens_limit >= count, "DivinityCellAuction: Nothing to sell"); bool isMinted = DivinityCellNFT(nft_contract).premint(msg.sender, count); require(isMinted, "DivinityCellAuction: mint failed"); bought_current_sell[current_sale_id][msg.sender] += count; tokens_this_sale -= count; tokens_limit -= count; return isMinted; } /** * @notice Mint count tokens for account. Can be called only by contract owner * @param account The address of account that will recieve tokens * @param count Count of tokens to mint * @return Whether or not the transaction succeeded */ function premint(address account, uint256 count) external onlyOwner nonReentrant returns(bool) { require(tokens_limit >= count, "DivinityCellAuction: can't mint that much tokens"); bool is_premnt_successful = DivinityCellNFT(nft_contract).premint(account, count); require(is_premnt_successful, "DivinityCellAuction: premint was unsuccessful"); tokens_limit -= count; return is_premnt_successful; } // Helpers /** * @return amount of tokens available for current mint transaction */ function getMintLimit() internal view returns(uint) { if (is_sell_private) { uint bought = boughtCurrentSale(msg.sender); if (mint_price == 0) { if (bought > 0) { return 0; } uint256 holdings = DivinityCellNFT(nft_contract).balanceOf(msg.sender); if (holdings >= 5) { return 2; } if (holdings >= 3) { return 1; } return 0; } return buy_limit - bought; } return 5; } }
Starts public token sale. Can be called only by contract owner and only if other sale is not running. Unlike private one, this will end only after all tokens are bought per_user_limitation Number of tokens that be bought by accounts this sale new_sale_start_timestamp Sale start timestamp return Whether or not the transaction succeeded/
function startPublicSale(uint32 per_user_limitation, uint256 tokens_count, uint256 new_sale_start_timestamp) external onlyOwner onlyIfNoSale returns(bool) { require(tokens_limit >= tokens_count, "DivinityCellAuction: Cant sell that much tokens"); require(tokens_limit > 0, "DivinityCellAuction: Cant sell that much tokens"); require(per_user_limitation > 0, "DivinityCellAuction: Wrong limitation passed"); tokens_this_sale = tokens_count; sale_start_timestamp = new_sale_start_timestamp; buy_limit = per_user_limitation; current_sale_id += 1; is_sell_private = false; return true; }
76,821
pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../token/ERC20MintableDetailed.sol"; import "../../math/DecimalMath.sol"; /** * @title ERC20MultiDividendable * @dev Implements an ERC20Mintable token with a dividend distribution procedure for dividendTokens received * @notice This contract was implemented from algorithms proposed by Nick Johnson here: https://medium.com/@weka/dividend-bearing-tokens-on-ethereum-42d01c710657 */ contract ERC20MultiDividendable is ERC20MintableDetailed { using SafeMath for uint256; using DecimalMath for uint256; mapping(address => uint256) public dividendsPerToken; mapping(address => mapping(address => uint256) ) public lastDPT; mapping(uint256 => address) public dividendTokens; uint256 public tokenIndex; constructor( string memory name, string memory symbol, uint8 decimals ) ERC20MintableDetailed(name, symbol, decimals) public {} /** * @notice Send dividendTokens to this function in orther to increase the dividends pool * @dev Must have approved this contract to spend amount of dividendToken from msg.sender * @param amount The amount of dividendTokens to transfer from msg.sender to this contract * @param dividendToken The address of the token you wish to transfer to this contract */ function releaseDividends(uint256 amount, address dividendToken) external virtual { resolveDividendToken(dividendToken); IERC20(dividendToken).transferFrom(msg.sender, address(this), amount); uint256 releasedDividends = amount .divd(this.totalSupply(), this.decimals()); dividendsPerToken[dividendToken] = dividendsPerToken[dividendToken] .add(releasedDividends); } /** * @dev Function to update an account * @param account The account to update * @param dividendToken The address of the token you wish to transfer to this contract * @notice Will revert if account need not be updated */ function claimDividends( address payable account, address dividendToken ) public virtual returns (uint256) { uint owing = dividendsOwing(account, dividendToken); require( owing > 0, "Account need not be updated now for this dividend token." ); lastDPT[account][dividendToken] = dividendsPerToken[ dividendToken ]; IERC20(dividendToken).transfer(account, owing); return owing; } function resolveDividendToken( address dividendToken ) internal { for (uint256 i = 0; i < tokenIndex; i++){ if (dividendTokens[i] == dividendToken){ return; } } dividendTokens[tokenIndex] = dividendToken; tokenIndex = tokenIndex + 1; } /** * @dev Internal function to compute dividends owing to an account * @param account The account for which to compute the dividends * @param dividendToken The address of the token you wish to transfer to this contract */ function dividendsOwing( address account, address dividendToken ) internal view returns(uint256) { uint256 owedDividendsPerToken = dividendsPerToken[dividendToken] .subd(lastDPT[account][dividendToken]); return this.balanceOf(account) .muld(owedDividendsPerToken, this.decimals()); } }
Internal function to compute dividends owing to an account account The account for which to compute the dividends dividendToken The address of the token you wish to transfer to this contract/
function dividendsOwing( address account, address dividendToken ) internal view returns(uint256) { uint256 owedDividendsPerToken = dividendsPerToken[dividendToken] .subd(lastDPT[account][dividendToken]); return this.balanceOf(account) .muld(owedDividendsPerToken, this.decimals()); }
12,834,555
./full_match/1/0x0E56532AFb793750799eeaA0843da18eEa2d1B2c/sources/contracts/SnapshotAffirmationVerifier.sol
once an affirmation is created and used on-chain it can't be used again
function write(Write calldata _write, Affirmation[] calldata _affirmations) public whenNotPaused { bytes32 writeHash = getWriteHash(_write); uint256 numValidAffirmations = 0; for (uint256 i = 0; i < _affirmations.length; ++i) { Affirmation calldata affirmation = _affirmations[i]; bytes32 affirmationHash = keccak256(abi.encodePacked(writeHash, affirmation.signer)); require(affirmationHashRegistry[affirmationHash] == false, "Affirmation has already been received"); affirmationHashRegistry[affirmationHash] = true; require(verifyAffirmation(writeHash, affirmation) == true, "Affirmation doesn't have valid signature"); require(permissedAffirmers[affirmation.signer] == true, "Affirmer is not valid"); emit Affirmed(writeHash, affirmationHash, affirmation.signer, affirmation.salt, affirmation.signature ); numValidAffirmations++; } require(numValidAffirmations >= minimumQuorumAffirmations, "Minimum affirmations not met"); string[] memory keys = new string[](1); string[] memory texts = new string[](1); keys[0] = _write.key; texts[0] = _write.text; permissionedTokenMetadataRegistry.writeDocuments(_write.tokenId, keys, texts); }
4,828,579
./full_match/44787/0x245C7046c28bd74aE9241B62C0ce6A9D884B74E4/sources/project_/contracts/EmissionProtocol.sol
Add emission data as a tuple, for category we take 0 for Production and 1 for Transport Takes all relevant data from the emission struct to add new emission entry Impossible to register same order twice/
function addOrder( bytes32 _orderId, bytes32 _accountId, uint16 _year, bool _closed, Emission[] memory _emissionData ) public onlyAuthorized { require( _orderId != bytes32(0), "This orderId is invalid" ); require( orders[_orderId].id == bytes32(0), "This order already exists" ); orders[_orderId] = Order({ id: _orderId, accountId: _accountId, year: _year, closed: _closed, approved: false }); orderOwner[_orderId][msg.sender] = true; for(uint256 i = 0; i < _emissionData.length; i++){ emission[_orderId].push(_emissionData[i]); } emit newEmission( msg.sender, _accountId, _orderId ); }
13,270,704
./partial_match/1/0x9B85A79028d2aa510A01e7125Cdabc5688400a21/sources/contracts/UniversePairVault.sol
calculate token0/token1
function _mockReserve(PositionHelper.Position memory position) internal view returns(uint256 reserve0, uint256 reserve1){ (uint160 sqrtPrice, , , , , , ) = IUniswapV3Pool(position.poolAddress).slot0(); (reserve0, reserve1) = LiquidityAmounts.getAmountsForLiquidity( sqrtPrice, TickMath.getSqrtRatioAtTick(position.lowerTick), TickMath.getSqrtRatioAtTick(position.upperTick), 1E20); }
2,691,858
./full_match/5/0x1129549CE336FdBb4c8b114BD5053eee88f97b1d/sources/project:/contracts/BridgeBase.sol
token.burn(msg.sender, amount); instead of burning, transfer to admin account
function burn(address to, uint amount, uint nonce, bytes calldata signature) external { require(processedNonces[msg.sender][nonce] == false, 'transfer already processed'); processedNonces[msg.sender][nonce] = true; uint AmountwithFees = amount + fees; token.transferFrom(to, address(this), AmountwithFees); emit Transfer( msg.sender, to, amount, block.timestamp, nonce, signature, Step.Burn ); }
1,932,443
//SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import 'hardhat/console.sol'; import '@openzeppelin/contracts/token/ERC1155/ERC1155.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; contract Epoxy is ERC1155 { using SafeERC20 for IERC20; event Deposit(address indexed from, uint256 value); event Withdraw(address indexed from, uint256 value); error InvalidInput(string); error IsFrozen(uint256 id); error IsNotManager(address caller, uint256 id); // Epoxy base currency IERC20 public immutable currency; // Epoxy base fee uint256 public immutable fee; // Epoxy allows individual sets to override the standard URI mapping(uint256 => string) private _uris; // Epoxy allows unfrozen sets to be managed mapping(uint256 => address) private _managers; // tracks whether a tokenId has been used before mapping(uint256 => bool) private _created; constructor( string memory _baseUri, IERC20 _currency, uint256 _fee ) ERC1155(_baseUri) { currency = _currency; fee = _fee; } // mint an equal amount of stickers per-set to a list of addresses function mint( address[] memory tos, uint256[] memory ids, uint256[] memory amounts, string[] memory uris, bytes memory data, address _manager ) public { // _mintBatch will check that ids and amounts are identical, but we also want to check uris length if (ids.length != uris.length) revert InvalidInput('Epoxy: ids and uris length mismatch'); // for each sticker set... for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; // if the set is frozen, bail if (frozen(id)) revert IsFrozen(id); if (created(id)) { // if the set has already been created, check for manager permission to modify it if (_msgSender() != _managers[id]) revert IsNotManager(_msgSender(), id); } else { // otherwise, this block is only executed on the _creation_ of a set // mark the set as created _created[id] = true; // assign manager to the set if provided if (_manager != address(0)) { _managers[id] = _manager; } } // here, we have permission to modify the set // if the arguments provided a uri for this set, use it if (bytes(uris[i]).length > 0) { _uris[id] = uris[i]; } } // calculate value of the mint transaction uint256 value = fee * tos.length * sumArray(amounts); // transfer currency from sender to Epoxy currency.safeTransferFrom(_msgSender(), address(this), value); emit Deposit(_msgSender(), value); // for each address receiving stickers... for (uint256 t = 0; t < tos.length; t++) { // mint the same sticker sets and amounts _mintBatch(tos[t], ids, amounts, data); } } function burn( address account, uint256[] memory ids, uint256[] memory amounts ) public { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), 'ERC1155: caller is not owner nor approved' ); // calculate value of burn transaction uint256 value = fee * sumArray(amounts); currency.transfer(_msgSender(), value); emit Withdraw(_msgSender(), value); _burnBatch(account, ids, amounts); } // clears the manager for a given set, freezing future mints function freeze(uint256[] memory ids) public { setManager(ids, address(0)); } // sets the manager for a list of ids, given that the sender is the active manager of every set function setManager(uint256[] memory ids, address _manager) public { for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; // technically this line is redundant, but clarity over efficiency for now if (frozen(id)) revert IsFrozen(id); if (_msgSender() != _managers[id]) revert IsNotManager(_msgSender(), id); _managers[id] = _manager; } } // managers can change the uri of a set while unfrozen function setURI(uint256[] memory ids, string[] memory newUris) public { if (ids.length != newUris.length) revert InvalidInput('Epoxy: ids and uris length mismatch'); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; if (frozen(id)) revert IsFrozen(id); if (_msgSender() != _managers[id]) revert IsNotManager(_msgSender(), id); string memory newUri = newUris[i]; _uris[id] = newUri; emit URI(newUri, id); } } // returns the specific uri of a set or the Epoxy base uri function uri(uint256 id) public view override returns (string memory) { string memory specific = _uris[id]; if (bytes(specific).length > 0) return specific; return super.uri(id); } function created(uint256 id) public view returns (bool) { return _created[id]; } function frozen(uint256 id) public view returns (bool) { return created(id) && _managers[id] == address(0); } function manager(uint256 id) public view returns (address) { return _managers[id]; } function sumArray(uint256[] memory _arr) internal pure returns (uint256 sum_) { sum_ = 0; for (uint256 i = 0; i < _arr.length; i++) { sum_ += _arr[i]; } } }
calculate value of burn transaction
function burn( address account, uint256[] memory ids, uint256[] memory amounts ) public { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), 'ERC1155: caller is not owner nor approved' ); uint256 value = fee * sumArray(amounts); currency.transfer(_msgSender(), value); emit Withdraw(_msgSender(), value); _burnBatch(account, ids, amounts); }
7,216,259
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `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: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract 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()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts 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: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // 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: contracts/SOA.sol // Written by Andrew Olson pragma solidity >=0.7.0 <0.9.0; contract KergomMace is ERC721, Ownable, ReentrancyGuard { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriPrefix = ""; string public uriSuffix = ".json"; string public hiddenMetadataUri; uint256 public cost = 0.03 ether; uint256 public maxSupply = 500; uint256 public maxMintAmountPerTx = 2; uint256 public whitelistAddressLimit = 4; uint256 public publicAddressLimit = 20; bytes32 public merkleRoot; bool public paused = true; bool public revealed = false; bool public publicMint = false; mapping(address => uint256) public whitelistMintedBalance; mapping(address => uint256) public publicMintedBalance; constructor() ERC721("Kergom of Olrend Mace", "SOA") { setHiddenMetadataUri("ipfs://QmaDNdLLUAW41YK6YNgVxZ3HvHWxj9JvNN6Kb8CoC7JBa7/kergom.json"); } modifier mintCompliance(uint256 _mintAmount) { require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function totalSupply() public view returns (uint256) { return supply.current(); } function WhitelistMint(bytes32[] calldata _merkleProof, uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); require(publicMint == false, "The public mint is live."); require(msg.value >= cost * _mintAmount, "Insufficient funds."); uint256 whitelistMintedAmount = whitelistMintedBalance[msg.sender]; require(whitelistMintedAmount + _mintAmount <= whitelistAddressLimit, "max NFT per address exceeded"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid proof."); _whitelistMintLoop(msg.sender, _mintAmount); } function Mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(publicMint == true, "The whitelist mint is live."); require(!paused, "The contract is paused!"); require(msg.value >= cost * _mintAmount, "Insufficient funds!"); uint256 publicMintedAmount = publicMintedBalance[msg.sender]; require(publicMintedAmount + _mintAmount <= publicAddressLimit, "max NFT per address exceeded"); _publicMintLoop(msg.sender, _mintAmount); } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _publicMintLoop(_receiver, _mintAmount); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function setPublicMint(bool _state) public onlyOwner { publicMint = _state; } function setmerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } function setPublicAddressLimit(uint256 _limit) public onlyOwner { publicAddressLimit = _limit; } function setWhitelistAddressLimit(uint256 _limit) public onlyOwner { whitelistAddressLimit = _limit; } function setMaxSupply(uint256 _newSupply) public onlyOwner { maxSupply = _newSupply; } function _publicMintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { publicMintedBalance[msg.sender]++; supply.increment(); _safeMint(_receiver, supply.current()); } } function _whitelistMintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { whitelistMintedBalance[msg.sender]++; supply.increment(); _safeMint(_receiver, supply.current()); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } function withdraw() public onlyOwner nonReentrant { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
Emitted when the pause is triggered by `account`./ Emitted when the pause is lifted by `account`./ Initializes the contract in unpaused state./
function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; constructor() { _paused = false; }
11,676
pragma solidity ^0.4.17; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import './AtomicSwapRegistry.sol'; contract Exchange { using SafeMath for uint256; function Exchange(address _swapRegistry) public { swapRegistry = AtomicSwapRegistry(_swapRegistry); } /*****************************************************************/ /** * Blockchains to swap with (one of them with be useless, since exchange contract will be deployed to it) */ uint8 constant ETH = 1; uint8 constant ETH_KOVAN = 2; uint8 constant ETH_RINKEBY = 3; uint8 constant EOS = 4; uint8 constant BITCOIN = 5; enum OpType {BUY, SELL} struct Order { address initiator; uint currencyCount; uint priceInWei; OpType opType; bool isFilled; bytes32 hash; } /*****************************************************************/ AtomicSwapRegistry public swapRegistry; mapping (address => uint) public deposits; mapping(uint8 => Order[]) public orders; mapping(address => bytes32[]) hashes; /*****************************************************************/ /** * want to get some currency, give back ether */ function buy(uint8 _secondBlockchain, uint _currencyCount, uint _priceInWeiForOneUnit) public { //todo hardcoded only ether like decimals (18), const 1 ether = 10^18 uint totalEther = _priceInWeiForOneUnit.mul(_currencyCount).div(1 ether); require(totalEther <= deposits[msg.sender]); deposits[msg.sender] = deposits[msg.sender].sub(totalEther); bool isMatched = false; // todo optimization :( for(uint i=0; i<orders[_secondBlockchain].length; i++) { Order storage order = orders[_secondBlockchain][i]; if (order.opType==OpType.BUY) { continue; } require(hashes[msg.sender].length>0); //todo minimum price, since not we get first suitable price if (order.priceInWei > _priceInWeiForOneUnit) { continue; } if (order.isFilled) { continue; } if (order.currencyCount == _currencyCount) { bytes32 currentHash = getNextHash(msg.sender); swapRegistry.initiate.value(totalEther)(msg.sender, 7200, currentHash, order.initiator); order.isFilled = true; order.hash = currentHash; isMatched = true; break; } } if (!isMatched) { orders[_secondBlockchain].push( Order( msg.sender, _currencyCount, _priceInWeiForOneUnit, OpType.BUY, false, 0 ) ); } } /** * want to get ether, give back some currency */ function sell(uint8 _secondBlockchain, uint _currencyCount, uint _priceInWeiForOneUnit) public { require(_currencyCount > 0); require(_priceInWeiForOneUnit > 0); bool isMatched = false; for(uint i=0; i<orders[_secondBlockchain].length; i++) { Order storage order = orders[_secondBlockchain][i]; if (order.opType==OpType.SELL) { continue; } //todo minimum price, since not we get first suitable price if (order.priceInWei < _priceInWeiForOneUnit) { continue; } if (order.isFilled) { continue; } if (hashes[order.initiator].length==0) { continue; } if (order.currencyCount == _currencyCount) { uint totalEther = order.priceInWei.mul(_currencyCount).div(1 ether); bytes32 currentHash = getNextHash(order.initiator); swapRegistry.initiate.value(totalEther)(order.initiator, 7200, currentHash, msg.sender); order.isFilled = true; order.hash = currentHash; isMatched = true; break; } } if (!isMatched) { orders[_secondBlockchain].push( Order( msg.sender, _currencyCount, _priceInWeiForOneUnit, OpType.SELL, false, 0 ) ); } } /*****************************************************************/ function myHashesCount() view public returns (uint) { return hashes[msg.sender].length; } function addHash(bytes32 _hash) public { if (_hash != 0) { //todo check that hash has been never used hashes[msg.sender].push(_hash); } } function getNextHash(address _addr) internal returns (bytes32 result) { assert(hashes[_addr].length > 0); result = hashes[_addr][ hashes[_addr].length-1 ]; hashes[_addr].length -= 1; } /*****************************************************************/ function myDeposit() view public returns (uint) { return deposits[msg.sender]; } function deposit() public payable { deposits[msg.sender] += msg.value; } function withdraw(uint _amount) public { require(deposits[msg.sender] >= _amount); deposits[msg.sender] -= _amount; msg.sender.transfer(_amount); } }
want to get some currency, give back ether/todo hardcoded only ether like decimals (18), const 1 ether = 10^18 todo optimization :(todo minimum price, since not we get first suitable price
function buy(uint8 _secondBlockchain, uint _currencyCount, uint _priceInWeiForOneUnit) public { uint totalEther = _priceInWeiForOneUnit.mul(_currencyCount).div(1 ether); require(totalEther <= deposits[msg.sender]); deposits[msg.sender] = deposits[msg.sender].sub(totalEther); bool isMatched = false; for(uint i=0; i<orders[_secondBlockchain].length; i++) { Order storage order = orders[_secondBlockchain][i]; if (order.opType==OpType.BUY) { continue; } require(hashes[msg.sender].length>0); if (order.priceInWei > _priceInWeiForOneUnit) { continue; } if (order.isFilled) { continue; } if (order.currencyCount == _currencyCount) { bytes32 currentHash = getNextHash(msg.sender); swapRegistry.initiate.value(totalEther)(msg.sender, 7200, currentHash, order.initiator); order.isFilled = true; order.hash = currentHash; isMatched = true; break; } } if (!isMatched) { orders[_secondBlockchain].push( Order( msg.sender, _currencyCount, _priceInWeiForOneUnit, OpType.BUY, false, 0 ) ); } }
13,132,068
./full_match/4/0xB62167c75B69F562Dcb160915Ec7F9c845DeDA0c/sources/PizzaNft.sol
for developer walletfor creator wallet
function calculateRarity() internal { Pizzas memory pizzaDetails; uint256 lowestRarity = 100; uint256 lowestRarityId = 0; uint256 rarityTotal = 0; uint256 pizzaId; address pizzaOwner; uint256 ingId; uint256[] memory meats; uint256[] memory toppings; bool ingAvailable = false; uint256 totalIngredientsNow = 3; for(uint256 i = 0; i < totalPizzas; i++) { pizzaId = pizzaIds[i]; pizzaDetails = pizzasList[pizzaId]; if(!pizzaDetails.unbaked) { if(pizzaDetails.base > 0) { ingId = userIngToIngIds[pizzaDetails.base]; rarityTotal = rarityTotal+ ingredientRarityPercent[ingId]; } if(pizzaDetails.sauce > 0) { ingId = userIngToIngIds[pizzaDetails.sauce]; rarityTotal = rarityTotal + ingredientRarityPercent[ingId]; } else { rarityTotal = rarityTotal + ingredientRarityPercent[5000]; } if(pizzaDetails.cheese > 0) { ingId = userIngToIngIds[pizzaDetails.cheese]; rarityTotal = rarityTotal + ingredientRarityPercent[ingId]; } else { rarityTotal = rarityTotal + ingredientRarityPercent[5001]; } for(uint256 x = 0; x < meatIngredients.length; x++) { totalIngredientsNow++; ingAvailable = false; meats = pizzaDetails.meats; for(uint256 y=0; y < meats.length; y++) { ingId = userIngToIngIds[meats[y]]; if(ingId == meatIngredients[x]) { ingAvailable = true; } } if(ingAvailable) { rarityTotal = rarityTotal + ingredientRarityPercent[meatIngredients[x]]; } else { rarityTotal = rarityTotal + hundered.sub(ingredientRarityPercent[meatIngredients[x]]); } } for(uint256 x = 0; x < toppingIngredients.length; x++) { totalIngredientsNow++; ingAvailable = false; toppings = pizzaDetails.toppings; for(uint256 y=0; y < toppings.length; y++) { ingId = userIngToIngIds[toppings[y]]; if(ingId == toppingIngredients[x]) { ingAvailable = true; } } if(ingAvailable) { rarityTotal = rarityTotal + ingredientRarityPercent[toppingIngredients[x]]; } else { rarityTotal = rarityTotal + hundered.sub(ingredientRarityPercent[toppingIngredients[x]]); } } rarityTotal = rarityTotal.div(totalIngredientsNow); if(rarityTotal < lowestRarity) { lowestRarity = rarityTotal; lowestRarityId = pizzaId; pizzaOwner = pizzaDetails.from; } pizzaDetails.calculated = true; pizzaDetails.rarity; pizzasList[pizzaId] = pizzaDetails; } } if(pizzaOwner != address(0)) { uint256 totalContractBalance = address(this).balance; uint256 availableContractBalance = totalContractBalance.sub(totalClaimable); uint256 rarityRewardShare = availableContractBalance.mul(RARITY_REWARD_SHARE).div(hundered); totalClaimable+=rarityRewardShare; RarityReward memory rarityReward = RarityReward( pizzaOwner, false, rarityRewardShare, rarityRewardShare, lowestRarityId, lowestRarity ); rarityRewardsList[totalRarityRewards] = rarityReward; rarityRewardsIds[totalRarityRewards] = lowestRarityId; uint256[] storage userRareNfts = rarityRewardOwnerIds[pizzaOwner]; userRareNfts.push(totalRarityRewards); rarityRewardOwnerIds[pizzaOwner] = userRareNfts; totalRarityRewards+=1; uint256 currentClaimable = claimableList[developerFundWallet]; currentClaimable += rarityRewardShare; claimableList[developerFundWallet] = currentClaimable; totalClaimable += currentClaimable; currentClaimable = claimableList[owner()]; currentClaimable += rarityRewardShare; claimableList[owner()] = currentClaimable; totalClaimable += currentClaimable; } }
12,273,547
pragma solidity 0.5.11; interface DharmaSmartWalletInterface { enum ActionType { Cancel, SetUserSigningKey, Generic, GenericAtomicBatch, SAIWithdrawal, USDCWithdrawal, ETHWithdrawal, SetEscapeHatch, RemoveEscapeHatch, DisableEscapeHatch, DAIWithdrawal, _ELEVEN, _TWELVE, _THIRTEEN, _FOURTEEN, _FIFTEEN, _SIXTEEN, _SEVENTEEN, _EIGHTEEN, _NINETEEN, _TWENTY } function getVersion() external pure returns (uint256 version); } interface DharmaSmartWalletFactoryV1Interface { function newSmartWallet( address userSigningKey ) external returns (address wallet); function getNextSmartWallet( address userSigningKey ) external view returns (address wallet); } interface DharmaKeyRingFactoryV2Interface { function newKeyRing( address userSigningKey, address targetKeyRing ) external returns (address keyRing); function getNextKeyRing( address userSigningKey ) external view returns (address targetKeyRing); } interface DharmaKeyRegistryInterface { function getKeyForUser(address account) external view returns (address key); } contract DharmaDeploymentHelper { DharmaSmartWalletFactoryV1Interface internal constant _WALLET_FACTORY = ( DharmaSmartWalletFactoryV1Interface( 0xfc00C80b0000007F73004edB00094caD80626d8D ) ); DharmaKeyRingFactoryV2Interface internal constant _KEYRING_FACTORY = ( DharmaKeyRingFactoryV2Interface( 0x2484000059004afB720000dc738434fA6200F49D ) ); DharmaKeyRegistryInterface internal constant _KEY_REGISTRY = ( DharmaKeyRegistryInterface( 0x000000000D38df53b45C5733c7b34000dE0BDF52 ) ); address internal constant beacon = 0x000000000026750c571ce882B17016557279ADaa; // Use the smart wallet instance runtime code hash to verify expected targets. bytes32 internal constant _SMART_WALLET_INSTANCE_RUNTIME_HASH = bytes32( 0xe25d4f154acb2394ee6c18d64fb5635959ba063d57f83091ec9cf34be16224d7 ); // The keyring instance runtime code hash is used to verify expected targets. bytes32 internal constant _KEY_RING_INSTANCE_RUNTIME_HASH = bytes32( 0xb15b24278e79e856d35b262e76ff7d3a759b17e625ff72adde4116805af59648 ); // Deploy a smart wallet and call it with arbitrary data. function deployWalletAndCall( address userSigningKey, // the key ring address smartWallet, bytes calldata data ) external returns (bool ok, bytes memory returnData) { _deployNewSmartWalletIfNeeded(userSigningKey, smartWallet); (ok, returnData) = smartWallet.call(data); } // Deploy a key ring and a smart wallet, then call the smart wallet // with arbitrary data. function deployKeyRingAndWalletAndCall( address initialSigningKey, // the initial key on the keyring address keyRing, address smartWallet, bytes calldata data ) external returns (bool ok, bytes memory returnData) { _deployNewKeyRingIfNeeded(initialSigningKey, keyRing); _deployNewSmartWalletIfNeeded(keyRing, smartWallet); (ok, returnData) = smartWallet.call(data); } // Get an actionID for the first action on a smart wallet before it // has been deployed. // no argument: empty string - abi.encode(); // one argument, like setUserSigningKey: abi.encode(argument) // withdrawals: abi.encode(amount, recipient) // generics: abi.encode(to, data) // generic batch: abi.encode(calls) -> array of {address to, bytes data} function getInitialActionID( address smartWallet, address initialUserSigningKey, // the key ring DharmaSmartWalletInterface.ActionType actionType, uint256 minimumActionGas, bytes calldata arguments ) external view returns (bytes32 actionID) { actionID = keccak256( abi.encodePacked( smartWallet, _getVersion(), initialUserSigningKey, _KEY_REGISTRY.getKeyForUser(smartWallet), uint256(0), // nonce starts at 0 minimumActionGas, actionType, arguments ) ); } function _deployNewKeyRingIfNeeded( address initialSigningKey, address expectedKeyRing ) internal returns (address keyRing) { // Only deploy if a smart wallet doesn't already exist at expected address. bytes32 hash; assembly { hash := extcodehash(expectedKeyRing) } if (hash != _KEY_RING_INSTANCE_RUNTIME_HASH) { require( _KEYRING_FACTORY.getNextKeyRing(initialSigningKey) == expectedKeyRing, "Key ring to be deployed does not match expected key ring." ); keyRing = _KEYRING_FACTORY.newKeyRing(initialSigningKey, expectedKeyRing); } else { // Note: the key ring at the expected address may have been modified so that // the supplied user signing key is no longer a valid key - therefore, treat // this helper as a way to protect against race conditions, not as a primary // mechanism for interacting with key ring contracts. keyRing = expectedKeyRing; } } function _deployNewSmartWalletIfNeeded( address userSigningKey, // the key ring address expectedSmartWallet ) internal returns (address smartWallet) { // Only deploy if a smart wallet doesn't already exist at expected address. bytes32 hash; assembly { hash := extcodehash(expectedSmartWallet) } if (hash != _SMART_WALLET_INSTANCE_RUNTIME_HASH) { require( _WALLET_FACTORY.getNextSmartWallet(userSigningKey) == expectedSmartWallet, "Smart wallet to be deployed does not match expected smart wallet." ); smartWallet = _WALLET_FACTORY.newSmartWallet(userSigningKey); } else { // Note: the smart wallet at the expected address may have been modified // so that the supplied user signing key is no longer a valid key. // Therefore, treat this helper as a way to protect against race // conditions, not as a primary mechanism for interacting with smart // wallet contracts. smartWallet = expectedSmartWallet; } } function _getVersion() internal view returns (uint256 version) { (, bytes memory data) = beacon.staticcall(""); address implementation = abi.decode(data, (address)); version = DharmaSmartWalletInterface(implementation).getVersion(); } }
Only deploy if a smart wallet doesn't already exist at expected address. Note: the key ring at the expected address may have been modified so that the supplied user signing key is no longer a valid key - therefore, treat this helper as a way to protect against race conditions, not as a primary mechanism for interacting with key ring contracts.
function _deployNewKeyRingIfNeeded( address initialSigningKey, address expectedKeyRing ) internal returns (address keyRing) { bytes32 hash; if (hash != _KEY_RING_INSTANCE_RUNTIME_HASH) { require( _KEYRING_FACTORY.getNextKeyRing(initialSigningKey) == expectedKeyRing, "Key ring to be deployed does not match expected key ring." ); keyRing = _KEYRING_FACTORY.newKeyRing(initialSigningKey, expectedKeyRing); keyRing = expectedKeyRing; } }
917,719
pragma solidity ^0.8.7; import "./ERC721A.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract nounmfers is ERC721A, Ownable, ReentrancyGuard { using Address for address; using SafeMath for uint256; using Strings for uint256; string public baseURI; uint256 public mintPrice = 0.02 ether; uint256 public maxSupply = 6969; uint256 public freeMintAmount = 1000; bool public publicSaleLive; uint256 public maxMint = 10; mapping(address => uint256) addressMinted; constructor() ERC721A("NoundMfs", "NMF") {} function freeMint(uint256 amount) external payable nonReentrant { require(publicSaleLive, "Public mint is not live"); require(totalSupply() + amount <= freeMintAmount, "Free Mint is Over"); require(msg.value == 0, "Must provide exact required ETH"); addressMinted[msg.sender] += amount; require(addressMinted[msg.sender] <= maxMint, "Max Mint per wallet is 10"); _safeMint(msg.sender, amount); } function mint(uint256 amount) external payable nonReentrant { require(publicSaleLive, "Public mint is not live"); require(amount > 0, "Amount to mint is 0"); require(totalSupply()+ amount <= maxSupply, "Sold out!"); require(msg.value == mintPrice.mul(amount), "Must provide exact required ETH"); addressMinted[msg.sender] += amount; require(addressMinted[msg.sender] <= maxMint, "Max Mint per wallet is 10"); _safeMint(msg.sender, amount); } function changeMaxMint(uint56 _new) external onlyOwner { maxMint = _new; } function setPublicSale(bool _status) external onlyOwner { publicSaleLive = _status; } function setFreeMintAmount(uint256 _new) external onlyOwner { freeMintAmount = _new; } function setMintPrice(uint256 _mintPrice) external onlyOwner { mintPrice = _mintPrice; } function setbaseURI(string memory _baseURI) external onlyOwner { baseURI = _baseURI; } function withdraw() external onlyOwner nonReentrant { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Failed to send ether"); } function devMint(uint256 amount) external onlyOwner { require(totalSupply() + amount <= maxSupply, "Sold out!"); _safeMint(msg.sender, amount); } function walletOfOwner(address address_) public virtual view returns (uint256[] memory) { uint256 _balance = balanceOf(address_); uint256[] memory _tokens = new uint256[] (_balance); uint256 _index; uint256 _loopThrough = totalSupply(); for (uint256 i = 0; i < _loopThrough; i++) { bool _exists = _exists(i); if (_exists) { if (ownerOf(i) == address_) { _tokens[_index] = i; _index++; } } else if (!_exists && _tokens[_balance - 1] == 0) { _loopThrough++; } } return _tokens; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token'); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/utils/Context.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). * * Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal currentIndex; // 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721A: global index out of bounds'); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('ERC721A: unable to get token of owner by index'); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), 'ERC721A: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'ERC721A: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } /** * 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) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); unchecked { for (uint256 curr = tokenId; curr >= 0; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert('ERC721A: unable to determine the owner of token'); } /** * @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) { 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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, 'ERC721A: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721A: approve caller is not owner nor approved for all' ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'ERC721A: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'ERC721A: 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 { _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 override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } 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; require(to != address(0), 'ERC721A: mint to the zero address'); require(quantity != 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1 unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } 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 || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _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)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * 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`. */ 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. * * 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` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
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./ Overflows are incredibly unrealistic. balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2128) - 1 updatedIndex overflows if currentIndex + quantity > 1.56e77 (2256) - 1
function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); require(quantity != 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); }
88,146
pragma solidity ^0.8.4; library BytesUtils { /* * @dev Returns the keccak-256 hash of a byte range. * @param self The byte string to hash. * @param offset The position to start hashing at. * @param len The number of bytes to hash. * @return The hash of the byte range. */ function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) { require(offset + len <= self.length); assembly { ret := keccak256(add(add(self, 32), offset), len) } } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. * @param self The first bytes to compare. * @param other The second bytes to compare. * @return The result of the comparison. */ function compare(bytes memory self, bytes memory other) internal pure returns (int) { return compare(self, 0, self.length, other, 0, other.length); } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first bytes to compare. * @param offset The offset of self. * @param len The length of self. * @param other The second bytes to compare. * @param otheroffset The offset of the other string. * @param otherlen The length of the other string. * @return The result of the comparison. */ function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) { uint shortest = len; if (otherlen < len) shortest = otherlen; uint selfptr; uint otherptr; assembly { selfptr := add(self, add(offset, 32)) otherptr := add(other, add(otheroffset, 32)) } for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask; if (shortest > 32) { mask = type(uint256).max; } else { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } int diff = int(a & mask) - int(b & mask); if (diff != 0) return diff; } selfptr += 32; otherptr += 32; } return int(len) - int(otherlen); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @param len The number of bytes to compare * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) { return keccak(self, offset, len) == keccak(other, otherOffset, len); } /* * @dev Returns true if the two byte ranges are equal with offsets. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) { return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset); } /* * @dev Compares a range of 'self' to all of 'other' and returns True iff * they are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) { return self.length >= offset + other.length && equals(self, offset, other, 0, other.length); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, bytes memory other) internal pure returns(bool) { return self.length == other.length && equals(self, 0, other, 0, self.length); } /* * @dev Returns the 8-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 8 bits of the string, interpreted as an integer. */ function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) { return uint8(self[idx]); } /* * @dev Returns the 16-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 16 bits of the string, interpreted as an integer. */ function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) { require(idx + 2 <= self.length); assembly { ret := and(mload(add(add(self, 2), idx)), 0xFFFF) } } /* * @dev Returns the 32-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bits of the string, interpreted as an integer. */ function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) { require(idx + 4 <= self.length); assembly { ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) { require(idx + 32 <= self.length); assembly { ret := mload(add(add(self, 32), idx)) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) { require(idx + 20 <= self.length); assembly { ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000) } } /* * @dev Returns the n byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes. * @param len The number of bytes. * @return The specified 32 bytes of the string. */ function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) { require(len <= 32); require(idx + len <= self.length); assembly { let mask := not(sub(exp(256, sub(32, len)), 1)) ret := and(mload(add(add(self, 32), idx)), mask) } } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes unchecked { uint mask = (256 ** (32 - len)) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } /* * @dev Copies a substring into a new byte string. * @param self The byte string to copy from. * @param offset The offset to start copying at. * @param len The number of bytes to copy. */ function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) { require(offset + len <= self.length); bytes memory ret = new bytes(len); uint dest; uint src; assembly { dest := add(ret, 32) src := add(add(self, 32), offset) } memcpy(dest, src, len); return ret; } // Maps characters from 0x30 to 0x7A to their base32 values. // 0xFF represents invalid characters in that range. bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'; /** * @dev Decodes unpadded base32 data of up to one word in length. * @param self The data to decode. * @param off Offset into the string to start at. * @param len Number of characters to decode. * @return The decoded data, left aligned. */ function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) { require(len <= 52); uint ret = 0; uint8 decoded; for(uint i = 0; i < len; i++) { bytes1 char = self[off + i]; require(char >= 0x30 && char <= 0x7A); decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]); require(decoded <= 0x20); if(i == len - 1) { break; } ret = (ret << 5) | decoded; } uint bitlen = len * 5; if(len % 8 == 0) { // Multiple of 8 characters, no padding ret = (ret << 5) | decoded; } else if(len % 8 == 2) { // Two extra characters - 1 byte ret = (ret << 3) | (decoded >> 2); bitlen -= 2; } else if(len % 8 == 4) { // Four extra characters - 2 bytes ret = (ret << 1) | (decoded >> 4); bitlen -= 4; } else if(len % 8 == 5) { // Five extra characters - 3 bytes ret = (ret << 4) | (decoded >> 1); bitlen -= 1; } else if(len % 8 == 7) { // Seven extra characters - 4 bytes ret = (ret << 2) | (decoded >> 3); bitlen -= 3; } else { revert(); } return bytes32(ret << (256 - bitlen)); } } pragma solidity ^0.8.4; /** * @dev An interface for contracts implementing a DNSSEC (signing) algorithm. */ interface Algorithm { /** * @dev Verifies a signature. * @param key The public key to verify with. * @param data The signed data to verify. * @param signature The signature to verify. * @return True iff the signature is valid. */ function verify(bytes calldata key, bytes calldata data, bytes calldata signature) external virtual view returns (bool); } pragma solidity ^0.8.4; /** * @title EllipticCurve * * @author Tilman Drerup; * * @notice Implements elliptic curve math; Parametrized for SECP256R1. * * Includes components of code by Andreas Olofsson, Alexander Vlasov * (https://github.com/BANKEX/CurveArithmetics), and Avi Asayag * (https://github.com/orbs-network/elliptic-curve-solidity) * * Source: https://github.com/tdrerup/elliptic-curve-solidity * * @dev NOTE: To disambiguate public keys when verifying signatures, activate * condition 'rs[1] > lowSmax' in validateSignature(). */ contract EllipticCurve { // Set parameters for curve. uint constant a = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC; uint constant b = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B; uint constant gx = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296; uint constant gy = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5; uint constant p = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF; uint constant n = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551; uint constant lowSmax = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0; /** * @dev Inverse of u in the field of modulo m. */ function inverseMod(uint u, uint m) internal pure returns (uint) { unchecked { if (u == 0 || u == m || m == 0) return 0; if (u > m) u = u % m; int t1; int t2 = 1; uint r1 = m; uint r2 = u; uint q; while (r2 != 0) { q = r1 / r2; (t1, t2, r1, r2) = (t2, t1 - int(q) * t2, r2, r1 - q * r2); } if (t1 < 0) return (m - uint(-t1)); return uint(t1); } } /** * @dev Transform affine coordinates into projective coordinates. */ function toProjectivePoint(uint x0, uint y0) internal pure returns (uint[3] memory P) { P[2] = addmod(0, 1, p); P[0] = mulmod(x0, P[2], p); P[1] = mulmod(y0, P[2], p); } /** * @dev Add two points in affine coordinates and return projective point. */ function addAndReturnProjectivePoint(uint x1, uint y1, uint x2, uint y2) internal pure returns (uint[3] memory P) { uint x; uint y; (x, y) = add(x1, y1, x2, y2); P = toProjectivePoint(x, y); } /** * @dev Transform from projective to affine coordinates. */ function toAffinePoint(uint x0, uint y0, uint z0) internal pure returns (uint x1, uint y1) { uint z0Inv; z0Inv = inverseMod(z0, p); x1 = mulmod(x0, z0Inv, p); y1 = mulmod(y0, z0Inv, p); } /** * @dev Return the zero curve in projective coordinates. */ function zeroProj() internal pure returns (uint x, uint y, uint z) { return (0, 1, 0); } /** * @dev Return the zero curve in affine coordinates. */ function zeroAffine() internal pure returns (uint x, uint y) { return (0, 0); } /** * @dev Check if the curve is the zero curve. */ function isZeroCurve(uint x0, uint y0) internal pure returns (bool isZero) { if(x0 == 0 && y0 == 0) { return true; } return false; } /** * @dev Check if a point in affine coordinates is on the curve. */ function isOnCurve(uint x, uint y) internal pure returns (bool) { if (0 == x || x == p || 0 == y || y == p) { return false; } uint LHS = mulmod(y, y, p); // y^2 uint RHS = mulmod(mulmod(x, x, p), x, p); // x^3 if (a != 0) { RHS = addmod(RHS, mulmod(x, a, p), p); // x^3 + a*x } if (b != 0) { RHS = addmod(RHS, b, p); // x^3 + a*x + b } return LHS == RHS; } /** * @dev Double an elliptic curve point in projective coordinates. See * https://www.nayuki.io/page/elliptic-curve-point-addition-in-projective-coordinates */ function twiceProj(uint x0, uint y0, uint z0) internal pure returns (uint x1, uint y1, uint z1) { uint t; uint u; uint v; uint w; if(isZeroCurve(x0, y0)) { return zeroProj(); } u = mulmod(y0, z0, p); u = mulmod(u, 2, p); v = mulmod(u, x0, p); v = mulmod(v, y0, p); v = mulmod(v, 2, p); x0 = mulmod(x0, x0, p); t = mulmod(x0, 3, p); z0 = mulmod(z0, z0, p); z0 = mulmod(z0, a, p); t = addmod(t, z0, p); w = mulmod(t, t, p); x0 = mulmod(2, v, p); w = addmod(w, p-x0, p); x0 = addmod(v, p-w, p); x0 = mulmod(t, x0, p); y0 = mulmod(y0, u, p); y0 = mulmod(y0, y0, p); y0 = mulmod(2, y0, p); y1 = addmod(x0, p-y0, p); x1 = mulmod(u, w, p); z1 = mulmod(u, u, p); z1 = mulmod(z1, u, p); } /** * @dev Add two elliptic curve points in projective coordinates. See * https://www.nayuki.io/page/elliptic-curve-point-addition-in-projective-coordinates */ function addProj(uint x0, uint y0, uint z0, uint x1, uint y1, uint z1) internal pure returns (uint x2, uint y2, uint z2) { uint t0; uint t1; uint u0; uint u1; if (isZeroCurve(x0, y0)) { return (x1, y1, z1); } else if (isZeroCurve(x1, y1)) { return (x0, y0, z0); } t0 = mulmod(y0, z1, p); t1 = mulmod(y1, z0, p); u0 = mulmod(x0, z1, p); u1 = mulmod(x1, z0, p); if (u0 == u1) { if (t0 == t1) { return twiceProj(x0, y0, z0); } else { return zeroProj(); } } (x2, y2, z2) = addProj2(mulmod(z0, z1, p), u0, u1, t1, t0); } /** * @dev Helper function that splits addProj to avoid too many local variables. */ function addProj2(uint v, uint u0, uint u1, uint t1, uint t0) private pure returns (uint x2, uint y2, uint z2) { uint u; uint u2; uint u3; uint w; uint t; t = addmod(t0, p-t1, p); u = addmod(u0, p-u1, p); u2 = mulmod(u, u, p); w = mulmod(t, t, p); w = mulmod(w, v, p); u1 = addmod(u1, u0, p); u1 = mulmod(u1, u2, p); w = addmod(w, p-u1, p); x2 = mulmod(u, w, p); u3 = mulmod(u2, u, p); u0 = mulmod(u0, u2, p); u0 = addmod(u0, p-w, p); t = mulmod(t, u0, p); t0 = mulmod(t0, u3, p); y2 = addmod(t, p-t0, p); z2 = mulmod(u3, v, p); } /** * @dev Add two elliptic curve points in affine coordinates. */ function add(uint x0, uint y0, uint x1, uint y1) internal pure returns (uint, uint) { uint z0; (x0, y0, z0) = addProj(x0, y0, 1, x1, y1, 1); return toAffinePoint(x0, y0, z0); } /** * @dev Double an elliptic curve point in affine coordinates. */ function twice(uint x0, uint y0) internal pure returns (uint, uint) { uint z0; (x0, y0, z0) = twiceProj(x0, y0, 1); return toAffinePoint(x0, y0, z0); } /** * @dev Multiply an elliptic curve point by a 2 power base (i.e., (2^exp)*P)). */ function multiplyPowerBase2(uint x0, uint y0, uint exp) internal pure returns (uint, uint) { uint base2X = x0; uint base2Y = y0; uint base2Z = 1; for(uint i = 0; i < exp; i++) { (base2X, base2Y, base2Z) = twiceProj(base2X, base2Y, base2Z); } return toAffinePoint(base2X, base2Y, base2Z); } /** * @dev Multiply an elliptic curve point by a scalar. */ function multiplyScalar(uint x0, uint y0, uint scalar) internal pure returns (uint x1, uint y1) { if(scalar == 0) { return zeroAffine(); } else if (scalar == 1) { return (x0, y0); } else if (scalar == 2) { return twice(x0, y0); } uint base2X = x0; uint base2Y = y0; uint base2Z = 1; uint z1 = 1; x1 = x0; y1 = y0; if(scalar%2 == 0) { x1 = y1 = 0; } scalar = scalar >> 1; while(scalar > 0) { (base2X, base2Y, base2Z) = twiceProj(base2X, base2Y, base2Z); if(scalar%2 == 1) { (x1, y1, z1) = addProj(base2X, base2Y, base2Z, x1, y1, z1); } scalar = scalar >> 1; } return toAffinePoint(x1, y1, z1); } /** * @dev Multiply the curve's generator point by a scalar. */ function multipleGeneratorByScalar(uint scalar) internal pure returns (uint, uint) { return multiplyScalar(gx, gy, scalar); } /** * @dev Validate combination of message, signature, and public key. */ function validateSignature(bytes32 message, uint[2] memory rs, uint[2] memory Q) internal pure returns (bool) { // To disambiguate between public key solutions, include comment below. if(rs[0] == 0 || rs[0] >= n || rs[1] == 0) {// || rs[1] > lowSmax) return false; } if (!isOnCurve(Q[0], Q[1])) { return false; } uint x1; uint x2; uint y1; uint y2; uint sInv = inverseMod(rs[1], n); (x1, y1) = multiplyScalar(gx, gy, mulmod(uint(message), sInv, n)); (x2, y2) = multiplyScalar(Q[0], Q[1], mulmod(rs[0], sInv, n)); uint[3] memory P = addAndReturnProjectivePoint(x1, y1, x2, y2); if (P[2] == 0) { return false; } uint Px = inverseMod(P[2], p); Px = mulmod(P[0], mulmod(Px, Px, p), p); return Px % n == rs[0]; } } pragma solidity ^0.8.4; import "./Algorithm.sol"; import "./EllipticCurve.sol"; import "../BytesUtils.sol"; contract P256SHA256Algorithm is Algorithm, EllipticCurve { using BytesUtils for *; /** * @dev Verifies a signature. * @param key The public key to verify with. * @param data The signed data to verify. * @param signature The signature to verify. * @return True iff the signature is valid. */ function verify(bytes calldata key, bytes calldata data, bytes calldata signature) external override view returns (bool) { return validateSignature(sha256(data), parseSignature(signature), parseKey(key)); } function parseSignature(bytes memory data) internal pure returns (uint256[2] memory) { require(data.length == 64, "Invalid p256 signature length"); return [uint256(data.readBytes32(0)), uint256(data.readBytes32(32))]; } function parseKey(bytes memory data) internal pure returns (uint256[2] memory) { require(data.length == 68, "Invalid p256 key length"); return [uint256(data.readBytes32(4)), uint256(data.readBytes32(36))]; } }
Multiply an elliptic curve point by a 2 power base (i.e., (2^exp)P))./
function multiplyPowerBase2(uint x0, uint y0, uint exp) internal pure returns (uint, uint) { uint base2X = x0; uint base2Y = y0; uint base2Z = 1; for(uint i = 0; i < exp; i++) { (base2X, base2Y, base2Z) = twiceProj(base2X, base2Y, base2Z); } return toAffinePoint(base2X, base2Y, base2Z); }
10,120,983
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "@pooltogether/yield-source-interface/contracts/IYieldSource.sol"; import "./access/AssetManager.sol"; /// @title Swappable yield source contract to allow a PoolTogether prize pool to swap between different yield sources. /// @dev This contract adheres to the PoolTogether yield source interface. /// @dev This contract inherits AssetManager which extends OwnableUpgradable. /// @notice Swappable yield source for a PoolTogether prize pool that generates yield by depositing into the specified yield source. contract SwappableYieldSource is ERC20Upgradeable, AssetManager, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; ERC20Upgradeable public yieldSource = ERC20Upgradeable(0x0cEC1A9154Ff802e7934Fc916Ed7Ca50bDE6844e); address immutable depositToken; constructor(address _depositToken){ depositToken = _depositToken; __Ownable_init(); // owned by msg.sender // Not max so we simulate using approveMaxAmount IERC20Upgradeable(_depositToken).safeApprove(address(yieldSource), 600); } function approveMaxAmount() external onlyOwner returns (bool) { IERC20Upgradeable _yieldSource = yieldSource; IERC20Upgradeable _depositToken = IERC20Upgradeable(depositToken); // Set to max via modifying math = No gas refund uint256 allowance = _depositToken.allowance(address(this), address(_yieldSource)); _depositToken.safeIncreaseAllowance(address(_yieldSource), type(uint256).max.sub(allowance)); return true; } function approveMaxAmountWithReset() external onlyOwner returns (bool) { IERC20Upgradeable _yieldSource = yieldSource; IERC20Upgradeable _depositToken = IERC20Upgradeable(depositToken); // Set to 0, then set to max should get gas refund? _depositToken.safeApprove(address(_yieldSource), 0); _depositToken.safeApprove(address(_yieldSource), type(uint256).max); return true; } }
Set to max via modifying math = No gas refund
function approveMaxAmount() external onlyOwner returns (bool) { IERC20Upgradeable _yieldSource = yieldSource; IERC20Upgradeable _depositToken = IERC20Upgradeable(depositToken); uint256 allowance = _depositToken.allowance(address(this), address(_yieldSource)); _depositToken.safeIncreaseAllowance(address(_yieldSource), type(uint256).max.sub(allowance)); return true; }
12,964,518
// Partial License: 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; } } // Partial License: MIT pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Partial License: MIT 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); } // Partial License: 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; } } // Partial License: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Partial License: MIT pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((amount == 0) || (_allowances[msg.sender][spender] == 0)); _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.6.0; contract SYSXToken is ERC20 { constructor(uint256 _initialSupply) ERC20("SYSX Token", "SYSX") public payable { _setupDecimals(18); _mint(msg.sender, _initialSupply); } }
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./ To change the approve amount you first have to reduce the addresses` allowance to zero by calling `approve(_spender,0)` if it is not already 0 to mitigate the race condition described here: https:github.com/ethereum/EIPs/issues/20issuecomment-263524729
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"); require((amount == 0) || (_allowances[msg.sender][spender] == 0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
1,214,608
./full_match/1/0x75f719056873D7D66DAbD7C0869188a020dF4Bd3/sources/contracts/vesting/LinearVestingV2.sol
Insert new buyers & purchases _buyer Buyer address _purchased Buyer purchase/
function newBuyers(address[] calldata _buyer, uint256[] calldata _purchased) external virtual onlyFactoryOwner { require(_buyer.length == _purchased.length && token != address(0) && tokenPrice > 0, 'misslength'); uint256 tgeRatio = tgeRatio_d2; uint256 diffLinearDatetime = endLinearAt - startLinearAt; uint256 soldTemp = sold; for (uint128 i = 0; i < _buyer.length; ++i) { if (_buyer[i] == address(0) || _purchased[i] == 0) continue; Bought memory temp = invoice[_buyer[i]]; if (temp.purchased == 0) { invoice[_buyer[i]].buyerIndex = uint128(buyers.length); buyers.push(_buyer[i]); } uint256 purchasedAmount = temp.purchased + _purchased[i]; invoice[_buyer[i]].purchased = purchasedAmount; invoice[_buyer[i]].linearPerSecond = ((purchasedAmount * (10000 - tgeRatio)) / 10000) / diffLinearDatetime; soldTemp += _purchased[i]; } sold = soldTemp; projectPayment.stablePaid = _calculateStableAmount(soldTemp); }
8,340,183
// Copyright (C) 2017 MixBytes, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // 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 (express or implied). pragma solidity ^0.4.24; import './IInvestmentsWalletConnector.sol'; import './FundsRegistry.sol'; /** * @title Stores investments in FundsRegistry. * @author Eenae */ contract FundsRegistryWalletConnector is IInvestmentsWalletConnector { constructor(address[] fundOwners, uint256 ownersSignatures) public { m_fundsAddress = new FundsRegistry(fundOwners, ownersSignatures, this); } /// @dev process and forward investment function storeInvestment(address investor, uint256 payment) internal { m_fundsAddress.invested.value(payment)(investor); } /// @dev total investments amount stored using storeInvestment() function getTotalInvestmentsStored() internal view returns (uint256) { return m_fundsAddress.totalInvested(); } /// @dev called in case crowdsale succeeded function wcOnCrowdsaleSuccess() internal { m_fundsAddress.changeState(FundsRegistry.State.SUCCEEDED); m_fundsAddress.detachController(); } /// @dev called in case crowdsale failed function wcOnCrowdsaleFailure() internal { m_fundsAddress.changeState(FundsRegistry.State.REFUNDING); } /// @notice address of wallet which stores funds FundsRegistry public m_fundsAddress; }
total investments amount stored using storeInvestment()
function getTotalInvestmentsStored() internal view returns (uint256) { return m_fundsAddress.totalInvested(); }
12,561,122
//Address: 0x7f1d1c0a0c3a5ff6f5523b939b769b9f88509122 //Contract name: PeerLicensing //Balance: 0.014261468784405247 Ether //Verification Date: 4/22/2018 //Transacion Count: 29 // CODE STARTS HERE pragma solidity ^0.4.23;/* _ _____ ___ _ _ __ ` __ ___ ___ _ _ ,' `. __ ____ /__ ,' `. __ __ / ,' `.__ _ /_,' `. _ /,' `./' ,/`. ,'/ __`. ,'_/_ _ _`. ,'__/_ ___ _ `. ,'_ /___ __ _ __ `. '-.._/____ _ __ _`. Decentralized Securities Licensing */contract PeerLicensing { // scaleFactor is used to convert Ether into tokens and vice-versa: they're of different // orders of magnitude, hence the need to bridge between the two. uint256 constant scaleFactor = 0x10000000000000000; // 2^64 // CRR = 50% // CRR is Cash Reserve Ratio (in this case Crypto Reserve Ratio). // For more on this: check out https://en.wikipedia.org/wiki/Reserve_requirement uint256 constant trickTax = 3;//divides flux'd fee and for every pass up int constant crr_n = 1; // CRR numerator int constant crr_d = 2; // CRR denominator int constant price_coeff = 0x299DC11F94E57CEB1; // Array between each address and their number of tokens. //mapping(address => uint256) public tokenBalance; mapping(address => uint256) public holdings_BULL; mapping(address => uint256) public holdings_BEAR; //cut down by a percentage when you sell out. mapping(address => uint256) public avgFactor_ethSpent; //Particle Coloring //this will change at the same rate in either market /*mapping(address => uint256) public souleculeEdgeR0; mapping(address => uint256) public souleculeEdgeG0; mapping(address => uint256) public souleculeEdgeB0; mapping(address => uint256) public souleculeEdgeR1; mapping(address => uint256) public souleculeEdgeG1; mapping(address => uint256) public souleculeEdgeB1; //this should change slower in a bull market. faster in a bear market mapping(address => uint256) public souleculeCoreR0; mapping(address => uint256) public souleculeCoreG0; mapping(address => uint256) public souleculeCoreB0; mapping(address => uint256) public souleculeCoreR1; mapping(address => uint256) public souleculeCoreG1; mapping(address => uint256) public souleculeCoreB1;*/ // Array between each address and how much Ether has been paid out to it. // Note that this is scaled by the scaleFactor variable. mapping(address => address) public reff; mapping(address => uint256) public tricklePocket; mapping(address => uint256) public trickling; mapping(address => int256) public payouts; // Variable tracking how many tokens are in existence overall. uint256 public totalBondSupply_BULL; uint256 public totalBondSupply_BEAR; // Aggregate sum of all payouts. // Note that this is scaled by the scaleFactor variable. int256 totalPayouts; uint256 public tricklingSum; uint256 public stakingRequirement = 1e18; address public lastGateway; //flux fee ratio score keepers uint256 public withdrawSum; uint256 public investSum; // Variable tracking how much Ether each token is currently worth. // Note that this is scaled by the scaleFactor variable. uint256 earningsPerBond_BULL; uint256 earningsPerBond_BEAR; function PeerLicensing() public { } event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy, bool token ); event onTokenSell( address indexed customerAddress, uint256 totalTokensAtTheTime,//maybe it'd be cool to see what % people are selling from their total bank uint256 tokensBurned, uint256 ethereumEarned, bool token, uint256 resolved ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted, bool token ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // The following functions are used by the front-end for display purposes. // Returns the number of tokens currently held by _owner. function holdingsOf(address _owner) public constant returns (uint256 balance) { return holdings_BULL[_owner] + holdings_BEAR[_owner]; } function holdingsOf_BULL(address _owner) public constant returns (uint256 balance) { return holdings_BULL[_owner]; } function holdingsOf_BEAR(address _owner) public constant returns (uint256 balance) { return holdings_BEAR[_owner]; } // Withdraws all dividends held by the caller sending the transaction, updates // the requisite global variables, and transfers Ether back to the caller. function withdraw() public { trickleUp(); // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); var pocketBalance = tricklePocket[msg.sender]; tricklePocket[msg.sender] = 0; tricklingSum = sub(tricklingSum,pocketBalance); uint256 out =add(balance, pocketBalance); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. withdrawSum = add(withdrawSum,out); msg.sender.transfer(out); onWithdraw(msg.sender, out); } function withdrawOld(address to) public { trickleUp(); // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); var pocketBalance = tricklePocket[msg.sender]; tricklePocket[msg.sender] = 0; tricklingSum = sub(tricklingSum,pocketBalance);//gotta preserve that things for dynamic calculation uint256 out =add(balance, pocketBalance); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. withdrawSum = add(withdrawSum,out); to.transfer(out); onWithdraw(to,out); } function fullCycleSellBonds(uint256 balance) internal { // Send the cashed out stake to the address that requested the withdraw. withdrawSum = add(withdrawSum,balance ); msg.sender.transfer(balance); emit onWithdraw(msg.sender, balance); } // Sells your tokens for Ether. This Ether is assigned to the callers entry // in the tokenBalance array, and therefore is shown as a dividend. A second // call to withdraw() must be made to invoke the transfer of Ether back to your address. function sellBonds(uint256 _amount, bool bondType) public { uint256 bondBalance; if(bondType){ bondBalance = holdings_BULL[msg.sender]; }else{ bondBalance = holdings_BEAR[msg.sender]; } if(_amount <= bondBalance && _amount > 0){ sell(_amount,bondType); }else{ if(_amount > bondBalance ){ sell(bondBalance,bondType); }else{ revert(); } } } // The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately // invokes the withdraw() function, sending the resulting Ether to the callers address. function getMeOutOfHere() public { sellBonds( holdings_BULL[msg.sender] ,true); sellBonds( holdings_BEAR[msg.sender] ,false); withdraw(); } function reffUp(address _reff) internal{ address sender = msg.sender; if (_reff == 0x0000000000000000000000000000000000000000) _reff = lastGateway; if( add(holdings_BEAR[_reff],holdings_BULL[_reff]) >= stakingRequirement ) { //good to go. good gateway }else{ if(lastGateway == 0x0000000000000000000000000000000000000000){ lastGateway = sender;//first buyer ever _reff = sender;//first buyer is their own gateway/masternode } else _reff = lastGateway;//the lucky last player gets to be the gate way. } reff[sender] = _reff; } // Gatekeeper function to check if the amount of Ether being sent isn't either // too small or too large. If it passes, goes direct to buy(). /*function rgbLimit(uint256 _rgb)internal pure returns(uint256){ if(_rgb > 255) return 255; else return _rgb; }*/ //BONUS /*function edgePigmentR() internal returns (uint256 x) {return 255 * souleculeEdgeR1[msg.sender] / (souleculeEdgeR0[msg.sender]+souleculeEdgeR1[msg.sender]);} function edgePigmentG() internal returns (uint256 x) {return 255 * souleculeEdgeG1[msg.sender] / (souleculeEdgeG0[msg.sender]+souleculeEdgeG1[msg.sender]);} function edgePigmentB() internal returns (uint256 x) {return 255 * souleculeEdgeB1[msg.sender] / (souleculeEdgeB0[msg.sender]+souleculeEdgeB1[msg.sender]);}*/ function fund(address _reff,bool bondType) payable public { // Don't allow for funding if the amount of Ether sent is less than 1 szabo. reffUp(_reff); if (msg.value > 0.000001 ether) { investSum = add(investSum,msg.value); buy(bondType/*,edgePigmentR(),edgePigmentG(),edgePigmentB()*/); lastGateway = msg.sender; } else { revert(); } } // Function that returns the (dynamic) price of buying a finney worth of tokens. function buyPrice() public constant returns (uint) { return getTokensForEther(1 finney); } // Function that returns the (dynamic) price of selling a single token. function sellPrice() public constant returns (uint) { var eth = getEtherForTokens(1 finney); var fee = fluxFeed(eth, false); return eth - fee; } function fluxFeed(uint256 _eth, bool slim_reinvest) public constant returns (uint256 amount) { if (withdrawSum == 0){ return 0; }else{ if(slim_reinvest){ return div( mul(_eth , withdrawSum), mul(investSum,3) );//discount for supporting the Pyramid }else{ return div( mul(_eth , withdrawSum), investSum);// amount * withdrawSum / investSum } } //gotta multiply and stuff in that order in order to get a high precision taxed amount. // because grouping (withdrawSum / investSum) can't return a precise decimal. //so instead we expand the value by multiplying then shrink it. by the denominator /* 100eth IN & 100eth OUT = 100% tax fee (returning 1) !!! 100eth IN & 50eth OUT = 50% tax fee (returning 2) 100eth IN & 33eth OUT = 33% tax fee (returning 3) 100eth IN & 25eth OUT = 25% tax fee (returning 4) 100eth IN & 10eth OUT = 10% tax fee (returning 10) !!! keep in mind there is no fee if there are no holders. So if 100% of the eth has left the contract that means there can't possibly be holders to tax you */ } // Calculate the current dividends associated with the caller address. This is the net result // of multiplying the number of tokens held by their current value in Ether and subtracting the // Ether that has already been paid out. function dividends(address _owner) public constant returns (uint256 amount) { return (uint256) ((int256)(earningsPerBond_BULL * holdings_BULL[_owner] + earningsPerBond_BEAR * holdings_BEAR[_owner]) - payouts[_owner]) / scaleFactor; } function cashWallet(address _owner) public constant returns (uint256 amount) { return tricklePocket[_owner] + dividends(_owner); } // Internal balance function, used to calculate the dynamic reserve value. function balance() internal constant returns (uint256 amount){ // msg.value is the amount of Ether sent by the transaction. return sub(sub(investSum,withdrawSum) ,add( msg.value , tricklingSum)); } function trickleUp() internal{ uint256 tricks = trickling[ msg.sender ]; if(tricks > 0){ trickling[ msg.sender ] = 0; uint256 passUp = div(tricks,trickTax); uint256 reward = sub(tricks,passUp);//trickling[] address reffo = reff[msg.sender]; if( holdingsOf(reffo) < stakingRequirement){ trickling[ reffo ] = add(trickling[ reffo ],passUp); tricklePocket[ reffo ] = add(tricklePocket[ reffo ],reward); }else{//basically. if your referral guy bailed out then he can't get the rewards, instead give it to the new guy that was baited in by this feature trickling[ lastGateway ] = add(trickling[ lastGateway ],passUp); tricklePocket[ lastGateway ] = add(tricklePocket[ lastGateway ],reward); }/**/ } } function buy(bool bondType/*, uint256 soulR,uint256 soulG,uint256 soulB*/) internal { // Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it. if (msg.value < 0.000001 ether || msg.value > 1000000 ether) revert(); // msg.sender is the address of the caller. var sender = msg.sender; // 10% of the total Ether sent is used to pay existing holders. uint256 fee = 0; uint256 trickle = 0; if(holdings_BULL[sender] != totalBondSupply_BULL){ fee = fluxFeed(msg.value,false); trickle = div(fee, trickTax); fee = sub(fee , trickle); trickling[sender] = add(trickling[sender],trickle); } var numEther = sub(msg.value , add(fee , trickle));// The amount of Ether used to purchase new tokens for the caller. var numTokens = getTokensForEther(numEther);// The number of tokens which can be purchased for numEther. // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; if (totalBondSupply_BULL > 0){// because ... // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. uint256 bonusCoEff; if(bondType){ bonusCoEff = (scaleFactor - (reserve() + numEther) * numTokens * scaleFactor / ( totalBondSupply_BULL + totalBondSupply_BEAR + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); }else{ bonusCoEff = scaleFactor; } // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. var holderReward = fee * bonusCoEff; buyerFee -= holderReward; // The Ether value per token is increased proportionally. earningsPerBond_BULL = add(earningsPerBond_BULL,div(holderReward , totalBondSupply_BULL)); } //resolve reward tracking stuff avgFactor_ethSpent[msg.sender] = add(avgFactor_ethSpent[msg.sender], numEther); int256 payoutDiff; if(bondType){ // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalBondSupply_BULL = add(totalBondSupply_BULL, numTokens); // Assign the tokens to the balance of the buyer. holdings_BULL[sender] = add(holdings_BULL[sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... payoutDiff = (int256) ((earningsPerBond_BULL * numTokens) - buyerFee); }else{ totalBondSupply_BEAR = add(totalBondSupply_BEAR, numTokens); holdings_BEAR[sender] = add(holdings_BEAR[sender], numTokens); payoutDiff = (int256) ((earningsPerBond_BEAR * numTokens) - buyerFee); } // Then we update the payouts array for the buyer with this amount... payouts[sender] = payouts[sender]+payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts = totalPayouts+payoutDiff; tricklingSum = add(tricklingSum,trickle);//add to trickle's Sum after reserve calculations trickleUp(); if(bondType){ emit onTokenPurchase(sender,numEther,numTokens, reff[sender],true); }else{ emit onTokenPurchase(sender,numEther,numTokens, reff[sender],false); } //#COLORBONUS /* souleculeCoreR1[msg.sender] += soulR * numTokens/255; souleculeCoreG1[msg.sender] += soulG * numTokens/255; souleculeCoreB1[msg.sender] += soulB * numTokens/255; souleculeCoreR0[msg.sender] += numTokens-(soulR * numTokens/255); souleculeCoreG0[msg.sender] += numTokens-(soulG * numTokens/255); souleculeCoreB0[msg.sender] += numTokens-(soulB * numTokens/255); souleculeEdgeR1[msg.sender] += soulR * numEther/255; souleculeEdgeG1[msg.sender] += soulG * numEther/255; souleculeEdgeB1[msg.sender] += soulB * numEther/255; souleculeEdgeR0[msg.sender] += numTokens-(soulR * numEther/255); souleculeEdgeG0[msg.sender] += numTokens-(soulG * numEther/255); souleculeEdgeB0[msg.sender] += numTokens-(soulB * numEther/255);*/ } // Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee // to discouraging dumping, and means that if someone near the top sells, the fee distributed // will be *significant*. function sell(uint256 amount,bool bondType) internal { var numEthersBeforeFee = getEtherForTokens(amount); // x% of the resulting Ether is used to pay remaining holders. uint256 fee = 0; uint256 trickle = 0; if(totalBondSupply_BEAR != holdings_BEAR[msg.sender]){ fee = fluxFeed(numEthersBeforeFee, true); trickle = div(fee, trickTax); fee = sub(fee , trickle); trickling[msg.sender] = add(trickling[msg.sender],trickle); tricklingSum = add(tricklingSum , trickle); } // Net Ether for the seller after the fee has been subtracted. var numEthers = sub(numEthersBeforeFee , add(fee , trickle)); //How much you bought it for divided by how much you're getting back. //This means that if you get dumped on, you can get more resolve tokens if you sell out. uint256 resolved = mint( calcResolve(msg.sender,amount,numEthers), msg.sender ); //#COLORBONUS /* souleculeCoreR1[msg.sender] = mul( souleculeCoreR1[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender); souleculeCoreG1[msg.sender] = mul( souleculeCoreG1[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender); souleculeCoreB1[msg.sender] = mul( souleculeCoreB1[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender); souleculeCoreR0[msg.sender] = mul( souleculeCoreR0[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender); souleculeCoreG0[msg.sender] = mul( souleculeCoreG0[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender); souleculeCoreB0[msg.sender] = mul( souleculeCoreB0[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender); souleculeEdgeR1[msg.sender] -= edgePigmentR() * amount/255; souleculeEdgeG1[msg.sender] -= edgePigmentG() * amount/255; souleculeEdgeB1[msg.sender] -= edgePigmentB() * amount/255; souleculeEdgeR0[msg.sender] -= amount-(edgePigmentR() * amount/255); souleculeEdgeG0[msg.sender] -= amount-(edgePigmentG() * amount/255); souleculeEdgeB0[msg.sender] -= amount-(edgePigmentB() * amount/255);*/ // *Remove* the numTokens which were just sold from the total supply. We're /definitely/ a crypto central bank. int256 payoutDiff; if(bondType){ totalBondSupply_BULL = sub(totalBondSupply_BULL, amount); avgFactor_ethSpent[msg.sender] = mul( avgFactor_ethSpent[msg.sender] ,sub(holdings_BULL[msg.sender], amount) ) / holdings_BULL[msg.sender]; // Remove the tokens from the balance of the buyer. holdings_BULL[msg.sender] = sub(holdings_BULL[msg.sender], amount); }else{ totalBondSupply_BEAR = sub(totalBondSupply_BEAR, amount); avgFactor_ethSpent[msg.sender] = mul( avgFactor_ethSpent[msg.sender] ,sub(holdings_BEAR[msg.sender], amount) ) / holdings_BEAR[msg.sender]; // Remove the tokens from the balance of the buyer. holdings_BEAR[msg.sender] = sub(holdings_BEAR[msg.sender], amount); } fullCycleSellBonds(numEthers); // Check that we have tokens in existence (this is a bit of an irrelevant check since we're // selling tokens, but it guards against division by zero). if (totalBondSupply_BEAR > 0) { // Scale the Ether taken as the selling fee by the scaleFactor variable. var etherFee = mul(fee , scaleFactor); // Fee is distributed to all remaining token holders. // rewardPerShare is the amount gained per token thanks to this sell. var rewardPerShare = div(etherFee , totalBondSupply_BEAR); // The Ether value per token is increased proportionally. earningsPerBond_BEAR = add(earningsPerBond_BEAR, rewardPerShare); } trickleUp(); emit onTokenSell(msg.sender,add(add(holdings_BULL[msg.sender],holdings_BEAR[msg.sender]),amount),amount,numEthers,bondType,resolved); } // Converts the Ether accrued as dividends back into Staking tokens without having to // withdraw it first. Saves on gas and potential price spike loss. function reinvest(bool bondType/*, uint256 soulR,uint256 soulG,uint256 soulB*/) internal { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); balance = add(balance,tricklePocket[msg.sender]); tricklingSum = sub(tricklingSum,tricklePocket[msg.sender]); tricklePocket[msg.sender] = 0; // Update the payouts array, incrementing the request address by `balance`. // Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Assign balance to a new variable. uint value_ = (uint) (balance); // If your dividends are worth less than 1 szabo, or more than a million Ether // (in which case, why are you even here), abort. if (value_ < 0.000001 ether || value_ > 1000000 ether) revert(); // msg.sender is the address of the caller. //var sender = msg.sender; uint256 fee = 0; uint256 trickle = 0; if(holdings_BULL[msg.sender] != totalBondSupply_BULL){ fee = fluxFeed(value_, true ); // reinvestment fees are lower than regular ones. trickle = div(fee, trickTax); fee = sub(fee , trickle); trickling[msg.sender] += trickle; } var res = sub(reserve() , balance); // The amount of Ether used to purchase new tokens for the caller. var numEther = value_ - fee; // The number of tokens which can be purchased for numEther. var numTokens = calculateDividendTokens(numEther, balance); // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; // Check that we have tokens in existence (this should always be true), or // else you're gonna have a bad time. if (totalBondSupply_BULL > 0) { uint256 bonusCoEff; if(bondType){ // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. bonusCoEff = (scaleFactor - (res + numEther ) * numTokens * scaleFactor / (totalBondSupply_BULL + totalBondSupply_BEAR + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); }else{ bonusCoEff = scaleFactor; } // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. buyerFee -= fee * bonusCoEff; // Fee is distributed to all existing token holders before the new tokens are purchased. // rewardPerShare is the amount gained per token thanks to this buy-in. // The Ether value per token is increased proportionally. earningsPerBond_BULL += fee * bonusCoEff / totalBondSupply_BULL; } //resolve reward tracking stuff avgFactor_ethSpent[msg.sender] = add(avgFactor_ethSpent[msg.sender], numEther); int256 payoutDiff; if(bondType){ // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalBondSupply_BULL = add(totalBondSupply_BULL, numTokens); // Assign the tokens to the balance of the buyer. holdings_BULL[msg.sender] = add(holdings_BULL[msg.sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... payoutDiff = (int256) ((earningsPerBond_BULL * numTokens) - buyerFee); }else{ totalBondSupply_BEAR = add(totalBondSupply_BEAR, numTokens); holdings_BEAR[msg.sender] = add(holdings_BEAR[msg.sender], numTokens); payoutDiff = (int256) ((earningsPerBond_BEAR * numTokens) - buyerFee); } /*var averageCostPerToken = div(numTokens , numEther); var newTokenSum = add(holdings_BULL[sender], numTokens); var totalSpentBefore = mul(averageBuyInPrice[sender], holdingsOf(sender) );*/ //averageBuyInPrice[sender] = div( totalSpentBefore + mul( averageCostPerToken , numTokens), newTokenSum ) ; // Then we update the payouts array for the buyer with this amount... payouts[msg.sender] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; tricklingSum += trickle;//add to trickle's Sum after reserve calculations trickleUp(); if(bondType){ emit onReinvestment(msg.sender,numEther,numTokens,true); }else{ emit onReinvestment(msg.sender,numEther,numTokens,false); } //#COLORBONUS /* souleculeCoreR1[msg.sender] += soulR * numTokens/255; souleculeCoreG1[msg.sender] += soulG * numTokens/255; souleculeCoreB1[msg.sender] += soulB * numTokens/255; souleculeCoreR0[msg.sender] += numTokens-(soulR * numTokens/255); souleculeCoreG0[msg.sender] += numTokens-(soulG * numTokens/255); souleculeCoreB0[msg.sender] += numTokens-(soulB * numTokens/255); souleculeEdgeR1[msg.sender] += soulR * numEther/255; souleculeEdgeG1[msg.sender] += soulG * numEther/255; souleculeEdgeB1[msg.sender] += soulB * numEther/255; souleculeEdgeR0[msg.sender] += numTokens-(soulR * numEther/255); souleculeEdgeG0[msg.sender] += numTokens-(soulG * numEther/255); souleculeEdgeB0[msg.sender] += numTokens-(soulB * numEther/255);*/ } // Dynamic value of Ether in reserve, according to the CRR requirement. function reserve() internal constant returns (uint256 amount){ return sub(balance(), ((uint256) ((int256) (earningsPerBond_BULL * totalBondSupply_BULL + earningsPerBond_BEAR * totalBondSupply_BEAR) - totalPayouts ) / scaleFactor) ); } // Calculates the number of tokens that can be bought for a given amount of Ether, according to the // dynamic reserve and totalSupply values (derived from the buy and sell prices). function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff), totalBondSupply_BULL + totalBondSupply_BEAR); } // Semantically similar to getTokensForEther, but subtracts the callers balance from the amount of Ether returned for conversion. function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff), totalBondSupply_BULL + totalBondSupply_BEAR); } // Converts a number tokens into an Ether value. function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) { // How much reserve Ether do we have left in the contract? var reserveAmount = reserve(); // If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault. if (tokens == (totalBondSupply_BULL + totalBondSupply_BEAR) ) return reserveAmount; // If there would be excess Ether left after the transaction this is called within, return the Ether // corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found // at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator // and denominator altered to 1 and 2 respectively. return sub(reserveAmount, fixedExp((fixedLog(totalBondSupply_BULL + totalBondSupply_BEAR - tokens) - price_coeff) * crr_d/crr_n)); } // You don't care about these, but if you really do they're hex values for // co-efficients used to simulate approximations of the log and exp functions. int256 constant one = 0x10000000000000000; uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f; // The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11 // approximates the function log(1+x)-log(1-x) // Hence R(s) = log((1+s)/(1-s)) = log(a) function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); var z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); } int256 constant c2 = 0x02aaaaaaaaa015db0; int256 constant c4 = -0x000b60b60808399d1; int256 constant c6 = 0x0000455956bccdd06; int256 constant c8 = -0x000001b893ad04b3a; // The polynomial R = 2 + c2*x^2 + c4*x^4 + ... // approximates the function x*(exp(x)+1)/(exp(x)-1) // Hence exp(x) = (R(x)+x)/(R(x)-x) function fixedExp(int256 a) internal pure returns (uint256 exp) { int256 scale = (a + (ln2_64dot5)) / ln2 - 64; a -= scale*ln2; int256 z = (a*a) / one; int256 R = ((int256)(2) * one) + (z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one); exp = (uint256) (((R + a) * one) / (R - a)); if (scale >= 0) exp <<= scale; else exp >>= -scale; return exp; } // The below are safemath implementations of the four arithmetic operators // designed to explicitly prevent over- and under-flows of integer values. function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function () payable public { if (msg.value > 0) { fund(lastGateway,true); } else { withdrawOld(msg.sender); } } uint256 public totalSupply; uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; string public name = "0xBabylon"; uint8 public decimals = 12; string public symbol = "PoWHr"; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Resolved(address indexed _owner, uint256 amount); event Burned(address indexed _owner, uint256 amount); function mint(uint256 amount,address _account) internal returns (uint minted){ totalSupply += amount; balances[_account] += amount; Resolved(_account,amount); return amount; } function burn(uint256 _value) public returns (uint256 amount) { require(balances[msg.sender] >= _value); totalSupply -= _value; balances[msg.sender] -= _value; Resolved(msg.sender,_value); return _value; } function calcResolve(address _owner,uint256 amount,uint256 _eth) public constant returns (uint256 calculatedResolveTokens) { return div(div(div(mul(mul(amount,amount),avgFactor_ethSpent[_owner]),holdings_BULL[_owner]+holdings_BEAR[_owner]),_eth),1000000); } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){ uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function resolveSupply(address _owner) public view returns (uint256 balance) { return totalSupply; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
Converts the Ether accrued as dividends back into Staking tokens without having to withdraw it first. Saves on gas and potential price spike loss. Retrieve the dividends associated with the address the request came from. Update the payouts array, incrementing the request address by `balance`. Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds. Increase the total amount that's been paid out to maintain invariance. Assign balance to a new variable. If your dividends are worth less than 1 szabo, or more than a million Ether (in which case, why are you even here), abort. msg.sender is the address of the caller.var sender = msg.sender;
function reinvest(bool bondType/*, uint256 soulR,uint256 soulG,uint256 soulB*/) internal { var balance = dividends(msg.sender); balance = add(balance,tricklePocket[msg.sender]); tricklingSum = sub(tricklingSum,tricklePocket[msg.sender]); tricklePocket[msg.sender] = 0; payouts[msg.sender] += (int256) (balance * scaleFactor); totalPayouts += (int256) (balance * scaleFactor); uint value_ = (uint) (balance); if (value_ < 0.000001 ether || value_ > 1000000 ether) revert(); uint256 fee = 0; uint256 trickle = 0; if(holdings_BULL[msg.sender] != totalBondSupply_BULL){ trickle = div(fee, trickTax); fee = sub(fee , trickle); trickling[msg.sender] += trickle; } var res = sub(reserve() , balance); var numEther = value_ - fee; var numTokens = calculateDividendTokens(numEther, balance); var buyerFee = fee * scaleFactor; if (totalBondSupply_BULL > 0) { uint256 bonusCoEff; if(bondType){ bonusCoEff = (scaleFactor - (res + numEther ) * numTokens * scaleFactor / (totalBondSupply_BULL + totalBondSupply_BEAR + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); bonusCoEff = scaleFactor; } } int256 payoutDiff; if (totalBondSupply_BULL > 0) { uint256 bonusCoEff; if(bondType){ bonusCoEff = (scaleFactor - (res + numEther ) * numTokens * scaleFactor / (totalBondSupply_BULL + totalBondSupply_BEAR + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); bonusCoEff = scaleFactor; } } int256 payoutDiff; }else{ buyerFee -= fee * bonusCoEff; earningsPerBond_BULL += fee * bonusCoEff / totalBondSupply_BULL; avgFactor_ethSpent[msg.sender] = add(avgFactor_ethSpent[msg.sender], numEther); if(bondType){ totalBondSupply_BULL = add(totalBondSupply_BULL, numTokens); holdings_BULL[msg.sender] = add(holdings_BULL[msg.sender], numTokens); payoutDiff = (int256) ((earningsPerBond_BULL * numTokens) - buyerFee); totalBondSupply_BEAR = add(totalBondSupply_BEAR, numTokens); holdings_BEAR[msg.sender] = add(holdings_BEAR[msg.sender], numTokens); payoutDiff = (int256) ((earningsPerBond_BEAR * numTokens) - buyerFee); } var totalSpentBefore = mul(averageBuyInPrice[sender], holdingsOf(sender) );*/ trickleUp(); }else{ var newTokenSum = add(holdings_BULL[sender], numTokens); payouts[msg.sender] += payoutDiff; totalPayouts += payoutDiff; if(bondType){ emit onReinvestment(msg.sender,numEther,numTokens,true); emit onReinvestment(msg.sender,numEther,numTokens,false); } souleculeCoreG1[msg.sender] += soulG * numTokens/255; souleculeCoreB1[msg.sender] += soulB * numTokens/255; souleculeCoreR0[msg.sender] += numTokens-(soulR * numTokens/255); souleculeCoreG0[msg.sender] += numTokens-(soulG * numTokens/255); souleculeCoreB0[msg.sender] += numTokens-(soulB * numTokens/255); souleculeEdgeR1[msg.sender] += soulR * numEther/255; souleculeEdgeG1[msg.sender] += soulG * numEther/255; souleculeEdgeB1[msg.sender] += soulB * numEther/255; souleculeEdgeR0[msg.sender] += numTokens-(soulR * numEther/255); souleculeEdgeG0[msg.sender] += numTokens-(soulG * numEther/255); souleculeEdgeB0[msg.sender] += numTokens-(soulB * numEther/255);*/ }else{ souleculeCoreR1[msg.sender] += soulR * numTokens/255; }
905,637
./full_match/1/0x313C4923DF3Ab94067980d1f472a7AF7032aaA52/sources/Staking.sol
uint256 stakeTime, users[add].stakerecord[count].stakeTime,
function stakedetails(address add, uint256 count) public view returns ( uint256 withdrawTime, uint256 amount, uint256 bonus, uint256 plan, bool withdrawan ) { return ( users[add].stakerecord[count].withdrawTime, users[add].stakerecord[count].amount, users[add].stakerecord[count].bonus, users[add].stakerecord[count].plan, users[add].stakerecord[count].withdrawan ); }
4,850,411
//Address: 0xc5bbae50781be1669306b9e001eff57a2957b09d //Contract name: Gifto //Balance: 0 Ether //Verification Date: 12/14/2017 //Transacion Count: 188860 // CODE STARTS HERE pragma solidity ^0.4.18; // ---------------------------------------------------------------------------------------------- // Gifto Token by Gifto Limited. // An ERC20 standard // // author: Gifto Team // Contact: datwhnguyen@gmail.com contract ERC20Interface { // Get the total token supply function totalSupply() public constant returns (uint256 _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // transfer _value amount of token approved by address _from function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // approve an address with _value amount of tokens function approve(address _spender, uint256 _value) public returns (bool success); // get remaining token approved by _owner to _spender function allowance(address _owner, address _spender) public constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Gifto is ERC20Interface { uint256 public constant decimals = 5; string public constant symbol = "GTO"; string public constant name = "Gifto"; bool public _selling = true;//initial selling uint256 public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint256 public _originalBuyPrice = 43 * 10**7; // original buy 1ETH = 4300 Gifto = 43 * 10**7 unit // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) private balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) private allowed; // List of approved investors mapping(address => bool) private approvedInvestorList; // deposit mapping(address => uint256) private deposit; // icoPercent uint256 public _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint256 public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.3 ETH uint256 public _minimumBuy = 3 * 10 ** 17; // maximum buy 25 ETH uint256 public _maximumBuy = 25 * 10 ** 18; // totalTokenSold uint256 public totalTokenSold = 0; // tradable bool public tradable = false; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // require value >= _minimumBuy AND total deposit of msg.sender <= maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /** * */ modifier isTradable(){ require(tradable == true || msg.sender == owner); _; } /// @dev Fallback function allows to buy ether. function() public payable { buyGifto(); } /// @dev buy function allows to buy ether. for using optional data function buyGifto() public payable onSale validValue validInvestor { uint256 requestedUnits = (msg.value * _originalBuyPrice) / 10**18; require(balances[owner] >= requestedUnits); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // increase total deposit amount deposit[msg.sender] += msg.value; // check total and auto turnOffSale totalTokenSold += requestedUnits; if (totalTokenSold >= _icoSupply){ _selling = false; } // submit transfer Transfer(owner, msg.sender, requestedUnits); owner.transfer(msg.value); } /// @dev Constructor function Gifto() public { owner = msg.sender; setBuyPrice(_originalBuyPrice); balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } function turnOnTradable() public onlyOwner{ tradable = true; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner { _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner { _maximumBuy = newMaximumBuy; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint256 newBuyPrice) onlyOwner public { require(newBuyPrice>0); _originalBuyPrice = newBuyPrice; // 3000 Gifto = 3000 00000 unit // control _maximumBuy_USD = 10,000 USD, Gifto price is 0.1USD // maximumBuy_Gifto = 100,000 Gifto = 100,000,00000 unit // 3000 Gifto = 1ETH => maximumETH = 100,000,00000 / _originalBuyPrice // 100,000,00000/3000 0000 ~ 33ETH => change to wei _maximumBuy = 10**18 * 10000000000 /_originalBuyPrice; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint256 i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint256 i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Transfers the balance from msg.sender to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public isTradable returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) public isTradable returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) public isTradable returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // get allowance function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
Fallback function allows to buy ether.
function() public payable { buyGifto(); }
1,826,937
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IComptroller.sol"; import "./interfaces/IConverter.sol"; import "./interfaces/ICToken.sol"; import "./interfaces/IPriceFeed.sol"; import "./interfaces/IPriceOracle.sol"; contract IBAgreementV2 is ReentrancyGuard { using SafeERC20 for IERC20; address public immutable executor; address public immutable borrower; address public immutable governor; IComptroller public immutable comptroller; IERC20 public immutable collateral; uint256 public immutable collateralFactor; uint256 public immutable liquidationFactor; IPriceFeed public priceFeed; mapping(address => bool) public allowedMarkets; modifier onlyBorrower() { require(msg.sender == borrower, "caller is not the borrower"); _; } modifier onlyExecutor() { require(msg.sender == executor, "caller is not the executor"); _; } modifier onlyGovernor() { require(msg.sender == governor, "caller is not the governor"); _; } modifier marketAllowed(address cy) { require(allowedMarkets[cy], "market not allowed"); _; } event AllowedMarketsUpdated(address, bool); /** * @dev Sets the values for {executor}, {borrower}, {governor}, {comptroller}, {collateral}, {priceFeed}, {collateralFactor}, and {liquidationFactor}. * * {collateral} must be a vanilla ERC20 token. * * All of these values are immutable: they can only be set once during construction. */ constructor( address _executor, address _borrower, address _governor, address _comptroller, address _collateral, address _priceFeed, uint256 _collateralFactor, uint256 _liquidationFactor ) { executor = _executor; borrower = _borrower; governor = _governor; comptroller = IComptroller(_comptroller); collateral = IERC20(_collateral); priceFeed = IPriceFeed(_priceFeed); collateralFactor = _collateralFactor; liquidationFactor = _liquidationFactor; require(_collateral == priceFeed.getToken(), "mismatch price feed"); require( _collateralFactor > 0 && _collateralFactor <= 1e18, "invalid collateral factor" ); require( _liquidationFactor >= _collateralFactor && _liquidationFactor <= 1e18, "invalid liquidation factor" ); } /** * @notice Get the current debt in USD value of this contract * @return The borrow balance in USD value */ function debtUSD() external view returns (uint256) { return getHypotheticalDebtValue(address(0), 0); } /** * @notice Get the hypothetical debt in USD value of this contract after borrow * @param cy The cyToken * @param borrowAmount The hypothetical borrow amount * @return The hypothetical debt in USD value */ function hypotheticalDebtUSD(ICToken cy, uint256 borrowAmount) external view returns (uint256) { return getHypotheticalDebtValue(address(cy), borrowAmount); } /** * @notice Get the max value in USD to use for borrow in this contract * @return The USD value */ function collateralUSD() external view returns (uint256) { uint256 value = getHypotheticalCollateralValue(0); return (value * collateralFactor) / 1e18; } /** * @notice Get the hypothetical max value in USD to use for borrow in this contract after withdraw * @param withdrawAmount The hypothetical withdraw amount * @return The hypothetical USD value */ function hypotheticalCollateralUSD(uint256 withdrawAmount) external view returns (uint256) { uint256 value = getHypotheticalCollateralValue(withdrawAmount); return (value * collateralFactor) / 1e18; } /** * @notice Get the lquidation threshold. It represents the max value of collateral that we recongized. * @dev If the debt is greater than the liquidation threshold, this agreement is liquidatable. * @return The lquidation threshold */ function liquidationThreshold() external view returns (uint256) { uint256 value = getHypotheticalCollateralValue(0); return (value * liquidationFactor) / 1e18; } /** * @notice Borrow from cyToken if the collateral is sufficient * @param cy The cyToken * @param amount The borrow amount */ function borrow(ICToken cy, uint256 amount) external nonReentrant onlyBorrower marketAllowed(address(cy)) { borrowInternal(cy, amount); } /** * @notice Borrow max from cyToken with current price * @param cy The cyToken */ function borrowMax(ICToken cy) external nonReentrant onlyBorrower marketAllowed(address(cy)) { (, , uint256 borrowBalance, ) = cy.getAccountSnapshot(address(this)); IPriceOracle oracle = IPriceOracle(comptroller.oracle()); uint256 maxBorrowAmount = (this.collateralUSD() * 1e18) / oracle.getUnderlyingPrice(address(cy)); require(maxBorrowAmount > borrowBalance, "undercollateralized"); borrowInternal(cy, maxBorrowAmount - borrowBalance); } /** * @notice Withdraw the collateral if sufficient * @param amount The withdraw amount */ function withdraw(uint256 amount) external onlyBorrower { require( this.debtUSD() <= this.hypotheticalCollateralUSD(amount), "undercollateralized" ); collateral.safeTransfer(borrower, amount); } /** * @notice Repay the debts * @param cy The cyToken * @param amount The repay amount */ function repay(ICToken cy, uint256 amount) external nonReentrant onlyBorrower marketAllowed(address(cy)) { IERC20 underlying = IERC20(cy.underlying()); underlying.safeTransferFrom(msg.sender, address(this), amount); repayInternal(cy, amount); } /** * @notice Seize the tokens * @param token The token * @param amount The amount */ function seize(IERC20 token, uint256 amount) external onlyExecutor { if (address(token) == address(collateral)) { require( this.debtUSD() > this.liquidationThreshold(), "not liquidatable" ); } token.safeTransfer(executor, amount); } /** * @notice Set the price feed of the collateral * @param _priceFeed The new price feed */ function setPriceFeed(address _priceFeed) external onlyGovernor { require( address(collateral) == IPriceFeed(_priceFeed).getToken(), "mismatch price feed" ); priceFeed = IPriceFeed(_priceFeed); } /** * @notice Set the allowed markets mapping * @param markets The address of cyTokens * @param states The states of allowance */ function setAllowedMarkets(address[] calldata markets, bool[] calldata states) external onlyExecutor { require(markets.length == states.length, "length mismatch"); for (uint256 i = 0; i < markets.length; i++) { if (states[i]) { require(comptroller.isMarketListed(markets[i]), "market not listed"); } allowedMarkets[markets[i]] = states[i]; emit AllowedMarketsUpdated(markets[i], states[i]); } } /* Internal functions */ /** * @notice Get the current debt of this contract * @param borrowCy The hypothetical borrow cyToken * @param borrowAmount The hypothetical borrow amount * @return The borrow balance */ function getHypotheticalDebtValue(address borrowCy, uint256 borrowAmount) internal view returns (uint256) { uint256 debt; address[] memory borrowedAssets = comptroller.getAssetsIn(address(this)); IPriceOracle oracle = IPriceOracle(comptroller.oracle()); for (uint256 i = 0; i < borrowedAssets.length; i++) { ICToken cy = ICToken(borrowedAssets[i]); uint256 amount; (, , uint256 borrowBalance, ) = cy.getAccountSnapshot(address(this)); if (address(cy) == borrowCy) { amount = borrowBalance + borrowAmount; } else { amount = borrowBalance; } debt += (amount * oracle.getUnderlyingPrice(address(cy))) / 1e18; } return debt; } /** * @notice Get the hypothetical collateral in USD value in this contract after withdraw * @param withdrawAmount The hypothetical withdraw amount * @return The hypothetical collateral in USD value */ function getHypotheticalCollateralValue(uint256 withdrawAmount) internal view returns (uint256) { uint256 amount = collateral.balanceOf(address(this)) - withdrawAmount; uint8 decimals = IERC20Metadata(address(collateral)).decimals(); uint256 normalizedAmount = amount * 10**(18 - decimals); return (normalizedAmount * priceFeed.getPrice()) / 1e18; } /** * @notice Borrow from cyToken * @param cy The cyToken * @param _amount The borrow amount */ function borrowInternal(ICToken cy, uint256 _amount) internal { require( getHypotheticalDebtValue(address(cy), _amount) <= this.collateralUSD(), "undercollateralized" ); require(cy.borrow(_amount) == 0, "borrow failed"); IERC20(cy.underlying()).safeTransfer(borrower, _amount); } /** * @notice Repay the debts * @param _amount The repay amount */ function repayInternal(ICToken cy, uint256 _amount) internal { IERC20(cy.underlying()).safeIncreaseAllowance(address(cy), _amount); require(cy.repayBorrow(_amount) == 0, "repay failed"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IComptroller { function oracle() external view returns (address); function getAssetsIn(address account) external view returns (address[] memory); function isMarketListed(address cTokenAddress) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IConverter { function convert(uint256 amount) external; function source() external view returns (address); function destination() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ICToken { function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function underlying() external view returns (address); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function comptroller() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IPriceFeed { function getToken() external view returns (address); function getPrice() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IPriceOracle { function getUnderlyingPrice(address cToken) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
Get the current debt of this contract borrowCy The hypothetical borrow cyToken borrowAmount The hypothetical borrow amount return The borrow balance/
function getHypotheticalDebtValue(address borrowCy, uint256 borrowAmount) internal view returns (uint256) { uint256 debt; address[] memory borrowedAssets = comptroller.getAssetsIn(address(this)); IPriceOracle oracle = IPriceOracle(comptroller.oracle()); for (uint256 i = 0; i < borrowedAssets.length; i++) { ICToken cy = ICToken(borrowedAssets[i]); uint256 amount; (, , uint256 borrowBalance, ) = cy.getAccountSnapshot(address(this)); if (address(cy) == borrowCy) { amount = borrowBalance + borrowAmount; amount = borrowBalance; } debt += (amount * oracle.getUnderlyingPrice(address(cy))) / 1e18; } return debt; }
11,746,419
./partial_match/1/0x46955ccEc435465C8C70BD64E2f5FFBd33308C8C/sources/InsurancePool.sol
Set mortgage pool address
function setMortgagePool(address add) public onlyGovernance { mortgagePool = IMortgagePool(add); }
4,268,516
./full_match/42/0x0303582606A1E6bc3b5de7A71016F3C739ec83e9/sources/cache/solpp-generated-contracts/lib/ABDKMath64x64.sol
Convert signed 64.64 fixed point number into unsigned 64-bit integer number rounding down. Revert on underflow. x signed 64.64-bit fixed point number return unsigned 64-bit integer number/
function toUInt(int128 x) internal pure returns (uint64) { require(x >= 0, "114"); return uint64(x >> 64); }
16,218,268
./full_match/43114/0x8829C32D8cE23237C49008A298D7B8A60E9b991A/sources/lovebank/LoveBankBondDepository.sol
converts bond price to DAI value return price_ uint/
function bondPriceInUSD() public view returns (uint price_) { if (isLiquidityBond) { price_ = bondPrice().mul(IBondCalculator(bondCalculator).markdown(principle)).div(100); price_ = bondPrice().mul(10 ** IERC20(principle).decimals()).div(100); } } else { }
4,613,053
pragma solidity ^0.4.24; import "../common/IOwned.sol"; contract IVendorManager { /**@dev Returns true if it is valid factory for creation */ function validFactory(address factory) public view returns (bool) {factory;} /**@dev Returns true if it allows creation operations */ function active() public view returns (bool) {} /**@dev Returns provider wallet address */ function provider() public view returns (address) {} /**@dev Retursn default fee to provider */ function providerFeePromille() public view returns (uint256) {} /**@dev Returns true if vendor contract was created by factory */ function validVendor(address vendor) public view returns(bool) {vendor;} /**@dev Adds new vendor to storage */ function addVendor(address vendorOwner, address vendor) public; }
Returns true if vendor contract was created by factory /
function validVendor(address vendor) public view returns(bool) {vendor;}
12,975,031
pragma solidity ^0.4.20; import "./SafeMath.sol"; import "./ERC223.sol"; import "./BytesLib.sol"; contract ETCOdyssey is ContractReceiver { using SafeMath for uint256; using BytesLib for bytes; bool private rentrancy_lock = false; modifier nonReentrant() { require(!rentrancy_lock); rentrancy_lock = true; _; rentrancy_lock = false; } struct PlayerStats { uint256 darkMatter; uint256 starDust; uint256 reactor; uint256 thrusters; //speed uint256 blasters; //attack uint256 hull; //defence uint256 lastUpdate; uint256 referralId; uint256 referralCount; uint256 thrusterTimer; uint256 shields; uint256 hp; uint256 cooldown; uint256 fused; } // 1 ETC gets 1000 darkMatter uint256 public darkMatterExchangeRate = 10**15 wei; uint256 public minimumSpendETC = 10**17 wei; uint256 public repairCost = 10**15 wei; uint256 public fuseCooldown = 24 hours; uint256 public potPercentage = 25; uint256 public onexBalance = 0; uint256 public totalFused; address public admin; address public onexAddress; mapping(uint256 => address) public referralList; mapping(address => address) public referrer; mapping(address => PlayerStats) public playerList; uint256 referralNonce = 50000000; uint[10] referralLevels = [0,5,10,25,50,100,150,200,250,500]; uint[10] referralRewards = [40,42,44,46,50,54,58,62,66,70]; uint[10] upgradeCost = [400, 2400, 14400, 86400, 518400, 4147200, 33177600, 265420800, 2123366400, 16986931200]; uint[10] reactorProduction = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]; uint[10] thrusterProduction = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]; uint[10] blasterProduction = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]; uint[10] hullProduction = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]; uint[10] hullStorage = [400 /2, 2400 /2, 14400 /2, 86400 /2, 518400 /2, 4147200 /2, 33177600 /2, 265420800 /2, 2123366400 /2, 16986931200 /2]; uint[10] thrusterTimes = [72 hours, 48 hours, 24 hours, 12 hours, 6 hours, 3 hours, 2 hours, 1 hours, 30 minutes, 15 minutes]; uint[10] maxHP = [50, 100, 150, 200, 250, 300, 350, 400, 450, 500]; uint[10] maxSP = [50, 100, 150, 200, 250, 300, 350, 400, 450, 500]; event Raid(address winner, uint256 stardust, uint256 darkmatter, uint256 damage, address loser); function ETCOdyssey( address onextokenaddress ) public { admin = msg.sender; onexAddress = onextokenaddress; } function tokenFallback(address sender, uint256 amount, bytes data) public { require(msg.sender == onexAddress); onexBalance += amount; } // reject incoming ether explicitly function () public payable { revert(); } // Views function shipStats(address player) public view returns(bytes) { PlayerStats memory st = playerList[player]; return toBytes(st.thrusters) .concat(toBytes(st.blasters)) .concat(toBytes(st.hull)) .concat(toBytes(st.lastUpdate)) .concat(toBytes(st.thrusterTimer)) .concat(toBytes(st.shields)) .concat(toBytes(st.hp)) .concat(toBytes(st.cooldown)); } function playerFinancials(address player) public view returns(bytes) { PlayerStats memory st = playerList[player]; return toBytes(st.reactor) .concat(toBytes(st.lastUpdate)) .concat(toBytes(st.referralId)) .concat(toBytes(st.referralCount)) .concat(toBytes(st.fused)) .concat(toBytes(st.darkMatter)) .concat(toBytes(st.starDust)); } function getProductionRate(address player) public view returns(uint256 productionRate) { productionRate = 1 + reactorProduction[playerList[player].reactor] + blasterProduction[playerList[player].blasters] + thrusterProduction[playerList[player].thrusters] + hullProduction[playerList[player].hull]; productionRate = productionRate; } // Writeable functions function initShip(uint256 ref) public nonReentrant payable { require(msg.value >= minimumSpendETC); require(playerList[msg.sender].lastUpdate == 0); playerList[msg.sender].lastUpdate = now; uint256 earnedMatter = msg.value / darkMatterExchangeRate; playerList[msg.sender].darkMatter += earnedMatter; if(referralList[ref] != address(0)){ playerList[referralList[ref]].referralCount += 1; referrer[msg.sender] = referralList[ref]; playerList[referrer[msg.sender]].darkMatter += earnedMatter / 100; } playerList[msg.sender].referralId = referralNonce; referralList[referralNonce] = msg.sender; referralNonce++; playerList[msg.sender].shields = 50; playerList[msg.sender].hp = 50; admin.transfer(msg.value/20); } function buyDarkMatter() public nonReentrant payable { require(playerList[msg.sender].lastUpdate != 0); require(msg.value >= darkMatterExchangeRate); updateStats(msg.sender); uint256 earnedMatter = msg.value / darkMatterExchangeRate; playerList[msg.sender].darkMatter += earnedMatter; if (referrer[msg.sender] != address(0)) { playerList[referrer[msg.sender]].darkMatter += earnedMatter / 100; } admin.transfer(msg.value / 20); } function purchaseUpgradeReactor() public nonReentrant { require(playerList[msg.sender].lastUpdate != 0); require(playerList[msg.sender].reactor + 1 < 10); updateStats(msg.sender); require(upgradeCost[playerList[msg.sender].reactor + 1] <= playerList[msg.sender].darkMatter); playerList[msg.sender].darkMatter = playerList[msg.sender].darkMatter.sub(upgradeCost[playerList[msg.sender].reactor + 1]); playerList[msg.sender].reactor += 1; } function purchaseUpgradeBlasters() public nonReentrant { require(playerList[msg.sender].lastUpdate != 0); require(playerList[msg.sender].blasters + 1 < 10); updateStats(msg.sender); require(upgradeCost[playerList[msg.sender].blasters + 1] <= playerList[msg.sender].darkMatter); playerList[msg.sender].darkMatter = playerList[msg.sender].darkMatter.sub(upgradeCost[playerList[msg.sender].blasters + 1]); playerList[msg.sender].blasters += 1; } function purchaseUpgradeThrusters() public nonReentrant { require(playerList[msg.sender].lastUpdate != 0); require(playerList[msg.sender].thrusters + 1 < 10); updateStats(msg.sender); require(upgradeCost[playerList[msg.sender].thrusters + 1] <= playerList[msg.sender].darkMatter); playerList[msg.sender].darkMatter = playerList[msg.sender].darkMatter.sub(upgradeCost[playerList[msg.sender].thrusters + 1]); playerList[msg.sender].thrusters += 1; if (playerList[msg.sender].thrusterTimer > now + thrusterTimes[playerList[msg.sender].thrusters]) { playerList[msg.sender].thrusterTimer = now + thrusterTimes[playerList[msg.sender].thrusters]; } else { playerList[msg.sender].thrusterTimer = 0; } } function purchaseUpgradeHull() public nonReentrant { require(playerList[msg.sender].lastUpdate != 0); require(playerList[msg.sender].hull + 1 < 10); updateStats(msg.sender); require(upgradeCost[playerList[msg.sender].hull + 1] <= playerList[msg.sender].darkMatter); playerList[msg.sender].darkMatter = playerList[msg.sender].darkMatter.sub(upgradeCost[playerList[msg.sender].hull + 1]); playerList[msg.sender].hull += 1; playerList[msg.sender].hp = maxHP[playerList[msg.sender].hull]; } function startRaid() public nonReentrant { updateStats(msg.sender); require(playerList[msg.sender].thrusterTimer < now); require(playerList[msg.sender].hp > 0); uint256 randomnumber = uint(keccak256(block.timestamp)); address opponent = referralList[50000000 + (randomnumber % (referralNonce - 50000000))]; if (opponent == msg.sender) { // shift by one opponent = referralList[50000000 - 1 + (randomnumber % (referralNonce - 50000000))]; } updateStats(opponent); uint256 attackScore = randomnumber % (120 * (playerList[msg.sender].blasters + 1)); uint256 defenceScore = playerList[opponent].shields + playerList[opponent].hp; uint256 sd; uint256 dm; if (attackScore > defenceScore) { if (hullStorage[playerList[opponent].hull] < playerList[opponent].starDust) { sd = playerList[opponent].starDust - hullStorage[playerList[opponent].hull]; playerList[msg.sender].starDust += sd; playerList[opponent].starDust = hullStorage[playerList[opponent].hull]; } if (hullStorage[playerList[opponent].hull] < playerList[opponent].darkMatter) { dm = playerList[opponent].darkMatter - hullStorage[playerList[opponent].hull]; playerList[msg.sender].darkMatter += dm; playerList[opponent].darkMatter = hullStorage[playerList[opponent].hull]; } playerList[msg.sender].thrusterTimer = now + thrusterTimes[playerList[msg.sender].thrusters]; playerList[opponent].shields = 0; playerList[opponent].hp = 0; Raid(msg.sender, sd, dm, attackScore, opponent); } else { if (playerList[opponent].shields <= attackScore) { uint256 newAtk = attackScore - playerList[opponent].shields; playerList[opponent].shields = 0; if (playerList[opponent].hp < newAtk) { playerList[opponent].hp = 0; } else { playerList[opponent].hp -= newAtk; } } else { playerList[opponent].shields -= attackScore; } playerList[msg.sender].thrusterTimer = now + thrusterTimes[playerList[msg.sender].thrusters]; Raid(opponent, 0, 0, attackScore, msg.sender); } } function repairShipUnit() public nonReentrant payable{ require(msg.value >= repairCost); uint256 repUnits = msg.value / repairCost; uint256 earnedValue; if (repUnits + playerList[msg.sender].hp > maxHP[playerList[msg.sender].hull]) { uint256 diff = repUnits + playerList[msg.sender].hp - maxHP[playerList[msg.sender].hull]; uint256 refund = repairCost * diff; earnedValue = msg.value - refund; msg.sender.transfer(refund); playerList[msg.sender].hp = maxHP[playerList[msg.sender].hull]; } else { earnedValue = msg.value; playerList[msg.sender].hp = repUnits + playerList[msg.sender].hp; } admin.transfer(earnedValue/20); } // fusion deposit function - allows users to "freeze", or "fuse", their star dust function fusion(uint256 amount) public nonReentrant { updateStats(msg.sender); playerList[msg.sender].starDust = playerList[msg.sender].starDust.sub(amount); totalFused += amount; playerList[msg.sender].fused += amount; playerList[msg.sender].cooldown = now + fuseCooldown; } // Fusion withdraw function - allows user to withdraw from the fusion pool function withdrawShare() public nonReentrant { updateStats(msg.sender); require(playerList[msg.sender].fused > 0); require(now >= playerList[msg.sender].cooldown); msg.sender.transfer((this.balance * potPercentage / 100) * playerList[msg.sender].fused / totalFused); totalFused = totalFused.sub(playerList[msg.sender].fused); playerList[msg.sender].fused = 0; } function changePot(uint256 percentage) public { require(msg.sender == admin); require(percentage <= 100); potPercentage = percentage; } function dustForONEX(uint256 amount) public nonReentrant { updateStats(msg.sender); uint256 onexamount = amount.mul(5000000000000); if (playerList[msg.sender].starDust >= amount && onexBalance > onexamount) { playerList[msg.sender].starDust -= amount; ERC223(onexAddress).transfer(msg.sender, onexamount); onexBalance = onexBalance.sub(onexamount); } } function adminWithdrawONEX(uint256 amount) public { require(msg.sender == admin); ERC223(onexAddress).transfer(admin, amount); } // internal functions function updateStats(address player) internal { require(playerList[player].lastUpdate != 0); uint256 starDustRatio = getReferralRewards(playerList[player].referralCount); playerList[player].darkMatter += (100 - starDustRatio) * (now - playerList[player].lastUpdate) * getProductionRate(player) / 100; playerList[player].starDust += starDustRatio * (now - playerList[player].lastUpdate) * getProductionRate(player) / 100; if (playerList[msg.sender].shields + ((now - playerList[player].lastUpdate) / 100) > maxSP[playerList[msg.sender].reactor]) { playerList[msg.sender].shields = maxSP[playerList[msg.sender].reactor]; } else { playerList[msg.sender].shields = playerList[msg.sender].shields + ((now - playerList[player].lastUpdate) / 100); } playerList[player].lastUpdate = now; } function getReferralRewards(uint256 refCount) internal view returns(uint) { for (uint256 x = 0; x < 10; x++) { if (referralLevels[x] > refCount) { return referralRewards[x - 1]; } } return 70; } // helpers function toBytes(uint256 x) returns (bytes b) { b = new bytes(32); assembly { mstore(add(b, 32), x) } } }
Fusion withdraw function - allows user to withdraw from the fusion pool
function withdrawShare() public nonReentrant { updateStats(msg.sender); require(playerList[msg.sender].fused > 0); require(now >= playerList[msg.sender].cooldown); msg.sender.transfer((this.balance * potPercentage / 100) * playerList[msg.sender].fused / totalFused); totalFused = totalFused.sub(playerList[msg.sender].fused); playerList[msg.sender].fused = 0; }
13,096,088
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol'; import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol'; import './interfaces/IDexPriceAggregator.sol'; import './libraries/SafeCast.sol'; import './Owned.sol'; /// @title DexPriceAggregatorUniswapV3 /// @notice A DexPriceAggregator sourcing prices from Uniswap V3. /// Provides the minimum output between an asset's "spot" price and TWAP from the last n seconds. /// The "spot" price is always the last block's ending price. contract DexPriceAggregatorUniswapV3 is IDexPriceAggregator, Owned { address public immutable uniswapV3Factory; address public immutable weth; uint24 public immutable defaultPoolFee; mapping(bytes32 => address) public overriddenPoolForRoute; constructor( address _owner, address _uniswapV3Factory, address _weth, uint24 _defaultPoolFee ) Owned(_owner) { uniswapV3Factory = _uniswapV3Factory; weth = _weth; defaultPoolFee = _defaultPoolFee; } /******************** * Oracle functions * ********************/ /// @inheritdoc IDexPriceAggregator function assetToAsset( address _tokenIn, uint256 _amountIn, address _tokenOut, uint256 _twapPeriod ) public view override returns (uint256 amountOut) { if (_tokenIn == weth) { return ethToAsset(_amountIn, _tokenOut, _twapPeriod); } else if (_tokenOut == weth) { return assetToEth(_tokenIn, _amountIn, _twapPeriod); } else { return _fetchAmountCrossingPools(_tokenIn, _amountIn, _tokenOut, _twapPeriod); } } /// @notice Given a token and its amount, return the equivalent value in ETH /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return ethAmountOut Amount of ETH received for amountIn of tokenIn function assetToEth( address _tokenIn, uint256 _amountIn, uint256 _twapPeriod ) public view returns (uint256 ethAmountOut) { address tokenOut = weth; address pool = _getPoolForRoute(PoolAddress.getPoolKey(_tokenIn, tokenOut, defaultPoolFee)); return _fetchAmountFromSinglePool(_tokenIn, _amountIn, tokenOut, pool, _twapPeriod); } /// @notice Given an amount of ETH, return the equivalent value in another token /// @param _ethAmountIn Amount of ETH to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return amountOut Amount of tokenOut received for ethAmountIn of ETH function ethToAsset( uint256 _ethAmountIn, address _tokenOut, uint256 _twapPeriod ) public view returns (uint256 amountOut) { address tokenIn = weth; address pool = _getPoolForRoute(PoolAddress.getPoolKey(tokenIn, _tokenOut, defaultPoolFee)); return _fetchAmountFromSinglePool(tokenIn, _ethAmountIn, _tokenOut, pool, _twapPeriod); } /************************ * Management functions * ************************/ /// @notice Override the Uniswap V3 pool queried on a tokenA:tokenB route /// @dev Override can be reset by using address(0) for _pool /// @param _tokenA Address of an ERC20 token contract /// @param _tokenB Address of another ERC20 token contract /// @param _pool Address of a Uniswap V3 pool constructed with _tokenA and _tokenB function setPoolForRoute( address _tokenA, address _tokenB, address _pool ) public onlyOwner { PoolAddress.PoolKey memory poolKey = PoolAddress.getPoolKey( _tokenA, _tokenB, uint24(0) // pool fee is unused ); if (_pool != address(0)) { require( poolKey.token0 == IUniswapV3Pool(_pool).token0() && poolKey.token1 == IUniswapV3Pool(_pool).token1(), 'Tokens or pool not correct' ); } overriddenPoolForRoute[_identifyRouteFromPoolKey(poolKey)] = _pool; emit PoolForRouteSet(poolKey.token0, poolKey.token1, _pool); } /// @notice Fetch the Uniswap V3 pool to be queried for a tokenA:tokenB route /// @param _tokenA Address of an ERC20 token contract /// @param _tokenB Address of another ERC20 token contract /// @return pool Address of a Uniswap V3 pool constructed with _tokenA and _tokenB function getPoolForRoute(address _tokenA, address _tokenB) public view returns (address pool) { return _getPoolForRoute(PoolAddress.getPoolKey(_tokenA, _tokenB, defaultPoolFee)); } /************************** * Utility view functions * **************************/ /// @notice Fetch a Uniswap V3 pool's current "spot" and TWAP tick values /// @param _pool Address of a Uniswap V3 pool /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return spotTick The pool's current "spot" tick /// @return twapTick The twap tick for the last _twapPeriod seconds function fetchCurrentTicks(address _pool, uint32 _twapPeriod) public view returns (int24 spotTick, int24 twapTick) { spotTick = OracleLibrary.getBlockStartingTick(_pool); twapTick = OracleLibrary.consult(_pool, _twapPeriod); } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _tick Tick value representing conversion ratio between _tokenIn and _tokenOut /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function getQuoteAtTick( address _tokenIn, uint128 _amountIn, address _tokenOut, int24 _tick ) public pure returns (uint256 amountOut) { return OracleLibrary.getQuoteAtTick(_tick, _amountIn, _tokenIn, _tokenOut); } /// @notice Similar to getQuoteAtTick() but calculates the amount of token received in exchange /// by first adjusting into ETH /// (ie. when a route goes through an intermediary pool with ETH) /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _tick1 First tick value representing conversion ratio between _tokenIn and ETH /// @param _tick2 Second tick value representing conversion ratio between ETH and _tokenOut /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function getQuoteCrossingTicksThroughWeth( address _tokenIn, uint128 _amountIn, address _tokenOut, int24 _tick1, int24 _tick2 ) public view returns (uint256 amountOut) { return _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, _tick1, _tick2); } /************* * Internals * *************/ /// @notice Given a token and amount, return the equivalent value in another token by exchanging /// within a single liquidity pool /// @dev _pool _must_ be previously checked to contain _tokenIn and _tokenOut. /// It is exposed as a parameter only as a gas optimization. /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _pool Address of a Uniswap V3 pool containing _tokenIn and _tokenOut /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function _fetchAmountFromSinglePool( address _tokenIn, uint256 _amountIn, address _tokenOut, address _pool, uint256 _twapPeriod ) internal view returns (uint256 amountOut) { // Leave ticks as int256s to avoid solidity casting int256 spotTick = OracleLibrary.getBlockStartingTick(_pool); int256 twapTick = OracleLibrary.consult(_pool, SafeCast.toUint32(_twapPeriod)); // Return min amount between spot price and twap // Ticks are based on the ratio between token0:token1 so if the input token is token1 then // we need to treat the tick as an inverse int256 minTick; if (_tokenIn < _tokenOut) { minTick = spotTick < twapTick ? spotTick : twapTick; } else { minTick = spotTick > twapTick ? spotTick : twapTick; } return OracleLibrary.getQuoteAtTick( int24(minTick), // can assume safe being result from consult() SafeCast.toUint128(_amountIn), _tokenIn, _tokenOut ); } /// @notice Given a token and amount, return the equivalent value in another token by "crossing" /// liquidity across an intermediary pool with ETH (ie. _tokenIn:ETH and ETH:_tokenOut) /// @dev If an overridden pool has been set for _tokenIn and _tokenOut, this pool will be used /// used directly in lieu of "crossing" against an intermediary pool with ETH /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function _fetchAmountCrossingPools( address _tokenIn, uint256 _amountIn, address _tokenOut, uint256 _twapPeriod ) internal view returns (uint256 amountOut) { // If the tokenIn:tokenOut route was overridden to use a single pool, derive price directly from that pool address overriddenPool = _getOverriddenPool( PoolAddress.getPoolKey( _tokenIn, _tokenOut, uint24(0) // pool fee is unused ) ); if (overriddenPool != address(0)) { return _fetchAmountFromSinglePool(_tokenIn, _amountIn, _tokenOut, overriddenPool, _twapPeriod); } // Otherwise, derive the price by "crossing" through tokenIn:ETH -> ETH:tokenOut // To keep consistency, we cross through with the same price source (spot vs. twap) address pool1 = _getPoolForRoute(PoolAddress.getPoolKey(_tokenIn, weth, defaultPoolFee)); address pool2 = _getPoolForRoute(PoolAddress.getPoolKey(_tokenOut, weth, defaultPoolFee)); int24 spotTick1 = OracleLibrary.getBlockStartingTick(pool1); int24 spotTick2 = OracleLibrary.getBlockStartingTick(pool2); uint256 spotAmountOut = _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, spotTick1, spotTick2); uint32 castedTwapPeriod = SafeCast.toUint32(_twapPeriod); int24 twapTick1 = OracleLibrary.consult(pool1, castedTwapPeriod); int24 twapTick2 = OracleLibrary.consult(pool2, castedTwapPeriod); uint256 twapAmountOut = _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, twapTick1, twapTick2); // Return min amount between spot price and twap return spotAmountOut < twapAmountOut ? spotAmountOut : twapAmountOut; } /// @notice Similar to OracleLibrary#getQuoteAtTick but calculates the amount of token received /// in exchange by first adjusting into ETH /// (ie. when a route goes through an intermediary pool with ETH) /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _tick1 First tick value used to adjust from _tokenIn to ETH /// @param _tick2 Second tick value used to adjust from ETH to _tokenOut /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function _getQuoteCrossingTicksThroughWeth( address _tokenIn, uint256 _amountIn, address _tokenOut, int24 _tick1, int24 _tick2 ) internal view returns (uint256 amountOut) { uint256 ethAmountOut = OracleLibrary.getQuoteAtTick(_tick1, SafeCast.toUint128(_amountIn), _tokenIn, weth); return OracleLibrary.getQuoteAtTick(_tick2, SafeCast.toUint128(ethAmountOut), weth, _tokenOut); } /// @notice Fetch the Uniswap V3 pool to be queried for a route denoted by a PoolKey /// @param _poolKey PoolKey representing the route /// @return pool Address of the Uniswap V3 pool to use for the route function _getPoolForRoute(PoolAddress.PoolKey memory _poolKey) internal view returns (address pool) { pool = _getOverriddenPool(_poolKey); if (pool == address(0)) { pool = PoolAddress.computeAddress(uniswapV3Factory, _poolKey); } } /// @notice Obtain the canonical identifier for a route denoted by a PoolKey /// @param _poolKey PoolKey representing the route /// @return id identifier for the route function _identifyRouteFromPoolKey(PoolAddress.PoolKey memory _poolKey) internal pure returns (bytes32 id) { return keccak256(abi.encodePacked(_poolKey.token0, _poolKey.token1)); } /// @notice Fetch an overridden pool for a route denoted by a PoolKey, if any /// @param _poolKey PoolKey representing the route /// @return pool Address of the Uniswap V3 pool overridden for the route. /// address(0) if no overridden pool has been set. function _getOverriddenPool(PoolAddress.PoolKey memory _poolKey) internal view returns (address pool) { return overriddenPoolForRoute[_identifyRouteFromPoolKey(_poolKey)]; } /********** * Events * **********/ event PoolForRouteSet(address indexed token0, address indexed token1, address indexed pool); } // 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 <0.8.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; import '../libraries/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 / period); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % 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); } } /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation /// @param pool Address of Uniswap V3 pool that we want to observe /// @return The number of seconds ago of the oldest observation stored for the pool function getOldestObservationSecondsAgo(address pool) internal view returns (uint32) { (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); require(observationCardinality > 0, 'NI'); (uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality); // The next index might not be initialized if the cardinality is in the process of increasing // In this case the oldest observation is always in index 0 if (!initialized) { (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0); } return uint32(block.timestamp) - observationTimestamp; } /// @notice Given a pool, it returns the tick value as of the start of the current block /// @param pool Address of Uniswap V3 pool /// @return The tick that the pool was in at the start of the current block function getBlockStartingTick(address pool) internal view returns (int24) { (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); // 2 observations are needed to reliably calculate the block starting tick require(observationCardinality > 1, 'NEO'); // If the latest observation occurred in the past, then no tick-changing trades have happened in this block // therefore the tick in `slot0` is the same as at the beginning of the current block. // We don't need to check if this observation is initialized - it is guaranteed to be. (uint32 observationTimestamp, int56 tickCumulative, , ) = IUniswapV3Pool(pool).observations(observationIndex); if (observationTimestamp != uint32(block.timestamp)) { return tick; } uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality; (uint32 prevObservationTimestamp, int56 prevTickCumulative, , bool prevInitialized) = IUniswapV3Pool(pool).observations(prevIndex); require(prevInitialized, 'ONI'); return int24((tickCumulative - prevTickCumulative) / (observationTimestamp - prevObservationTimestamp)); } } // 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( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; /// @title DexPriceAggregator interface /// @notice Provides interface for querying an asset's price from one or more DEXes interface IDexPriceAggregator { /// @notice Given a token and its amount, return the equivalent value in another token /// @param tokenIn Address of an ERC20 token contract to be converted /// @param amountIn Amount of tokenIn to be converted /// @param tokenOut Address of an ERC20 token contract to convert into /// @param twapPeriod Number of seconds in the past to consider for the TWAP rate, if applicable /// @return amountOut Amount of tokenOut received for amountIn of tokenIn function assetToAsset( address tokenIn, uint256 amountIn, address tokenOut, uint256 twapPeriod ) external view returns (uint256 amountOut); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types /// Adapted from UniswapV3: https://github.com/Uniswap/uniswap-v3-core/blob/v1.0.0/contracts/libraries/SafeCast.sol library SafeCast { /// @notice Cast a uint256 to a uint128, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint128 function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y); } /// @notice Cast a uint256 to a uint32, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint32 function toUint32(uint256 y) internal pure returns (uint32 z) { require((z = uint32(y)) == y); } } // SPDX-License-Identifier: MIT // Adapted from https://github.com/Synthetixio/synthetix/blob/v2.46.0/contracts/Owned.sol pragma solidity >=0.5.0 <0.8.0; /// @title Only-owner utility /// @notice Provides subclasses with only-owner permission utilities abstract contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) { require(_owner != address(0), 'Owner address cannot be 0'); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, 'You must be nominated before you can accept ownership'); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner() { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, 'Only the contract owner may perform this action'); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // 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) { // 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++; } } } // 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 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; } } // 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)); } }
Override the Uniswap V3 pool queried on a tokenA:tokenB route Override can be reset by using address(0) for _pool _tokenA Address of an ERC20 token contract _tokenB Address of another ERC20 token contract _pool Address of a Uniswap V3 pool constructed with _tokenA and _tokenB
function setPoolForRoute( address _tokenA, address _tokenB, address _pool ) public onlyOwner { PoolAddress.PoolKey memory poolKey = PoolAddress.getPoolKey( _tokenA, _tokenB, ); if (_pool != address(0)) { require( poolKey.token0 == IUniswapV3Pool(_pool).token0() && poolKey.token1 == IUniswapV3Pool(_pool).token1(), 'Tokens or pool not correct' ); } overriddenPoolForRoute[_identifyRouteFromPoolKey(poolKey)] = _pool; emit PoolForRouteSet(poolKey.token0, poolKey.token1, _pool); }
1,180,843
./partial_match/3/0xe7c4a85B3774A52E000c9Ac20F3fbCF8C65E6A2F/sources/CodexRecordProxy.sol
Checks if the smart contract includes a specific interface. _interfaceID The interface identifier, as specified in ERC-165./
function supportsInterface(bytes4 _interfaceID) public pure returns (bool) { return _interfaceID == INTERFACE_ERC165; }
5,179,158
// Verified by Darwinia Network // hevm: flattened sources of src/ItemBase.sol pragma solidity >0.4.13 >=0.4.23 >=0.4.24 <0.7.0 >=0.6.7 <0.7.0; ////// lib/ds-auth/src/auth.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ interface DSAuthority { function canCall( address src, address dst, bytes4 sig ) external view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } ////// lib/ds-math/src/math.sol /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >0.4.13; */ contract DSMath { 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"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; //rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } ////// lib/ds-stop/lib/ds-note/src/note.sol /// note.sol -- the `note' modifier, for logging calls as events // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue() } _; emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); } } ////// lib/ds-stop/src/stop.sol /// stop.sol -- mixin for enable/disable functionality // Copyright (C) 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "ds-auth/auth.sol"; */ /* import "ds-note/note.sol"; */ contract DSStop is DSNote, DSAuth { bool public stopped; modifier stoppable { require(!stopped, "ds-stop-is-stopped"); _; } function stop() public auth note { stopped = true; } function start() public auth note { stopped = false; } } ////// lib/zeppelin-solidity/src/proxy/Initializable.sol // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version /* pragma solidity >=0.4.24 <0.7.0; */ /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } ////// src/interfaces/IELIP002.sol /* pragma solidity ^0.6.7; */ /** @title IELIP002 @dev See https://github.com/evolutionlandorg/furnace/blob/main/elip-002.md @author echo.hu@itering.com */ interface IELIP002 { struct Item { // index of `Formula` uint256 index; // strength rate uint128 rate; uint16 objClassExt; uint16 class; uint16 grade; // element prefer uint16 prefer; // major material address major; uint256 id; // amount of minor material address minor; uint256 amount; } /** @dev `Enchanted` MUST emit when item is enchanted. The `user` argument MUST be the address of an account/contract that is approved to make the enchant (SHOULD be msg.sender). The `tokenId` argument MUST be token Id of the item which it is enchanted. The `index` argument MUST be index of the `Formula`. The `rate` argument MUST be rate of minor material. The `objClassExt` argument MUST be extension of `ObjectClass`. The `class` argument MUST be class of the item. The `grade` argument MUST be grade of the item. The `prefer` argument MUST be prefer of the item. The `major` argument MUST be token address of major material. The `id` argument MUST be token id of major material. The `minor` argument MUST be token address of minor material. The `amount` argument MUST be token amount of minor material. The `now` argument MUST be timestamp of enchant. */ event Enchanced( address indexed user, uint256 indexed tokenId, uint256 index, uint128 rate, uint16 objClassExt, uint16 class, uint16 grade, uint16 prefer, address major, uint256 id, address minor, uint256 amount, uint256 now ); /** @dev `Disenchanted` MUST emit when item is disenchanted. The `user` argument MUST be the address of an account/contract that is approved to make the disenchanted (SHOULD be msg.sender). The `tokenId` argument MUST be token Id of the item which it is disenchated. The `majors` argument MUST be major token addresses of major material. The `id` argument MUST be token ids of major material. The `minor` argument MUST be token addresses of minor material. The `amount` argument MUST be token amounts of minor material. */ event Disenchanted( address indexed user, uint256 tokenId, address major, uint256 id, address minor, uint256 amount ); /** @notice Caller must be owner of tokens to enchant. @dev Enchant function, Enchant a new NFT token from ERC721 tokens and ERC20 tokens. Enchant rule is according to `Formula`. MUST revert if `_index` is not in `formula`. MUST revert on any other error. @param _index Index of formula to enchant. @param _id ID of NFT tokens. @param _token Address of FT token. @return { "tokenId": "New Token ID of Enchanting." } */ function enchant( uint256 _index, uint256 _id, address _token ) external returns (uint256); // { // ### smelt // 1. check Formula rule by index // 2. transfer FT and NFT to address(this) // 3. track FTs NFT to new NFT // 4. mint new NFT to caller // } /** @notice Caller must be owner of token id to disenchat. @dev Disenchant function, A enchanted NFT can be disenchanted into origin ERC721 tokens and ERC20 tokens recursively. MUST revert on any other error. @param _id Token ID to disenchant. @param _depth Depth of disenchanting recursively. */ function disenchant(uint256 _id, uint256 _depth) external; // { // ### disenchant // 1. tranfer _id to address(this) // 2. burn new NFT // 3. delete track FTs NFTs to new NFT // 4. transfer FNs NFTs to owner // } /** @dev Get base info of item. @param _tokenId Token id of item. @return { "objClassExt": "Extension of `ObjectClass`.", "class": "Class of the item.", "grade": "Grade of the item." } */ function getBaseInfo(uint256 _tokenId) external view returns ( uint16, uint16, uint16 ); /** @dev Get rate of item. @param _tokenId Token id of item. @param _element Element item prefer. @return { "rate": "strength rate of item." } */ function getRate(uint256 _tokenId, uint256 _element) external view returns (uint256); function getPrefer(uint256 _tokenId) external view returns (uint16); function getObjectClassExt(uint256 _tokenId) external view returns (uint16); } ////// src/interfaces/IFormula.sol /* pragma solidity ^0.6.7; */ /** @title IFormula @author echo.hu@itering.com */ interface IFormula { struct FormulaEntry { // item name bytes32 name; // strength rate uint128 rate; // extension of `ObjectClass` uint16 objClassExt; uint16 class; uint16 grade; bool canDisenchant; // if it is removed // uint256 enchantTime; // uint256 disenchantTime; // uint256 loseRate; bool disable; // minor material info bytes32 minor; uint256 amount; // major material info // [address token, uint16 objectClassExt, uint16 class, uint16 grade] address majorAddr; uint16 majorObjClassExt; uint16 majorClass; uint16 majorGrade; } event AddFormula( uint256 indexed index, bytes32 name, uint128 rate, uint16 objClassExt, uint16 class, uint16 grade, bool canDisenchant, bytes32 minor, uint256 amount, address majorAddr, uint16 majorObjClassExt, uint16 majorClass, uint16 majorGrade ); event DisableFormula(uint256 indexed index); event EnableFormula(uint256 indexed index); /** @notice Only governance can add `formula`. @dev Add a formula rule. MUST revert if length of `_majors` is not the same as length of `_class`. MUST revert if length of `_minors` is not the same as length of `_mins` and `_maxs. MUST revert on any other error. @param _name New enchanted NFT name. @param _rate New enchanted NFT rate. @param _objClassExt New enchanted NFT objectClassExt. @param _class New enchanted NFT class. @param _grade New enchanted NFT grade. @param _minor FT Token address of minor meterail for enchanting. @param _amount FT Token amount of minor meterail for enchanting. @param _majorAddr FT token address of major meterail for enchanting. @param _majorObjClassExt FT token objectClassExt of major meterail for enchanting. @param _majorClass FT token class of major meterail for enchanting. @param _majorGrade FT token grade of major meterail for enchanting. */ function insert( bytes32 _name, uint128 _rate, uint16 _objClassExt, uint16 _class, uint16 _grade, bool _canDisenchant, bytes32 _minor, uint256 _amount, address _majorAddr, uint16 _majorObjClassExt, uint16 _majorClass, uint16 _majorGrade ) external; /** @notice Only governance can enable `formula`. @dev Enable a formula rule. MUST revert on any other error. @param _index index of formula. */ function disable(uint256 _index) external; /** @notice Only governance can disble `formula`. @dev Disble a formula rule. MUST revert on any other error. @param _index index of formula. */ function enable(uint256 _index) external; /** @dev Returns the length of the formula. 0x1f7b6d32 */ function length() external view returns (uint256); /** @dev Returns the availability of the formula. */ function isDisable(uint256 _index) external view returns (bool); /** @dev returns the minor material of the formula. */ function getMinor(uint256 _index) external view returns (bytes32, uint256); /** @dev Decode major info of the major. 0x6ef2fd27 @return { "token": "Major token address.", "objClassExt": "Major token objClassExt.", "class": "Major token class.", "grade": "Major token address." } */ function getMajorInfo(uint256 _index) external view returns ( address, uint16, uint16, uint16 ); /** @dev Returns meta info of the item. 0x78533046 @return { "objClassExt": "Major token objClassExt.", "class": "Major token class.", "grade": "Major token address.", "base": "Base strength rate.", "enhance": "Enhance strength rate.", } */ function getMetaInfo(uint256 _index) external view returns ( uint16, uint16, uint16, uint128 ); /** @dev returns canDisenchant of the formula. */ function canDisenchant(uint256 _index) external view returns (bool); } ////// src/interfaces/IMetaDataTeller.sol /* pragma solidity ^0.6.7; */ interface IMetaDataTeller { function addTokenMeta( address _token, uint16 _grade, uint112 _strengthRate ) external; function getObjClassExt(address _token, uint256 _id) external view returns (uint16 objClassExt); //0xf666196d function getMetaData(address _token, uint256 _id) external view returns (uint16, uint16, uint16); //0x7999a5cf function getPrefer(bytes32 _minor, address _token) external view returns (uint256); //0x33281815 function getRate( address _token, uint256 _id, uint256 _index ) external view returns (uint256); //0xf8350ed0 function isAllowed(address _token, uint256 _id) external view returns (bool); } ////// src/interfaces/IObjectOwnership.sol /* pragma solidity ^0.6.7; */ interface IObjectOwnership { function mintObject(address _to, uint128 _objectId) external returns (uint256 _tokenId); function burn(address _to, uint256 _tokenId) external; } ////// src/interfaces/ISettingsRegistry.sol /* pragma solidity ^0.6.7; */ interface ISettingsRegistry { function uintOf(bytes32 _propertyName) external view returns (uint256); function stringOf(bytes32 _propertyName) external view returns (string memory); function addressOf(bytes32 _propertyName) external view returns (address); function bytesOf(bytes32 _propertyName) external view returns (bytes memory); function boolOf(bytes32 _propertyName) external view returns (bool); function intOf(bytes32 _propertyName) external view returns (int); function setUintProperty(bytes32 _propertyName, uint _value) external; function setStringProperty(bytes32 _propertyName, string calldata _value) external; function setAddressProperty(bytes32 _propertyName, address _value) external; function setBytesProperty(bytes32 _propertyName, bytes calldata _value) external; function setBoolProperty(bytes32 _propertyName, bool _value) external; function setIntProperty(bytes32 _propertyName, int _value) external; function getValueTypeOf(bytes32 _propertyName) external view returns (uint /* SettingsValueTypes */ ); event ChangeProperty(bytes32 indexed _propertyName, uint256 _type); } ////// src/ItemBase.sol /* pragma solidity ^0.6.7; */ /* import "ds-math/math.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "zeppelin-solidity/proxy/Initializable.sol"; */ /* import "./interfaces/IELIP002.sol"; */ /* import "./interfaces/IFormula.sol"; */ /* import "./interfaces/ISettingsRegistry.sol"; */ /* import "./interfaces/IMetaDataTeller.sol"; */ /* import "./interfaces/IObjectOwnership.sol"; */ contract ItemBase is Initializable, DSStop, DSMath, IELIP002 { // 0x434f4e54524143545f4d455441444154415f54454c4c45520000000000000000 bytes32 public constant CONTRACT_METADATA_TELLER = "CONTRACT_METADATA_TELLER"; // 0x434f4e54524143545f464f524d554c4100000000000000000000000000000000 bytes32 public constant CONTRACT_FORMULA = "CONTRACT_FORMULA"; // 0x434f4e54524143545f4f424a4543545f4f574e45525348495000000000000000 bytes32 public constant CONTRACT_OBJECT_OWNERSHIP = "CONTRACT_OBJECT_OWNERSHIP"; //0x434f4e54524143545f4c505f454c454d454e545f544f4b454e00000000000000 bytes32 public constant CONTRACT_LP_ELEMENT_TOKEN = "CONTRACT_LP_ELEMENT_TOKEN"; //0x434f4e54524143545f454c454d454e545f544f4b454e00000000000000000000 bytes32 public constant CONTRACT_ELEMENT_TOKEN = "CONTRACT_ELEMENT_TOKEN"; // rate precision uint128 public constant RATE_PRECISION = 10**8; // save about 200 gas when contract create bytes4 private constant _SELECTOR_TRANSFERFROM = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); bytes4 private constant _SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); /*** STORAGE ***/ uint128 public lastItemObjectId; ISettingsRegistry public registry; mapping(uint256 => Item) public tokenId2Item; // mapping(uint256 => mapping(uint256 => uint256)) public tokenId2Rate; /** * @dev Same with constructor, but is used and called by storage proxy as logic contract. */ function initialize(address _registry) public initializer { owner = msg.sender; emit LogSetOwner(msg.sender); registry = ISettingsRegistry(_registry); // trick test // lastItemObjectId = 1000000; } function _safeTransferFrom( address token, address from, address to, uint256 value ) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(_SELECTOR_TRANSFERFROM, from, to, value)); // solhint-disable-line require( success && (data.length == 0 || abi.decode(data, (bool))), "Furnace: TRANSFERFROM_FAILED" ); } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(_SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'Furnace: TRANSFER_FAILED'); } function enchant( uint256 _index, uint256 _id, address _token ) external override stoppable returns (uint256) { address teller = registry.addressOf(CONTRACT_METADATA_TELLER); address formula = registry.addressOf(CONTRACT_FORMULA); require( IFormula(formula).isDisable(_index) == false, "Furnace: FORMULA_DISABLE" ); (address majorAddr, uint16 originClass, uint16 originPrefer) = _dealMajor(teller, formula, _index, _id); (uint16 prefer, uint256 amount) = _dealMinor(teller, formula, _index, _token); if (originClass > 0) { require(prefer == originPrefer, "Furnace: INVALID_PREFER"); } return _enchanceItem(formula, _index, prefer, majorAddr, _id, _token, amount); } function _dealMajor( address teller, address formula, uint256 _index, uint256 _id ) private returns (address, uint16, uint16) { ( address majorAddress, uint16 majorObjClassExt, uint16 majorClass, uint16 majorGrade ) = IFormula(formula).getMajorInfo(_index); (uint16 objectClassExt, uint16 class, uint16 grade) = IMetaDataTeller(teller).getMetaData(majorAddress, _id); require( objectClassExt == majorObjClassExt, "Furnace: INVALID_OBJECTCLASSEXT" ); require(class == majorClass, "Furnace: INVALID_CLASS"); require(grade == majorGrade, "Furnace: INVALID_GRADE"); _safeTransferFrom(majorAddress, msg.sender, address(this), _id); uint16 prefer = 0; if (class > 0) { prefer = getPrefer(_id); } return (majorAddress, class, prefer); } function _dealMinor( address teller, address formula, uint256 _index, address _token ) private returns (uint16, uint256) { (bytes32 minor, uint256 amount) = IFormula(formula).getMinor(_index); uint16 prefer = 0; uint256 element = IMetaDataTeller(teller).getPrefer(minor, _token); require(element > 0 && element < 6, "Furnace: INVALID_MINOR"); prefer |= uint16(1 << element); require(amount <= uint128(-1), "Furnace: VALUE_OVERFLOW"); _safeTransferFrom(_token, msg.sender, address(this), amount); return (prefer, amount); } function _enchanceItem( address formula, uint256 _index, uint16 _prefer, address _major, uint256 _id, address _minor, uint256 _amount ) private returns (uint256) { lastItemObjectId += 1; require(lastItemObjectId <= uint128(-1), "Furnace: OBJECTID_OVERFLOW"); (uint16 objClassExt, uint16 class, uint16 grade, uint128 rate) = IFormula(formula).getMetaInfo(_index); Item memory item = Item({ index: _index, rate: rate, objClassExt: objClassExt, class: class, grade: grade, prefer: _prefer, major: _major, id: _id, minor: _minor, amount: _amount }); uint256 tokenId = IObjectOwnership(registry.addressOf(CONTRACT_OBJECT_OWNERSHIP)) .mintObject(msg.sender, lastItemObjectId); tokenId2Item[tokenId] = item; emit Enchanced( msg.sender, tokenId, item.index, item.rate, item.objClassExt, item.class, item.grade, item.prefer, item.major, item.id, item.minor, item.amount, now // solhint-disable-line ); return tokenId; } function _disenchantItem(address to, uint256 tokenId) private { IObjectOwnership(registry.addressOf(CONTRACT_OBJECT_OWNERSHIP)).burn( to, tokenId ); delete tokenId2Item[tokenId]; } function disenchant(uint256 _id, uint256 _depth) external override stoppable { _safeTransferFrom( registry.addressOf(CONTRACT_OBJECT_OWNERSHIP), msg.sender, address(this), _id ); _disenchant(_id, _depth); } function _disenchant(uint256 _tokenId, uint256 _depth) private { ( uint16 class, bool canDisenchant, address major, uint256 id, address minor, uint256 amount ) = getEnchantedInfo(_tokenId); require(_depth > 0, "Furnace: INVALID_DEPTH"); require(canDisenchant == true, "Furnace: DISENCHANT_DISABLE"); require(class > 0, "Furnace: INVALID_CLASS"); _disenchantItem(address(this), _tokenId); if (_depth == 1 || class == 0) { _safeTransferFrom(major, address(this), msg.sender, id); } else { _disenchant(id, _depth - 1); } _safeTransfer(minor, msg.sender, amount); emit Disenchanted(msg.sender, _tokenId, major, id, minor, amount); } function getRate(uint256 _tokenId, uint256 _element) public view override returns (uint256) { Item storage item = tokenId2Item[_tokenId]; if (uint256(item.prefer) & (1 << _element) > 0) { return uint256(item.rate); } return uint256(item.rate / 2); } function getBaseInfo(uint256 _tokenId) public view override returns ( uint16, uint16, uint16 ) { Item storage item = tokenId2Item[_tokenId]; return (item.objClassExt, item.class, item.grade); } function getPrefer(uint256 _tokenId) public view override returns (uint16) { return tokenId2Item[_tokenId].prefer; } function getObjectClassExt(uint256 _tokenId) public view override returns (uint16) { return tokenId2Item[_tokenId].objClassExt; } function getEnchantedInfo(uint256 _tokenId) public view returns ( uint16, bool, address, uint256, address, uint256 ) { Item storage item = tokenId2Item[_tokenId]; return ( item.class, IFormula(registry.addressOf(CONTRACT_FORMULA)).canDisenchant(item.index), item.major, item.id, item.minor, item.amount ); } }
/ src/interfaces/IFormula.sol pragma solidity ^0.6.7; //
interface IFormula { function getRate(uint256 _tokenId, uint256 _element) external view returns (uint256); function getPrefer(uint256 _tokenId) external view returns (uint16); function getObjectClassExt(uint256 _tokenId) external view returns (uint16); } @title IFormula @author echo.hu@itering.com struct FormulaEntry { bytes32 name; uint128 rate; uint16 objClassExt; uint16 class; uint16 grade; bool canDisenchant; bool disable; bytes32 minor; uint256 amount; address majorAddr; uint16 majorObjClassExt; uint16 majorClass; uint16 majorGrade; } event AddFormula( uint256 indexed index, bytes32 name, uint128 rate, uint16 objClassExt, uint16 class, uint16 grade, bool canDisenchant, bytes32 minor, uint256 amount, address majorAddr, uint16 majorObjClassExt, uint16 majorClass, uint16 majorGrade ); event DisableFormula(uint256 indexed index); event EnableFormula(uint256 indexed index); @dev Add a formula rule. MUST revert if length of `_majors` is not the same as length of `_class`. MUST revert if length of `_minors` is not the same as length of `_mins` and `_maxs. MUST revert on any other error. @param _name New enchanted NFT name. @param _rate New enchanted NFT rate. @param _objClassExt New enchanted NFT objectClassExt. @param _class New enchanted NFT class. @param _grade New enchanted NFT grade. @param _minor FT Token address of minor meterail for enchanting. @param _amount FT Token amount of minor meterail for enchanting. @param _majorAddr FT token address of major meterail for enchanting. @param _majorObjClassExt FT token objectClassExt of major meterail for enchanting. @param _majorClass FT token class of major meterail for enchanting. @param _majorGrade FT token grade of major meterail for enchanting. @notice Only governance can add `formula`. function insert( bytes32 _name, uint128 _rate, uint16 _objClassExt, uint16 _class, uint16 _grade, bool _canDisenchant, bytes32 _minor, uint256 _amount, address _majorAddr, uint16 _majorObjClassExt, uint16 _majorClass, uint16 _majorGrade ) external; @notice Only governance can enable `formula`. @dev Enable a formula rule. MUST revert on any other error. @param _index index of formula. function disable(uint256 _index) external; @notice Only governance can disble `formula`. @dev Disble a formula rule. MUST revert on any other error. @param _index index of formula. function enable(uint256 _index) external; @dev Returns the length of the formula. 0x1f7b6d32 function length() external view returns (uint256); @dev Returns the availability of the formula. function isDisable(uint256 _index) external view returns (bool); @dev returns the minor material of the formula. function getMinor(uint256 _index) external view returns (bytes32, uint256); @dev Decode major info of the major. 0x6ef2fd27 @return { "token": "Major token address.", "objClassExt": "Major token objClassExt.", "class": "Major token class.", "grade": "Major token address." } function getMajorInfo(uint256 _index) external view returns ( address, uint16, uint16, uint16 ); @dev Returns meta info of the item. 0x78533046 @return { "objClassExt": "Major token objClassExt.", "class": "Major token class.", "grade": "Major token address.", "base": "Base strength rate.", "enhance": "Enhance strength rate.", } }
441,360
pragma solidity 0.5.8; library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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; 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 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); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) public _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 public _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner,address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from,address to,uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } function increaseAllowance(address spender,uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender,uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } 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); } } contract ProfitToken is ERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (uint256 _initialAmount, string memory name, uint8 decimals, string memory symbol) public { _name = name; _symbol = symbol; _decimals = decimals; _totalSupply = _initialAmount.mul(10 ** uint256(_decimals)); _balances[0xD136c8d017927A3450F3741315d0C4ba06253992] = _initialAmount.mul(10 ** uint256(_decimals)); } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } }
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; }
14,867,701
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "../interfaces/ERC20Spec.sol"; import "../interfaces/ERC721SpecExt.sol"; import "../lib/SafeERC20.sol"; import "../utils/UpgradeableAccessControl.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; /** * @title Upgradeable ERC721 Implementation * * @notice Zeppelin based ERC721 implementation, supporting token enumeration * (ERC721EnumerableUpgradeable) and flexible token URI management (ERC721URIStorageUpgradeable) * * // TODO: consider allowing to override each individual token URI * * @dev Based on Zeppelin ERC721EnumerableUpgradeable and ERC721URIStorageUpgradeable with some modifications * to tokenURI function * * @author Basil Gorin */ abstract contract UpgradeableERC721 is MintableERC721, BurnableERC721, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, UpgradeableAccessControl { // using ERC20.transfer wrapper from OpenZeppelin adopted SafeERC20 using SafeERC20 for ERC20; /** * @dev Base URI is used to construct ERC721Metadata.tokenURI as * `base URI + token ID` if token URI is not set (not present in `_tokenURIs` mapping) * * @dev For example, if base URI is https://api.com/token/, then token #1 * will have an URI https://api.com/token/1 * * @dev If token URI is set with `setTokenURI()` it will be returned as is via `tokenURI()` */ string public baseURI; /** * @dev Empty reserved space in storage. The size of the __gap array is calculated so that * the amount of storage used by a contract always adds up to the 50. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; /** * @notice Enables ERC721 transfers of the tokens * (transfer by the token owner himself) * @dev Feature FEATURE_TRANSFERS must be enabled in order for * `transferFrom()` function to succeed when executed by token owner */ uint32 public constant FEATURE_TRANSFERS = 0x0000_0001; /** * @notice Enables ERC721 transfers on behalf * (transfer by someone else on behalf of token owner) * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for * `transferFrom()` function to succeed whe executed by approved operator * @dev Token owner must call `approve()` or `setApprovalForAll()` * first to authorize the transfer on behalf */ uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002; /** * @notice Enables token owners to burn their own tokens * * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by token owner */ uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008; /** * @notice Enables approved operators to burn tokens on behalf of their owners * * @dev Feature FEATURE_BURNS_ON_BEHALF must be enabled in order for * `burn()` function to succeed when called by approved operator */ uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @notice Token destroyer is responsible for destroying (burning) * tokens owned by an arbitrary address * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens * (calling `burn` function) */ uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000; /** * @notice URI manager is responsible for managing base URI * part of the token URI ERC721Metadata interface * * @dev Role ROLE_URI_MANAGER allows updating the base URI * (executing `setBaseURI` function) */ uint32 public constant ROLE_URI_MANAGER = 0x0004_0000; /** * @notice People do mistakes and may send ERC20 tokens by mistake; since * NFT smart contract is not designed to accept and hold any ERC20 tokens, * it allows the rescue manager to "rescue" such lost tokens * * @notice Rescue manager is responsible for "rescuing" ERC20 tokens accidentally * sent to the smart contract * * @dev Role ROLE_RESCUE_MANAGER allows withdrawing any ERC20 tokens stored * on the smart contract balance */ uint32 public constant ROLE_RESCUE_MANAGER = 0x0008_0000; /** * @dev Fired in _mint() and all the dependent functions like mint(), safeMint() * * @param _by an address which executed update * @param _to an address token was minted to * @param _tokenId token ID minted */ event Minted(address indexed _by, address indexed _to, uint256 indexed _tokenId); /** * @dev Fired in _burn() and all the dependent functions like burn() * * @param _by an address which executed update * @param _from an address token was burnt from * @param _tokenId token ID burnt */ event Burnt(address indexed _by, address indexed _from, uint256 indexed _tokenId); /** * @dev Fired in setBaseURI() * * @param _by an address which executed update * @param oldVal old _baseURI value * @param newVal new _baseURI value */ event BaseURIUpdated(address indexed _by, string oldVal, string newVal); /** * @dev Fired in setTokenURI() * * @param _by an address which executed update * @param tokenId token ID which URI was updated * @param oldVal old _baseURI value * @param newVal new _baseURI value */ event TokenURIUpdated(address indexed _by, uint256 tokenId, string oldVal, string newVal); /** * @dev "Constructor replacement" for upgradeable, must be execute immediately after deployment * see https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializers * * @param _name token name (ERC721Metadata) * @param _symbol token symbol (ERC721Metadata) * @param _owner smart contract owner having full privileges */ function _postConstruct(string memory _name, string memory _symbol, address _owner) internal virtual initializer { // execute all parent initializers in cascade __ERC721_init(_name, _symbol); __ERC721Enumerable_init_unchained(); __ERC721URIStorage_init_unchained(); UpgradeableAccessControl._postConstruct(_owner); } /** * @inheritdoc IERC165Upgradeable */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { // calculate based on own and inherited interfaces return ERC721EnumerableUpgradeable.supportsInterface(interfaceId) || interfaceId == type(MintableERC721).interfaceId || interfaceId == type(BurnableERC721).interfaceId; } /** * @dev Restricted access function which updates base URI used to construct * ERC721Metadata.tokenURI * * @dev Requires executor to have ROLE_URI_MANAGER permission * * @param __baseURI new base URI to set */ function setBaseURI(string memory __baseURI) public virtual { // verify the access permission require(isSenderInRole(ROLE_URI_MANAGER), "access denied"); // emit an event first - to log both old and new values emit BaseURIUpdated(msg.sender, baseURI, __baseURI); // and update base URI baseURI = __baseURI; } /** * @inheritdoc ERC721Upgradeable */ function _baseURI() internal view virtual override returns (string memory) { // just return stored public value to support Zeppelin impl return baseURI; } /** * @dev Sets the token URI for the token defined by its ID * * @param _tokenId an ID of the token to set URI for * @param _tokenURI token URI to set */ function setTokenURI(uint256 _tokenId, string memory _tokenURI) public virtual { // verify the access permission require(isSenderInRole(ROLE_URI_MANAGER), "access denied"); // we do not verify token existence: we want to be able to // preallocate token URIs before tokens are actually minted // emit an event first - to log both old and new values emit TokenURIUpdated(msg.sender, _tokenId, "zeppelin", _tokenURI); // and update token URI - delegate to ERC721URIStorage _setTokenURI(_tokenId, _tokenURI); } /** * @inheritdoc ERC721URIStorageUpgradeable */ function _setTokenURI(uint256 _tokenId, string memory _tokenURI) internal virtual override { // delegate to ERC721URIStorage impl return super._setTokenURI(_tokenId, _tokenURI); } /** * @inheritdoc ERC721Upgradeable */ function tokenURI(uint256 _tokenId) public view virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { // delegate to ERC721URIStorage impl return ERC721URIStorageUpgradeable.tokenURI(_tokenId); } /** * @notice Checks if specified token exists * * @dev Returns whether the specified token ID has an ownership * information associated with it * @param _tokenId ID of the token to query existence for * @return whether the token exists (true - exists, false - doesn't exist) */ function exists(uint256 _tokenId) public view virtual override returns (bool) { // delegate to super implementation return _exists(_tokenId); } /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Unsafe: doesn't execute `onERC721Received` on the receiver. * Prefer the use of `saveMint` instead of `mint`. * * @dev Requires executor to have `ROLE_TOKEN_CREATOR` permission * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function mint(address _to, uint256 _tokenId) public virtual override { // mint token - delegate to `_mint` _mint(_to, _tokenId); } /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Requires executor to have `ROLE_TOKEN_CREATOR` permission * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param _data additional data with no specified format, sent in call to `_to` */ function safeMint(address _to, uint256 _tokenId, bytes memory _data) public virtual override { // mint token safely - delegate to `_safeMint` _safeMint(_to, _tokenId, _data); } /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Requires executor to have `ROLE_TOKEN_CREATOR` permission * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function safeMint(address _to, uint256 _tokenId) public virtual override { // mint token safely - delegate to `_safeMint` _safeMint(_to, _tokenId); } /** * @dev Destroys the token with token ID specified * * @dev Requires executor to have `ROLE_TOKEN_DESTROYER` permission * or FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features to be enabled * * @dev Can be disabled by the contract creator forever by disabling * FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features and then revoking * its own roles to burn tokens and to enable burning features * * @param _tokenId ID of the token to burn */ function burn(uint256 _tokenId) public virtual override { // burn token - delegate to `_burn` _burn(_tokenId); } /** * @inheritdoc ERC721Upgradeable */ function _mint(address _to, uint256 _tokenId) internal virtual override { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR), "access denied"); // delegate to super implementation super._mint(_to, _tokenId); // emit an additional event to better track who performed the operation emit Minted(msg.sender, _to, _tokenId); } /** * @inheritdoc ERC721Upgradeable */ function _burn(uint256 _tokenId) internal virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { // read token owner data // verifies token exists under the hood address _from = ownerOf(_tokenId); // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // verify sender is either token owner, or approved by the token owner to burn tokens require(msg.sender == _from || msg.sender == getApproved(_tokenId) || isApprovedForAll(_from, msg.sender), "access denied"); } // delegate to the super implementation with URI burning ERC721URIStorageUpgradeable._burn(_tokenId); // emit an additional event to better track who performed the operation emit Burnt(msg.sender, _from, _tokenId); } /** * @inheritdoc ERC721Upgradeable */ function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { // for transfers only - verify if transfers are enabled require(_from == address(0) || _to == address(0) // won't affect minting/burning || _from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS) || _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), _from == msg.sender? "transfers are disabled": "transfers on behalf are disabled"); // delegate to ERC721Enumerable impl ERC721EnumerableUpgradeable._beforeTokenTransfer(_from, _to, _tokenId); } /** * @dev Restricted access function to rescue accidentally sent ERC20 tokens, * the tokens are rescued via `transfer` function call on the * contract address specified and with the parameters specified: * `_contract.transfer(_to, _value)` * * @dev Requires executor to have `ROLE_RESCUE_MANAGER` permission * * @param _contract smart contract address to execute `transfer` function on * @param _to to address in `transfer(_to, _value)` * @param _value value to transfer in `transfer(_to, _value)` */ function rescueErc20(address _contract, address _to, uint256 _value) public { // verify the access permission require(isSenderInRole(ROLE_RESCUE_MANAGER), "access denied"); // perform the transfer as requested, without any checks ERC20(_contract).safeTransfer(_to, _value); } }
Creates new token with token ID specified and assigns an ownership `_to` for this token Checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received` on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. Requires executor to have `ROLE_TOKEN_CREATOR` permission _to an address to mint token to _tokenId ID of the token to mint _data additional data with no specified format, sent in call to `_to`/ mint token safely - delegate to `_safeMint`
function safeMint(address _to, uint256 _tokenId, bytes memory _data) public virtual override { _safeMint(_to, _tokenId, _data); }
12,902,176
pragma solidity >=0.4.22 <0.8.0; import "./IERC20.sol"; contract CarRental { struct RentalCar { // Estrutura destinada às credenciais do carro alugado uint256 id; bool isAvailable; // disponibilidade bool isActive; // uint256 price; address owner; uint256 activeRentalId; } struct Rental{ // Estrutura destinada às propriedades do aluguer uint256 id; // identificador do aluguer uint256 carId; // id do carro uint256 price; // preço uint256 timeOfRental; // timestamp do inicio do aluguer uint256 timeOfDelivery; // timestamp do fim do aluguer uint256[] eventsOccured; // eventos ocorridos bool isFinished; // booleana correspondente ao fim do aluguer } RentalCar[] internal cars; // Inicialização das estruturas Rental[] internal rentals; // Inicialização das estruturas mapping(uint256 => RentalCar) internal transactionApproved; uint32 internal privateId = 0; // Events event CreateCar(uint256 id, bool isAvailable, bool isActive, uint256 price, address owner, uint256 activeRentalId); // Criação do veículo event EditedCar(uint256 id, bool available, uint256 price); // Edição do veículo event DeletedCar(uint256 id); // Eliminar um veículo event RentStarted(uint256 id, uint256 carId, uint256 price, uint256 timeOfRental, uint256 timeOfDelivery,uint256[] eventsOccured, bool isFinished); // Inicialização do contrato de aluguer event RentEnded(uint256 id, uint256 carId, uint256 timeOfDelivery,uint256[] eventsOccured, bool isFinished); // Cessação do contrato de aluguer event ExcessVelocity(uint256 id, string description); // Evento de alerta de excesso de velocidade event SuddenBreak(uint256 id, string description); // Evento de alerta de travagem repentina event Accident(uint256 id, string description); // Evento de alerta de acidente event Breakdown(uint256 id, string description); // Evento de avaria // This initializes our contract state (sets enum to Pending once the program starts) constructor () public { } // Função de criação do veículo function createVehicle(uint256 price) public { uint256 vehicleId = cars.length; RentalCar memory car = RentalCar( vehicleId, true, true, price, msg.sender, // endereço do owner, 0 ); cars.push(car); emit CreateCar(vehicleId, true, true, price, msg.sender, 0); // registar o evento } // Função de eliminar veículo function delVehicle(uint256 id) public { // Obrigatório para a execução da função require(cars[id].isActive == true, "car is inactive"); require(cars[id].isAvailable == true, "car is unavailable"); require(msg.sender == cars[id].owner, "not the car's owner"); cars[id].isAvailable = false; cars[id].isActive = false; emit DeletedCar(id); // registar o evento } // Função de editar o veículo function editVehicle(uint256 id, uint256 price, bool status) public { // Obrigatório para a execução da função require(cars[id].isActive == true, "car is inactive"); // require(cars[id].isAvailable == true, "car is unavailable"); require(msg.sender == cars[id].owner, "not the car's owner"); cars[id].price = price; cars[id].isAvailable = status; emit EditedCar(id, status, price); } // Função para iniciar o aluguer function carRenting(uint256 id) public payable returns (string memory) { // Obrigatório para a execução da função require(cars[id].isActive == true, "car is inactive"); require(msg.sender != cars[id].owner); require(msg.value >= cars[id].price); require(cars[id].isAvailable == true); uint256 rentalId = rentals.length; Rental memory rental = Rental( rentalId, id, cars[id].price, block.timestamp, 0, new uint256[](0), false ); rentals.push(rental); cars[id].activeRentalId = rentalId; payable(address(this)).transfer(cars[id].price); // cast a payable address cars[id].isAvailable = false; emit RentStarted(rentalId, id, cars[id].price, block.timestamp, 0, new uint256[](0), false); // registar o evento } // Função para terminar o aluguer function killRenting(uint256 id) public returns (string memory) { // Função para eliminar o aluguer // Obrigatório para a execução da função require(cars[id].isActive == true, "car is inactive"); require(msg.sender == cars[id].owner); require(cars[id].isAvailable == false); require(!rentals[cars[id].activeRentalId].isFinished); rentals[cars[id].activeRentalId].timeOfDelivery = block.timestamp; rentals[cars[id].activeRentalId].isFinished = true; msg.sender.transfer(cars[id].price); cars[id].isAvailable = true; emit RentEnded(cars[id].activeRentalId, id, block.timestamp, rentals[cars[id].activeRentalId].eventsOccured, true); } // Função para associar os eventos ao veículo alugado function emitEvent(uint256 id, string memory description, uint8 eventCode) public{ // Obrigatório para a execução da função require(cars[id].isActive == false, "car is inactive"); require(!rentals[cars[id].activeRentalId].isFinished); if(eventCode == 1){ emit ExcessVelocity(id, description); }else if(eventCode == 2){ emit SuddenBreak(id, description); }else if(eventCode == 3){ emit Accident(id, description); }else if(eventCode == 4){ emit Breakdown(id, description); } rentals[cars[id].activeRentalId].eventsOccured.push(eventCode); } }
Obrigatório para a execução da função require(cars[id].isAvailable == true, "car is unavailable");
function editVehicle(uint256 id, uint256 price, bool status) public { require(cars[id].isActive == true, "car is inactive"); require(msg.sender == cars[id].owner, "not the car's owner"); cars[id].price = price; cars[id].isAvailable = status; emit EditedCar(id, status, price); }
5,419,886
// SPDX-License-Identifier: ISC pragma solidity ^0.8.4; import "../interfaces/IERC20.sol"; import "../utils/Context.sol"; import "../interfaces/IWhitelist.sol"; contract PrivateSale is Context { /** * Investment Structure. */ struct Investment { uint256 _usdt; uint256 _usdc; uint256 _busd; } /** * @dev `_usdt` represents the usdt smart contract address. * `_admin` is the account that controls the sale. */ address private _usdt; address private _usdc; address private _busd; address private _whitelist; address private _admin; /** * @dev stores the total unique investement addresses. */ uint256 private _investors; mapping(uint256 => address) private _investor; /** * @dev stores the usdt invested by each account. */ mapping(address => Investment) private _investment; /** * @dev checks if the investor already invested. */ mapping(address => bool) private _isInvestor; /** * @dev checks if `caller` is `_admin` * reverts if the `caller` is not the `_admin` account. */ modifier onlyAdmin() { require(_admin == msgSender(), "Error: caller not admin"); _; } /** * @dev is emitted when a successful investment is made. */ event Invest(address indexed from, uint256 amount, bytes32 currency); constructor(address _usdtAddress, address _usdcAddress, address _busdAddress, address _whitelistOracle) { _admin = msgSender(); _usdt = _usdtAddress; _usdc = _usdcAddress; _busd = _busdAddress; _whitelist = _whitelistOracle; } /** * @dev invests `_usdtAmount` to the vesting smart contract. * * Requirements: * `_usdtAmount` should be approved by `caller` account. * `_usdtAmount` should be greater or equal to balance of `caller` account */ function investUsdt(uint256 _usdtAmount) public virtual returns (bool) { require(IWhiteList(_whitelist).whitelisted(msgSender()), "Error: investor not elligible for purchase"); uint256 balance = IERC20(_usdt).balanceOf(msgSender()); uint256 allowance = IERC20(_usdt).allowance(msgSender(), address(this)); require(balance >= _usdtAmount, "Error: insufficient USDT Balance"); require( allowance >= _usdtAmount, "Error: allowance less than spending" ); if(!_isInvestor[msgSender()]) { _investors += 1; _investor[_investors] = msgSender(); } Investment storage i = _investment[msgSender()]; i._usdt += _usdtAmount; emit Invest(msgSender(), _usdtAmount, bytes32("USDT")); IERC20(_usdt).transferFrom(msgSender(), address(this), _usdtAmount); return true; } /** * @dev invests `_usdcAmount` to the vesting smart contract. * * Requirements: * `_usdcAmount` should be approved by `caller` account. * `_usdcAmount` should be greater or equal to balance of `caller` account */ function investUsdc(uint256 _usdcAmount) public virtual returns (bool) { require(IWhiteList(_whitelist).whitelisted(msgSender()), "Error: investor not elligible for purchase"); uint256 balance = IERC20(_usdc).balanceOf(msgSender()); uint256 allowance = IERC20(_usdc).allowance(msgSender(), address(this)); require(balance >= _usdcAmount, "Error: insufficient USDC Balance"); require( allowance >= _usdcAmount, "Error: allowance less than spending" ); if(!_isInvestor[msgSender()]) { _investors += 1; _investor[_investors] = msgSender(); } Investment storage i = _investment[msgSender()]; i._usdc += _usdcAmount; emit Invest(msgSender(), _usdcAmount, bytes32("USDC")); IERC20(_usdc).transferFrom(msgSender(), address(this), _usdcAmount); return true; } /** * @dev invests `_busdAmount` to the vesting smart contract. * * Requirements: * `_busdAmount` should be approved by `caller` account. * `_busdAmount` should be greater or equal to balance of `caller` account */ function investBusd(uint256 _busdAmount) public virtual returns (bool) { require(IWhiteList(_whitelist).whitelisted(msgSender()), "Error: investor not elligible for purchase"); uint256 balance = IERC20(_busd).balanceOf(msgSender()); uint256 allowance = IERC20(_busd).allowance(msgSender(), address(this)); require(balance >= _busdAmount, "Error: insufficient BUSD Balance"); require( allowance >= _busdAmount, "Error: allowance less than spending" ); if(!_isInvestor[msgSender()]) { _investors += 1; _investor[_investors] = msgSender(); } Investment storage i = _investment[msgSender()]; i._busd += _busdAmount; emit Invest(msgSender(), _busdAmount, bytes32("BUSD")); IERC20(_busd).transferFrom(msgSender(), address(this), _busdAmount); return true; } /** * @dev returns the amount of usdt invested by `_user` */ function investment(address _user) public view virtual returns (uint256, uint256, uint256) { Investment storage i = _investment[_user]; return(i._usdc, i._usdt, i._busd); } /** * @dev returns the usdt smart contract used for purchase. */ function usdt() public view returns (address) { return _usdt; } /** * @dev returns the usdc smart contract used for purchase. */ function usdc() public view returns (address) { return _usdc; } /** * @dev returns the busd smart contract used for purchase. */ function busd() public view returns (address) { return _busd; } /** * @dev returns the total number of investors. */ function totalInvestors() public view returns (uint256) { return _investors; } /** * @dev returns individual investor address. */ function investor(uint256 investorId) public view returns (address) { return _investor[investorId]; } /** * @dev returns the admin account used for purchase. */ function admin() public view returns (address) { return _admin; } /** * @dev transfers ownership to a different account. * * Requirements: * `newAdmin` cannot be a zero address. * `caller` should be current admin. */ function transferControl(address newAdmin) public virtual onlyAdmin { require(newAdmin != address(0), "Error: owner cannot be zero"); _admin = newAdmin; } /** * @dev updates the usdt sc address. * * Requirements: * `newAddress` cannot be a zero address. * `caller` should be current admin. */ function updateUsdt(address newAddress) public virtual onlyAdmin { require(newAddress != address(0), "Error: address cannot be zero"); _usdt = newAddress; } /** * @dev updates the usdc sc address. * * Requirements: * `newAddress` cannot be a zero address. * `caller` should be current admin. */ function updateUsdc(address newAddress) public virtual onlyAdmin { require(newAddress != address(0), "Error: address cannot be zero"); _usdc = newAddress; } /** * @dev updates the busd sc address. * * Requirements: * `newAddress` cannot be a zero address. * `caller` should be current admin. */ function updateBusd(address newAddress) public virtual onlyAdmin { require(newAddress != address(0), "Error: address cannot be zero"); _busd = newAddress; } /** * @dev updates the whitelist oracle address. * * Requirements: * `newAddress` cannot be a zero address. * `caller` should be current admin. */ function updateOracle(address newAddress) public virtual onlyAdmin { require(newAddress != address(0), "Error: owner cannot be zero"); _whitelist = newAddress; } /** * @dev send usdt from SC to any EOA. * * `caller` should be admin account. * `to` cannot be zero address. */ function sendUsdt(address to, uint256 amount) public virtual onlyAdmin returns (bool) { require(to != address(0), "Error: cannot send to zero addresss"); IERC20(_usdt).transfer(to, amount); return true; } /** * @dev send usdc from SC to any EOA. * * `caller` should be admin account. * `to` cannot be zero address. */ function sendUsdc(address to, uint256 amount) public virtual onlyAdmin returns (bool) { require(to != address(0), "Error: cannot send to zero addresss"); IERC20(_usdc).transfer(to, amount); return true; } /** * @dev send busd from SC to any EOA. * * `caller` should be admin account. * `to` cannot be zero address. */ function sendBusd(address to, uint256 amount) public virtual onlyAdmin returns (bool) { require(to != address(0), "Error: cannot send to zero addresss"); IERC20(_busd).transfer(to, amount); return true; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; interface IERC20 { /** * @dev returns the tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev returns the remaining number of tokens the `spender' can spend * on behalf of the owner. * * This value changes when {approve} or {transferFrom} is executed. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev transfers the `amount` of tokens from caller's account * to the `recipient` account. * * returns boolean value indicating the operation status. * * Emits a {Transfer} event */ function transfer(address recipient, uint256 amount) external; /** * @dev transfers the `amount` on behalf of `spender` to the `recipient` account. * * returns a boolean indicating the operation status. * * Emits a {Transfer} event. */ function transferFrom( address spender, address recipient, uint256 amount ) external; } // SPDX-License-Identifier: ISC pragma solidity ^0.8.4; /** * Library Like Contract. Not Required for deployment */ abstract contract Context { function msgSender() internal view virtual returns(address) { return msg.sender; } function msgData() internal view virtual returns(bytes calldata) { this; return msg.data; } function msgValue() internal view virtual returns(uint256) { return msg.value; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; /** * @dev interface of Whitelist Contract. */ interface IWhiteList { /** * @dev whitelist the `_user` for purchase. * * Requirements: * `_user` should not be a zero address. * `_user` should not be already whitelisted. * * returns a bool to represent the status of the transaction. */ function whitelist(address _user) external returns (bool); /** * @dev blacklists the `user` from sale. * * Requirements: * `_user` should be whitelisted before. * `_user` cannot be a zero address. * * returns a bool to represent the status of the transaction. */ function blacklist(address _user) external returns (bool); /** * @dev transfers the control of whitelisting to another wallet. * * Requirements: * `_newGovernor` should not be a zero address. * `caller` should be the current governor. * * returns a bool to represent the status of the transaction. */ function transferGovernor(address _newGovernor) external returns (bool); /** * @dev returns a bool to represent the whitelisting status of a wallet. * * true - address is whitelisted and can purchase tokens. * false - prevented from sale. */ function whitelisted(address _user) external view returns (bool); }
updates the whitelist oracle address. Requirements: `newAddress` cannot be a zero address. `caller` should be current admin./
function updateOracle(address newAddress) public virtual onlyAdmin { require(newAddress != address(0), "Error: owner cannot be zero"); _whitelist = newAddress; }
1,129,341
./partial_match/1/0x43c5b1391e8679eC8330A3767830484D3E829024/sources/BhxManage.sol
管理员取出合约里的erc20代币 创建usdt的合约对象 获取合约地址的余额 从合约地址转出usdt到to地址
function takeErc20(address _erc20Address) external onlyOwner { require(_erc20Address != address(0), "BHXManage: Zero address error"); ERC20 erc20 = ERC20(_erc20Address); uint256 _value = erc20.balanceOf(address(this)); TransferHelper.safeTransfer(_erc20Address, msg.sender, _value); }
2,733,146
pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; import "../../openzeppelin/Ownable.sol"; import "../../interfaces/IERC20.sol"; import "../Staking/Staking.sol"; import "../IFeeSharingProxy.sol"; import "./IVesting.sol"; import "../ApprovalReceiver.sol"; import "./VestingStorage.sol"; contract VestingLogic is IVesting, VestingStorage, ApprovalReceiver { event TokensStaked(address indexed caller, uint256 amount); event VotesDelegated(address indexed caller, address delegatee); event TokensWithdrawn(address indexed caller, address receiver); event DividendsCollected(address indexed caller, address loanPoolToken, address receiver, uint32 maxCheckpoints); event MigratedToNewStakingContract(address indexed caller, address newStakingContract); /** * @dev Throws if called by any account other than the token owner or the contract owner. */ modifier onlyOwners() { require(msg.sender == tokenOwner || isOwner(), "unauthorized"); _; } /** * @dev Throws if called by any account other than the token owner. */ modifier onlyTokenOwner() { require(msg.sender == tokenOwner, "unauthorized"); _; } /** * @notice stakes tokens according to the vesting schedule * @param _amount the amount of tokens to stake * */ function stakeTokens(uint256 _amount) public { _stakeTokens(msg.sender, _amount); } /** * @notice stakes tokens according to the vesting schedule * @dev this function will be invoked from receiveApproval * @dev SOV.approveAndCall -> this.receiveApproval -> this.stakeTokensWithApproval * @param _sender the sender of SOV.approveAndCall * @param _amount the amount of tokens to stake * */ function stakeTokensWithApproval(address _sender, uint256 _amount) public onlyThisContract { _stakeTokens(_sender, _amount); } function _stakeTokens(address _sender, uint256 _amount) internal { //maybe better to allow staking unil the cliff was reached if (startDate == 0) { startDate = staking.timestampToLockDate(block.timestamp); } endDate = staking.timestampToLockDate(block.timestamp + duration); //transfer the tokens to this contract bool success = SOV.transferFrom(_sender, address(this), _amount); require(success); //allow the staking contract to access them SOV.approve(address(staking), _amount); staking.stakesBySchedule(_amount, cliff, duration, FOUR_WEEKS, address(this), tokenOwner); emit TokensStaked(_sender, _amount); } /** * @notice Delegate votes from `msg.sender` which are locked until lockDate to `delegatee` * @param _delegatee The address to delegate votes to */ function delegate(address _delegatee) public onlyTokenOwner { require(_delegatee != address(0), "delegatee address invalid"); //withdraw for each unlocked position for (uint256 i = startDate + cliff; i < endDate; i += FOUR_WEEKS) { staking.delegate(_delegatee, i); } emit VotesDelegated(msg.sender, _delegatee); } /** * @notice withdraws all tokens from the staking contract and forwards them to an address specified by the token owner * @param receiver the receiving address * @dev can be called only by owner * */ function governanceWithdrawTokens(address receiver) public { require(msg.sender == address(staking), "unauthorized"); _withdrawTokens(receiver, true); } /** * @notice withdraws unlocked tokens from the staking contract and forwards them to an address specified by the token owner * @param receiver the receiving address **/ function withdrawTokens(address receiver) public onlyOwners { _withdrawTokens(receiver, false); } function _withdrawTokens(address receiver, bool isGovernance) internal { require(receiver != address(0), "receiver address invalid"); uint96 stake; //usually we just need to iterate over the possible dates until now uint256 end; //in the unlikely case that all tokens have been unlocked early, allow to withdraw all of them. if (staking.allUnlocked() || isGovernance) { end = endDate; } else { end = block.timestamp; } //withdraw for each unlocked position for (uint256 i = startDate + cliff; i <= end; i += FOUR_WEEKS) { //read amount to withdraw stake = staking.getPriorUserStakeByDate(address(this), i, block.number - 1); //withdraw if > 0 if (stake > 0) { if (isGovernance) { staking.governanceWithdraw(stake, i, receiver); } else { staking.withdraw(stake, i, receiver); } } } emit TokensWithdrawn(msg.sender, receiver); } /** * @dev collect dividends from fee sharing proxy */ function collectDividends( address _loanPoolToken, uint32 _maxCheckpoints, address _receiver ) public onlyOwners { require(_receiver != address(0), "receiver address invalid"); //invokes the fee sharing proxy feeSharingProxy.withdraw(_loanPoolToken, _maxCheckpoints, _receiver); emit DividendsCollected(msg.sender, _loanPoolToken, _receiver, _maxCheckpoints); } /** * @notice allows the owners to migrate the positions to a new staking contract * */ function migrateToNewStakingContract() public onlyOwners { staking.migrateToNewStakingContract(); staking = Staking(staking.newStakingContract()); emit MigratedToNewStakingContract(msg.sender, address(staking)); } function _getToken() internal view returns (address) { return address(SOV); } function _getSelectors() internal view returns (bytes4[] memory) { bytes4[] memory selectors = new bytes4[](1); selectors[0] = this.stakeTokensWithApproval.selector; return selectors; } }
collect dividends from fee sharing proxy/invokes the fee sharing proxy
function collectDividends( address _loanPoolToken, uint32 _maxCheckpoints, address _receiver ) public onlyOwners { require(_receiver != address(0), "receiver address invalid"); feeSharingProxy.withdraw(_loanPoolToken, _maxCheckpoints, _receiver); emit DividendsCollected(msg.sender, _loanPoolToken, _receiver, _maxCheckpoints); }
14,111,653
pragma solidity ^0.4.15; /** * @title Queue * @dev Data structure contract used in `Crowdsale.sol` * Allows buyers to line up on a first-in-first-out basis * See this example: http://interactivepython.org/courselib/static/pythonds/BasicDS/ImplementingaQueueinPython.html */ contract Queue { uint8 size = 5; uint8 curSize; uint timeLimit; participant[] participantsList; struct participant{ address a; uint timeLimit; } function Queue(uint _timeLimit) { timeLimit = _timeLimit; } /* Returns the number of people waiting in line */ function qsize() constant returns(uint8) { return curSize; } /* Returns whether the queue is empty or not */ function empty() constant returns(bool) { return curSize == 0; } /* Returns the address of the person in the front of the queue */ function getFirst() constant returns(address) { if(curSize == 0){ return address(0); } return participantsList[0].a; } /* Allows `msg.sender` to check their position in the queue */ function checkPlace() constant returns(uint8) { for(uint8 i = 0; i < curSize; i++){ if(participantsList[i].a == msg.sender){ return i; } } revert(); } /* Allows anyone to expel the first person in line if their time * limit is up */ function checkTime() { if(participantsList[0].timeLimit < now){ dequeue(); } } /* Removes the first person in line; either when their time is up or when * they are done with their purchase */ function dequeue() { delete participantsList[0]; curSize = curSize - 1; if(curSize> 0){ participantsList[0].timeLimit = now + timeLimit; } } /* Places `addr` in the first empty position in the queue */ function enqueue(address addr) { if(curSize >= size - 1){ return; } participantsList.push(participant( addr, now + timeLimit)); curSize = curSize + 1; } }
Allows anyone to expel the first person in line if their time limit is up/
function checkTime() { if(participantsList[0].timeLimit < now){ dequeue(); } }
2,564,610
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; import "./ServiceClaim.sol"; import "./AEECToken.sol"; import "./Organizations.sol"; import "./Insurer.sol"; import "./Patient.sol"; contract Provider { bytes32 id; string name; address[] patients; address[] serviceClaims; address insAddr; mapping(address=>address) serviceClaimMap; //mapping from patient address to serviceClaim address mapping (address=>string) SCMap; mapping (string=>address) newP; mapping (address=>string) public patientMap; //ID of patient to specific provider - event PatientCreated(address addr, string name); event SCID(string scName, address addr); event ClaimCreated(address addr, uint256 amount, uint256 timeFiled); event PatientRetrieval(Patient patient); event Claims(address[] unverifiedClaims); constructor(string memory _name, bytes32 _id, address _insAddr) public { // preLoadInfo(); //token = AEECToken(_tokenAddr); //token._mint(address(this),1000000); id = _id; name = _name; insAddr = _insAddr; } //addPatient //getPatints //provideService //fileClaimy // getPatient function addPatient(string memory _name) public returns(address pAddr) { bytes32 pid = keccak256(abi.encodePacked(_name)); //address[] memory uServiceList; //address[] memory uClaimList; //address[] memory vClaimList; Patient newPatient = new Patient(pid, _name); //bytes32 patientHash = keccak256(abi.encodePacked(newPatient)); patientMap[address(newPatient)] = _name; patients.push(address(newPatient)); //providerMap[_providerID].patients.push(newPatient.id); emit PatientCreated(address(newPatient), _name); newP[_name] = address(newPatient); return address(newPatient); } function getNewPatient(string memory _name) public view returns(address newAddr) { return newP[_name]; } function getPatients() public view returns(address[] memory _patients) { return patients; } function getPatient(address _addr) public returns (bool){ //Patient memory patient = patientMap[_addr]; Patient cP = Patient(_addr); emit PatientRetrieval(cP); return true; } function provideService(string memory _name, address _patientAddress, uint256 _timeProvided) public returns(address SCAddress) { bytes32 sid = keccak256(abi.encodePacked(_name, id, _patientAddress)); ServiceClaim serviceClaim = new ServiceClaim(insAddr, address(this), _patientAddress, sid, _name, _timeProvided); serviceClaims.push(address(serviceClaim)); serviceClaimMap[_patientAddress] = address(serviceClaim); Patient cP = Patient(_patientAddress); Insurer cI = Insurer(insAddr); cI.addSC(address(serviceClaim)); cP.recordService(address(serviceClaim)); SCMap[address(serviceClaim)] = _name; emit SCID(_name, address(serviceClaim)); return address(serviceClaim); } function fileClaim(address _serviceClaimAddr, uint256 _amount, uint256 _timeFiled) public returns(address ClaimAddr) { //Patient storage cPatient = patientMap[_patient]; ServiceClaim myServiceClaim = ServiceClaim(_serviceClaimAddr); //uint256 newClaimID = myServiceClaim.fileClaim(_amount, _timeProvided); //serviceClaims.push(address(myServiceClaim)); //emit SCEvent(newSC); address patientAddr = myServiceClaim.getPatientAddress(); uint256 amount = myServiceClaim.file(_amount, _timeFiled); Patient cP = Patient(patientAddr); emit PatientRetrieval(cP); cP.fileClaim(address(myServiceClaim)); emit ClaimCreated(address(myServiceClaim), amount, _timeFiled); Insurer cI = Insurer(insAddr); cI.file(address(myServiceClaim)); return address(myServiceClaim); } function getPatientName(address _addr) public view returns (string memory) { string memory patient = patientMap[_addr]; return patient; } function getInsAddr() public view returns (address){ return insAddr; } }
Patient memory patient = patientMap[_addr];
function getPatient(address _addr) public returns (bool){ Patient cP = Patient(_addr); emit PatientRetrieval(cP); return true; }
1,823,986
./partial_match/1/0x304dd601bEf9224fBec69781dA604756D8ab5b7e/sources/MCDMonitorV2.sol
Allows owner to change gas cost for repay operation, but only up to 3 millions _gasCost New gas cost for repay method
function changeRepayGasCost(uint256 _gasCost) public onlyOwner { require(_gasCost < 3_000_000, "Repay gas cost over limit"); REPAY_GAS_COST = _gasCost; }
2,733,236
pragma solidity ^0.4.11; contract ChronoBankPlatform { mapping(bytes32 => address) public proxies; function symbols(uint _idx) public constant returns (bytes32); function symbolsCount() public constant returns (uint); function name(bytes32 _symbol) returns(string); function setProxy(address _address, bytes32 _symbol) returns(uint errorCode); function isCreated(bytes32 _symbol) constant returns(bool); function isOwner(address _owner, bytes32 _symbol) returns(bool); function owner(bytes32 _symbol) constant returns(address); function totalSupply(bytes32 _symbol) returns(uint); function balanceOf(address _holder, bytes32 _symbol) returns(uint); function allowance(address _from, address _spender, bytes32 _symbol) returns(uint); function baseUnit(bytes32 _symbol) returns(uint8); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, address _account) returns(uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) returns(uint errorCode); function revokeAsset(bytes32 _symbol, uint _value) returns(uint errorCode); function isReissuable(bytes32 _symbol) returns(bool); function changeOwnership(bytes32 _symbol, address _newOwner) returns(uint errorCode); } contract ChronoBankAsset { function __transferWithReference(address _to, uint _value, string _reference, address _sender) returns(bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool); function __approve(address _spender, uint _value, address _sender) returns(bool); function __process(bytes _data, address _sender) payable { revert(); } } contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); } /** * @title ChronoBank Asset Proxy. * * Proxy implements ERC20 interface and acts as a gateway to a single platform asset. * Proxy adds symbol and caller(sender) when forwarding requests to platform. * Every request that is made by caller first sent to the specific asset implementation * contract, which then calls back to be forwarded onto platform. * * Calls flow: Caller -> * Proxy.func(...) -> * Asset.__func(..., Caller.address) -> * Proxy.__func(..., Caller.address) -> * Platform.proxyFunc(..., symbol, Caller.address) * * Asset implementation contract is mutable, but each user have an option to stick with * old implementation, through explicit decision made in timely manner, if he doesn&#39;t agree * with new rules. * Each user have a possibility to upgrade to latest asset contract implementation, without the * possibility to rollback. * * Note: all the non constant functions return false instead of throwing in case if state change * didn&#39;t happen yet. */ contract ChronoBankAssetProxy is ERC20 { // Supports ChronoBankPlatform ability to return error codes from methods uint constant OK = 1; // Assigned platform, immutable. ChronoBankPlatform public chronoBankPlatform; // Assigned symbol, immutable. bytes32 public smbl; // Assigned name, immutable. string public name; string public symbol; /** * Sets platform address, assigns symbol and name. * * Can be set only once. * * @param _chronoBankPlatform platform contract address. * @param _symbol assigned symbol. * @param _name assigned name. * * @return success. */ function init(ChronoBankPlatform _chronoBankPlatform, string _symbol, string _name) returns(bool) { if (address(chronoBankPlatform) != 0x0) { return false; } chronoBankPlatform = _chronoBankPlatform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; } function stringToBytes32(string memory source) returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /** * Only platform is allowed to call. */ modifier onlyChronoBankPlatform() { if (msg.sender == address(chronoBankPlatform)) { _; } } /** * Only current asset owner is allowed to call. */ modifier onlyAssetOwner() { if (chronoBankPlatform.isOwner(msg.sender, smbl)) { _; } } /** * Returns asset implementation contract for current caller. * * @return asset implementation contract. */ function _getAsset() internal returns(ChronoBankAsset) { return ChronoBankAsset(getVersionFor(msg.sender)); } /** * Returns asset total supply. * * @return asset total supply. */ function totalSupply() constant returns(uint) { return chronoBankPlatform.totalSupply(smbl); } /** * Returns asset balance for a particular holder. * * @param _owner holder address. * * @return holder balance. */ function balanceOf(address _owner) constant returns(uint) { return chronoBankPlatform.balanceOf(_owner, smbl); } /** * Returns asset allowance from one holder to another. * * @param _from holder that allowed spending. * @param _spender holder that is allowed to spend. * * @return holder to spender allowance. */ function allowance(address _from, address _spender) constant returns(uint) { return chronoBankPlatform.allowance(_from, _spender, smbl); } /** * Returns asset decimals. * * @return asset decimals. */ function decimals() constant returns(uint8) { return chronoBankPlatform.baseUnit(smbl); } /** * Transfers asset balance from the caller to specified receiver. * * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transfer(address _to, uint _value) returns(bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, ""); } else { return false; } } /** * Transfers asset balance from the caller to specified receiver adding specified comment. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform&#39;s Transfer event. * * @return success. */ function transferWithReference(address _to, uint _value, string _reference) returns(bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, _reference); } else { return false; } } /** * Resolves asset implementation contract for the caller and forwards there arguments along with * the caller address. * * @return success. */ function _transferWithReference(address _to, uint _value, string _reference) internal returns(bool) { return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender); } /** * Performs transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform&#39;s Transfer event. * @param _sender initial caller. * * @return success. */ function __transferWithReference(address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) { return chronoBankPlatform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; } /** * Prforms allowance transfer of asset balance between holders. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transferFrom(address _from, address _to, uint _value) returns(bool) { if (_to != 0x0) { return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender); } else { return false; } } /** * Performs allowance transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform&#39;s Transfer event. * @param _sender initial caller. * * @return success. */ function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) { return chronoBankPlatform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK; } /** * Sets asset spending allowance for a specified spender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * * @return success. */ function approve(address _spender, uint _value) returns(bool) { if (_spender != 0x0) { return _getAsset().__approve(_spender, _value, msg.sender); } else { return false; } } /** * Performs allowance setting call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * @param _sender initial caller. * * @return success. */ function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) returns(bool) { return chronoBankPlatform.proxyApprove(_spender, _value, smbl, _sender) == OK; } /** * Emits ERC20 Transfer event on this contract. * * Can only be, and, called by assigned platform when asset transfer happens. */ function emitTransfer(address _from, address _to, uint _value) onlyChronoBankPlatform() { Transfer(_from, _to, _value); } /** * Emits ERC20 Approval event on this contract. * * Can only be, and, called by assigned platform when asset allowance set happens. */ function emitApprove(address _from, address _spender, uint _value) onlyChronoBankPlatform() { Approval(_from, _spender, _value); } /** * Resolves asset implementation contract for the caller and forwards there transaction data, * along with the value. This allows for proxy interface growth. */ function () payable { _getAsset().__process.value(msg.value)(msg.data, msg.sender); } /** * Indicates an upgrade freeze-time start, and the next asset implementation contract. */ event UpgradeProposal(address newVersion); // Current asset implementation contract address. address latestVersion; // Proposed next asset implementation contract address. address pendingVersion; // Upgrade freeze-time start. uint pendingVersionTimestamp; // Timespan for users to review the new implementation and make decision. uint constant UPGRADE_FREEZE_TIME = 3 days; // Asset implementation contract address that user decided to stick with. // 0x0 means that user uses latest version. mapping(address => address) userOptOutVersion; /** * Only asset implementation contract assigned to sender is allowed to call. */ modifier onlyAccess(address _sender) { if (getVersionFor(_sender) == msg.sender) { _; } } /** * Returns asset implementation contract address assigned to sender. * * @param _sender sender address. * * @return asset implementation contract address. */ function getVersionFor(address _sender) constant returns(address) { return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender]; } /** * Returns current asset implementation contract address. * * @return asset implementation contract address. */ function getLatestVersion() constant returns(address) { return latestVersion; } /** * Returns proposed next asset implementation contract address. * * @return asset implementation contract address. */ function getPendingVersion() constant returns(address) { return pendingVersion; } /** * Returns upgrade freeze-time start. * * @return freeze-time start. */ function getPendingVersionTimestamp() constant returns(uint) { return pendingVersionTimestamp; } /** * Propose next asset implementation contract address. * * Can only be called by current asset owner. * * Note: freeze-time should not be applied for the initial setup. * * @param _newVersion asset implementation contract address. * * @return success. */ function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don&#39;t apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; UpgradeProposal(_newVersion); return true; } /** * Cancel the pending upgrade process. * * Can only be called by current asset owner. * * @return success. */ function purgeUpgrade() onlyAssetOwner() returns(bool) { if (pendingVersion == 0x0) { return false; } delete pendingVersion; delete pendingVersionTimestamp; return true; } /** * Finalize an upgrade process setting new asset implementation contract address. * * Can only be called after an upgrade freeze-time. * * @return success. */ function commitUpgrade() returns(bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; return true; } /** * Disagree with proposed upgrade, and stick with current asset implementation * until further explicit agreement to upgrade. * * @return success. */ function optOut() returns(bool) { if (userOptOutVersion[msg.sender] != 0x0) { return false; } userOptOutVersion[msg.sender] = latestVersion; return true; } /** * Implicitly agree to upgrade to current and future asset implementation upgrades, * until further explicit disagreement. * * @return success. */ function optIn() returns(bool) { delete userOptOutVersion[msg.sender]; return true; } }
Implicitly agree to upgrade to current and future asset implementation upgrades, until further explicit disagreement. return success./
function optIn() returns(bool) { delete userOptOutVersion[msg.sender]; return true; }
15,415,280
./partial_match/1/0x4D3e53EB6175d9aE9eafAbc21FC5C44153F99079/sources/chalUniswapMining.sol
calculate claimable chal based on current state if it's the first stake for user and the first stake for entire mining program, set stakerIndex as stakeInitialIndex
function claimablechal(address _address) public view returns(uint){ uint stakerIndex = stakerIndexes[_address]; if (stakerIndex == 0 && totalStaked == 0) { stakerIndex = stakeInitialIndex; } if(stakerIndex == 0){ stakerIndex = miningStateIndex; } uint deltaIndex = miningStateIndex.sub(stakerIndex); uint chalDelta = deltaIndex.mul(stakerPower[_address]).div(1e18); return chalDelta; }
2,672,850
pragma solidity ^0.5.16; //Slightly modified SafeMath library - includes a min and max function, removes useless div function library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a + b; assert(c >= a); } else { c = a + b; assert(c <= a); } } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint256(a) : uint256(b); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a - b; assert(c <= a); } else { c = a - b; assert(c >= a); } } } pragma solidity ^0.5.0; /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor */ library TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint256 value; address miner; } struct Dispute { bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int256 tally; //current tally of votes for - against measure bool executed; //is the dispute settled bool disputeVotePassed; //did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress; //new fork address (if fork proposal) mapping(bytes32 => uint256) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("fee"); //fee paid corresponding to dispute mapping(address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute 4=ReadyForUnlocking 5=Unlocked uint256 startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number } struct Request { string queryString; //id to string api string dataSymbol; //short name for api request bytes32 queryHash; //hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity)) uint256[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint256) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("granularity"); //multiplier for miners // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number //This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint256 => uint256) finalValues; mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized. mapping(uint256 => address[5]) minersByValue; mapping(uint256 => uint256[5]) valuesByTimestamp; } struct TellorStorageStruct { bytes32 currentChallenge; //current challenge to be solved uint256[51] requestQ; //uint50 array of the top50 requests by payment amount uint256[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_owner");//Tellor Owner address // address keccak256("_deity");//Tellor Owner that can do things at will // address keccak256("pending_owner"); // The proposed new owner mapping(bytes32 => uint256) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) // keccak256("_tblock"); // // keccak256("runningTips"); // VAriable to track running tips // keccak256("currentReward"); // The current reward // keccak256("devShare"); // The amount directed towards th devShare // keccak256("currentTotalTips"); // //This is a boolean that tells you if a given challenge has been completed by a given miner mapping(bytes32 => mapping(address => bool)) minersByChallenge; mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint256 => Dispute) disputesById; //disputeId=> Dispute details mapping(address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping(address => uint256)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info mapping(uint256 => Request) requestDetails; //mapping of apiID to details mapping(bytes32 => uint256) requestIdByQueryHash; // api bytes32 gets an id = to count of requests array mapping(bytes32 => uint256) disputeIdByDisputeHash; //maps a hash to an ID for each dispute } } pragma solidity ^0.5.16; /** * @title Tellor Transfer * @dev Contains the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library TellorTransfer { using SafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value); //ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event bytes32 public constant stakeAmount = 0x7be108969d31a3f0b261465c71f2b0ba9301cd914d55d9091c3b36a49d4d41b2; //keccak256("stakeAmount") /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self, msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount, "Allowance is wrong"); self.allowed[_from][msg.sender] -= _amount; doTransfer(self, _from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint256 _amount) public returns (bool) { require(_spender != address(0), "Spender is 0-address"); require(self.allowed[msg.sender][_spender] == 0 || _amount == 0, "Spender is already approved"); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(TellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) { return self.allowed[_user][_spender]; } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public { require(_amount != 0, "Tried to send non-positive amount"); require(_to != address(0), "Receiver is 0 address"); require(allowedToTrade(self, _from, _amount), "Should have sufficient balance to trade"); uint256 previousBalance = balanceOf(self, _from); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOf(self,_to); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(TellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) { return balanceOfAt(self, _user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) { TellorStorage.Checkpoint[] storage checkpoints = self.balances[_user]; if (checkpoints.length == 0|| checkpoints[0].fromBlock > _blockNumber) { return 0; } else { if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length - 2; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock ==_blockNumber){ return checkpoints[mid].value; }else if(checkpoints[mid].fromBlock < _blockNumber) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus != 0 && self.stakerDetails[_user].currentStatus < 5) { //Subtracts the stakeAmount from balance if the _user is staked if (balanceOf(self, _user)- self.uintVars[stakeAmount] >= _amount) { return true; } return false; } return (balanceOf(self, _user) >= _amount); } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public { if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].fromBlock != block.number) { checkpoints.push(TellorStorage.Checkpoint({ fromBlock : uint128(block.number), value : uint128(_value) })); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } } pragma solidity ^0.5.16; /** * @title Tellor Dispute * @dev Contains the methods related to disputes. Tellor.sol references this library for function's logic. */ library TellorDispute { using SafeMath for uint256; using SafeMath for int256; //emitted when a new dispute is initialized event NewDispute(uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner); //emitted when a new vote happens event Voted(uint256 indexed _disputeID, bool _position, address indexed _voter, uint256 indexed _voteWeight); //emitted upon dispute tally event DisputeVoteTallied(uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _active); event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; require(_request.minedBlockNum[_timestamp] != 0, "Mined block is 0"); require(_minerIndex < 5, "Miner index is wrong"); //_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex //provided by the party initiating the dispute address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp)); //Increase the dispute count by 1 uint256 disputeId = self.uintVars[keccak256("disputeCount")] + 1; self.uintVars[keccak256("disputeCount")] = disputeId; //Sets the new disputeCount as the disputeId //Ensures that a dispute is not already open for the that miner, requestId and timestamp uint256 hashId = self.disputeIdByDisputeHash[_hash]; if(hashId != 0){ self.disputesById[disputeId].disputeUintVars[keccak256("origID")] = hashId; } else{ self.disputeIdByDisputeHash[_hash] = disputeId; hashId = disputeId; } uint256 origID = hashId; uint256 dispRounds = self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")] + 1; self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")] = dispRounds; self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds))] = disputeId; if(disputeId != origID){ uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds-1))]; require(self.disputesById[lastID].disputeUintVars[keccak256("minExecutionDate")] <= now, "Dispute is already open"); if(self.disputesById[lastID].executed){ require(now - self.disputesById[lastID].disputeUintVars[keccak256("tallyDate")] <= 1 days, "Time for voting haven't elapsed"); } } uint256 _fee; if (_minerIndex == 2) { self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")] = self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")] +1; //update dispute fee for this case _fee = self.uintVars[keccak256("stakeAmount")]*self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")]; } else { _fee = self.uintVars[keccak256("disputeFee")] * dispRounds; } //maps the dispute to the Dispute struct self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: false, reportedMiner: _miner, reportingParty: msg.sender, proposedForkAddress: address(0), executed: false, disputeVotePassed: false, tally: 0 }); //Saves all the dispute variables for the disputeId self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId; self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp; self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 2 days * dispRounds; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = _fee; TellorTransfer.doTransfer(self, msg.sender, address(this),_fee); //Values are sorted as they come in and the official value is the median of the first five //So the "official value" miner is always minerIndex==2. If the official value is being //disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute if (_minerIndex == 2) { _request.inDispute[_timestamp] = true; _request.finalValues[_timestamp] = 0; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId, _requestId, _timestamp, _miner); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bool _supportsDispute) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Get the voteWeight or the balance of the user at the time/blockNumber the disupte began uint256 voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]); //Require that the msg.sender has not voted require(disp.voted[msg.sender] != true, "Sender has already voted"); //Requre that the user had a balance >0 at time/blockNumber the disupte began require(voteWeight != 0, "User balance is 0"); //ensures miners that are under dispute cannot vote require(self.stakerDetails[msg.sender].currentStatus != 3, "Miner is under dispute"); //Update user voting status to true disp.voted[msg.sender] = true; //Update the number of votes for the dispute disp.disputeUintVars[keccak256("numberOfVotes")] += 1; //If the user supports the dispute increase the tally for the dispute by the voteWeight //otherwise decrease it if (_supportsDispute) { disp.tally = disp.tally.add(int256(voteWeight)); } else { disp.tally = disp.tally.sub(int256(voteWeight)); } //Let the network know the user has voted on the dispute and their casted vote emit Voted(_disputeId, _supportsDispute, msg.sender, voteWeight); } /** * @dev tallies the votes and locks the stake disbursement(currentStatus = 4) if the vote passes * @param _disputeId is the dispute id */ function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Ensure this has not already been executed/tallied require(disp.executed == false, "Dispute has been already executed"); require(now >= disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed"); require(disp.reportingParty != address(0), "reporting Party is address 0"); int256 _tally = disp.tally; if (_tally > 0) { //Set the dispute state to passed/true disp.disputeVotePassed = true; } //If the vote is not a proposed fork if (disp.isPropFork == false) { //Ensure the time for voting has elapsed TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; //If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported // miner and transfer the stakeAmount and dispute fee to the reporting party if(stakes.currentStatus == 3){ stakes.currentStatus = 4; } } else if (uint(_tally) >= ((self.uintVars[keccak256("total_supply")] * 10) / 100)) { emit NewTellorAddress(disp.proposedForkAddress); } disp.disputeUintVars[keccak256("tallyDate")] = now; disp.executed = true; emit DisputeVoteTallied(_disputeId, _tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public { bytes32 _hash = keccak256(abi.encode(_propNewTellorAddress)); TellorTransfer.doTransfer(self, msg.sender, address(this), 100e18); //This is the fork fee (just 100 tokens flat, no refunds) self.uintVars[keccak256("disputeCount")]++; uint256 disputeId = self.uintVars[keccak256("disputeCount")]; if(self.disputeIdByDisputeHash[_hash] != 0){ self.disputesById[disputeId].disputeUintVars[keccak256("origID")] = self.disputeIdByDisputeHash[_hash]; } else{ self.disputeIdByDisputeHash[_hash] = disputeId; } uint256 origID = self.disputeIdByDisputeHash[_hash]; self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]++; uint256 dispRounds = self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]; self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds))] = disputeId; if(disputeId != origID){ uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds-1))]; require(self.disputesById[lastID].disputeUintVars[keccak256("minExecutionDate")] <= now, "Dispute is already open"); if(self.disputesById[lastID].executed){ require(now - self.disputesById[lastID].disputeUintVars[keccak256("tallyDate")] <= 1 days, "Time for voting haven't elapsed"); } } self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: true, reportedMiner: msg.sender, reportingParty: msg.sender, proposedForkAddress: _propNewTellorAddress, executed: false, disputeVotePassed: false, tally: 0 }); self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; } /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 origID = self.disputeIdByDisputeHash[_hash]; uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]))]; TellorStorage.Dispute storage disp = self.disputesById[lastID]; require(disp.disputeVotePassed == true, "vote needs to pass"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting for further disputes has not passed"); self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress; } /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { uint256 origID = self.disputeIdByDisputeHash[self.disputesById[_disputeId].hash]; uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]))]; if(lastID == 0){ lastID = origID; } TellorStorage.Dispute storage disp = self.disputesById[origID]; TellorStorage.Dispute storage last = self.disputesById[lastID]; //disputeRounds is increased by 1 so that the _id is not a negative number when it is the first time a dispute is initiated uint256 dispRounds = disp.disputeUintVars[keccak256("disputeRounds")]; if(dispRounds == 0){ dispRounds = 1; } uint256 _id; require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out"); require(now - last.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed"); TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; disp.disputeUintVars[keccak256("paid")] = 1; if (last.disputeVotePassed == true){ //Changing the currentStatus and startDate unstakes the reported miner and transfers the stakeAmount stakes.startDate = now - (now % 86400); //Reduce the staker count self.uintVars[keccak256("stakerCount")] -= 1; //Update the minimum dispute fee that is based on the number of stakers updateMinDisputeFee(self); //Decreases the stakerCount since the miner's stake is being slashed if(stakes.currentStatus == 4){ stakes.currentStatus = 5; TellorTransfer.doTransfer(self,disp.reportedMiner,disp.reportingParty,self.uintVars[keccak256("stakeAmount")]); stakes.currentStatus =0 ; } for(uint i = 0; i < dispRounds;i++){ _id = disp.disputeUintVars[keccak256(abi.encode(dispRounds-i))]; if(_id == 0){ _id = origID; } TellorStorage.Dispute storage disp2 = self.disputesById[_id]; //transfer fee adjusted based on number of miners if the minerIndex is not 2(official value) TellorTransfer.doTransfer(self,address(this), disp2.reportingParty, disp2.disputeUintVars[keccak256("fee")]); } } else { stakes.currentStatus = 1; TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; if(disp.disputeUintVars[keccak256("minerSlot")] == 2) { //note we still don't put timestamp back into array (is this an issue? (shouldn't be)) _request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = disp.disputeUintVars[keccak256("value")]; } if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) { _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; } for(uint i = 0; i < dispRounds;i++){ _id = disp.disputeUintVars[keccak256(abi.encode(dispRounds-i))]; if(_id != 0){ last = self.disputesById[_id];//handling if happens during an upgrade } TellorTransfer.doTransfer(self,address(this),last.reportedMiner,self.disputesById[_id].disputeUintVars[keccak256("fee")]); } } if (disp.disputeUintVars[keccak256("minerSlot")] == 2) { self.requestDetails[disp.disputeUintVars[keccak256("requestId")]].apiUintVars[keccak256("disputeCount")]--; } } /** * @dev This function upates the minimun dispute fee as a function of the amount * of staked miners */ function updateMinDisputeFee(TellorStorage.TellorStorageStruct storage self) public { uint256 stakeAmount = self.uintVars[keccak256("stakeAmount")]; uint256 targetMiners = self.uintVars[keccak256("targetMiners")]; self.uintVars[keccak256("disputeFee")] = SafeMath.max(15e18, (stakeAmount-(stakeAmount*(SafeMath.min(targetMiners,self.uintVars[keccak256("stakerCount")])*1000)/ targetMiners)/1000)); } } pragma solidity ^0.5.16; //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library Utilities { /** * @dev Returns the max value in an array. * The zero position here is ignored. It's because * there's no null in solidity and we map each address * to an index in this array. So when we get 51 parties, * and one person is kicked out of the top 50, we * assign them a 0, and when you get mined and pulled * out of the top 50, also a 0. So then lot's of parties * will have zero as the index so we made the array run * from 1-51 with zero as nothing. * @param data is the array to calculate max from * @return max amount and its index within the array */ function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) { maxIndex = 1; max = data[maxIndex]; for (uint256 i = 2; i < data.length; i++) { if (data[i] > max) { max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. * @param data is the array to calculate min from * @return min amount and its index within the array */ function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for (uint256 i = data.length - 2; i > 0; i--) { if (data[i] < min) { min = data[i]; minIndex = i; } } } /** * @dev Returns the 5 requestsId's with the top payouts in an array. * @param data is the array to get the top 5 from * @return to 5 max amounts and their respective index within the array */ function getMax5(uint256[51] memory data) internal pure returns (uint256[5] memory max, uint256[5] memory maxIndex) { uint256 min5 = data[1]; uint256 minI = 0; for(uint256 j=0;j<5;j++){ max[j]= data[j+1];//max[0]=data[1] maxIndex[j] = j+1;//maxIndex[0]= 1 if(max[j] < min5){ min5 = max[j]; minI = j; } } for(uint256 i = 6; i < data.length; i++) { if (data[i] > min5) { max[minI] = data[i]; maxIndex[minI] = i; min5 = data[i]; for(uint256 j=0;j<5;j++){ if(max[j] < min5){ min5 = max[j]; minI = j; } } } } } } pragma solidity ^0.5.16; /** * itle Tellor Stake * @dev Contains the methods related to miners staking and unstaking. Tellor.sol * references this library for function's logic. */ library TellorStake { event NewStake(address indexed _sender); //Emits upon new staker event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period /*Functions*/ /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the deposit */ function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require that the miner is staked require(stakes.currentStatus == 1, "Miner is not staked"); //Change the miner staked to locked to be withdrawStake stakes.currentStatus = 2; //Change the startDate to now since the lock up period begins now //and the miner can only withdraw 7 days later from now(check the withdraw function) stakes.startDate = now - (now % 86400); //Reduce the staker count self.uintVars[keccak256("stakerCount")] -= 1; //Update the minimum dispute fee that is based on the number of stakers TellorDispute.updateMinDisputeFee(self); emit StakeWithdrawRequested(msg.sender); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have //passed by since they locked for withdraw require(now - (now % 86400) - stakes.startDate >= 7 days, "7 days didn't pass"); require(stakes.currentStatus == 2, "Miner was not locked for withdrawal"); stakes.currentStatus = 0; emit StakeWithdrawn(msg.sender); } /** * @dev This function allows miners to deposit their stake. */ function depositStake(TellorStorage.TellorStorageStruct storage self) public { newStake(self, msg.sender); //self adjusting disputeFee TellorDispute.updateMinDisputeFee(self); } /** * @dev This function is used by the init function to succesfully stake the initial 5 miners. * The function updates their status/state and status start date so they are locked it so they can't withdraw * and updates the number of stakers in the system. */ function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal { require(TellorTransfer.balanceOf(self, staker) >= self.uintVars[keccak256("stakeAmount")], "Balance is lower than stake amount"); //Ensure they can only stake if they are not currrently staked or if their stake time frame has ended //and they are currently locked for witdhraw require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2, "Miner is in the wrong state"); self.uintVars[keccak256("stakerCount")] += 1; self.stakerDetails[staker] = TellorStorage.StakeInfo({ currentStatus: 1, //this resets their stake start date to today startDate: now - (now % 86400) }); emit NewStake(staker); } /** * @dev Getter function for the requestId being mined * @return variables for the current minin event: Challenge, 5 RequestId, difficulty and Totaltips */ function getNewCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns(bytes32 _challenge,uint[5] memory _requestIds,uint256 _difficulty, uint256 _tip){ for(uint i=0;i<5;i++){ _requestIds[i] = self.currentMiners[i].value; } return (self.currentChallenge,_requestIds,self.uintVars[keccak256("difficulty")],self.uintVars[keccak256("currentTotalTips")]); } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on top 5 requests(highest payout)-- RequestId, Totaltips */ function getNewVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck) { idsOnDeck = getTopRequestIDs(self); for(uint i = 0;i<5;i++){ tipsOnDeck[i] = self.requestDetails[idsOnDeck[i]].apiUintVars[keccak256("totalTip")]; } } /** * @dev Getter function for the top 5 requests with highest payouts. This function is used within the getNewVariablesOnDeck function * @return uint256[5] is an array with the top 5(highest payout) _requestIds at the time the function is called */ function getTopRequestIDs(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[5] memory _requestIds) { uint256[5] memory _max; uint256[5] memory _index; (_max, _index) = Utilities.getMax5(self.requestQ); for(uint i=0;i<5;i++){ if(_max[i] != 0){ _requestIds[i] = self.requestIdByRequestQIndex[_index[i]]; } else{ _requestIds[i] = self.currentMiners[4-i].value; } } } } pragma solidity ^0.5.0; /** * @title Tellor Getters Library * @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this * libary for the getters logic */ library TellorGettersLibrary { using SafeMath for uint256; event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ //The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address. //Only needs to be in library /** * @dev This function allows us to set a new Deity (or remove it) * @param _newDeity address of the new Deity of the tellor system */ function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal { require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity"); self.addressVars[keccak256("_deity")] = _newDeity; } //Only needs to be in library /** * @dev This function allows the deity to upgrade the Tellor System * @param _tellorContract address of new updated TellorCore contract */ function changeTellorContract(TellorStorage.TellorStorageStruct storage self, address _tellorContract) internal { require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity"); self.addressVars[keccak256("tellorContract")] = _tellorContract; emit NewTellorAddress(_tellorContract); } /*Tellor Getters*/ /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge, address _miner) public view returns (bool) { return self.minersByChallenge[_challenge][_miner]; } /** * @dev Checks if an address voted in a dispute * @param _disputeId to look up * @param _address of voting party to look up * @return bool of whether or not party voted */ function didVote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, address _address) internal view returns (bool) { return self.disputesById[_disputeId].voted[_address]; } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] * @return address requested */ function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (address) { return self.addressVars[_data]; } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) internal view returns (bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256) { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; return ( disp.hash, disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty, disp.proposedForkAddress, [ disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")], disp.disputeUintVars[keccak256("fee")] ], disp.tally ); } /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns (bytes32, uint256, uint256, string memory, uint256, uint256) { return ( self.currentChallenge, self.uintVars[keccak256("currentRequestId")], self.uintVars[keccak256("difficulty")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString, self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")] ); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self, bytes32 _hash) internal view returns (uint256) { return self.disputeIdByDisputeHash[_hash]; } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bytes32 _data) internal view returns (uint256) { return self.disputesById[_disputeId].disputeUintVars[_data]; } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, bool) { return ( retrieveData( self, self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")] ), true ); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256, bool) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; if (_request.requestTimestamps.length != 0) { return (retrieveData(self, _requestId, _request.requestTimestamps[_request.requestTimestamps.length - 1]), true); } else { return (0, false); } } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].minedBlockNum[_timestamp]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (address[5] memory) { return self.requestDetails[_requestId].minersByValue[_timestamp]; } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256) { return self.requestDetails[_requestId].requestTimestamps.length; } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint256 _index) internal view returns (uint256) { require(_index <= 50, "RequestQ index is above 50"); return self.requestIdByRequestQIndex[_index]; } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _timestamp) internal view returns (uint256) { return self.requestIdByTimestamp[_timestamp]; } /** * @dev Getter function for requestId based on the qeuaryHash * @param _queryHash hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns (uint256) { return self.requestIdByQueryHash[_queryHash]; } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[51] memory) { return self.requestQ; } /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, bytes32 _data) internal view returns (uint256) { return self.requestDetails[_requestId].apiUintVars[_data]; } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (string memory, string memory, bytes32, uint256, uint256, uint256) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return ( _request.queryString, _request.dataSymbol, _request.queryHash, _request.apiUintVars[keccak256("granularity")], _request.apiUintVars[keccak256("requestQPosition")], _request.apiUintVars[keccak256("totalTip")] ); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256) { return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256[5] memory) { return self.requestDetails[_requestId].valuesByTimestamp[_timestamp]; } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self, uint256 _requestID, uint256 _index) internal view returns (uint256) { return self.requestDetails[_requestID].requestTimestamps[_index]; } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (uint256) { return self.uintVars[_data]; } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256, string memory) { uint256 newRequestId = getTopRequestID(self); return ( newRequestId, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")], self.requestDetails[newRequestId].queryString ); } /** * @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function * @return uint _requestId of request with highest payout at the time the function is called */ function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256 _requestId) { uint256 _max; uint256 _index; (_max, _index) = Utilities.getMax(self.requestQ); _requestId = self.requestIdByRequestQIndex[_index]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to looku p * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (bool) { return self.requestDetails[_requestId].inDispute[_timestamp]; } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].finalValues[_timestamp]; } /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256) { return self.uintVars[keccak256("total_supply")]; } } pragma solidity ^0.5.16; /** * @title Tellor Oracle System Library * @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work * along with the value and smart contracts can requestData and tip miners. */ library TellorLibrary { using SafeMath for uint256; bytes32 public constant requestCount = 0x05de9147d05477c0a5dc675aeea733157f5092f82add148cf39d579cafe3dc98; //keccak256("requestCount") bytes32 public constant totalTip = 0x2a9e355a92978430eca9c1aa3a9ba590094bac282594bccf82de16b83046e2c3; //keccak256("totalTip") bytes32 public constant _tBlock = 0x969ea04b74d02bb4d9e6e8e57236e1b9ca31627139ae9f0e465249932e824502; //keccak256("_tBlock") bytes32 public constant timeOfLastNewValue = 0x97e6eb29f6a85471f7cc9b57f9e4c3deaf398cfc9798673160d7798baf0b13a4; //keccak256("timeOfLastNewValue") bytes32 public constant difficulty = 0xb12aff7664b16cb99339be399b863feecd64d14817be7e1f042f97e3f358e64e; //keccak256("difficulty") bytes32 public constant timeTarget = 0xad16221efc80aaf1b7e69bd3ecb61ba5ffa539adf129c3b4ffff769c9b5bbc33; //keccak256("timeTarget") bytes32 public constant runningTips = 0xdb21f0c4accc4f2f5f1045353763a9ffe7091ceaf0fcceb5831858d96cf84631; //keccak256("runningTips") bytes32 public constant currentReward = 0x9b6853911475b07474368644a0d922ee13bc76a15cd3e97d3e334326424a47d4; //keccak256("currentReward") bytes32 public constant total_supply = 0xb1557182e4359a1f0c6301278e8f5b35a776ab58d39892581e357578fb287836; //keccak256("total_supply") bytes32 public constant devShare = 0x8fe9ded8d7c08f720cf0340699024f83522ea66b2bbfb8f557851cb9ee63b54c; //keccak256("devShare") bytes32 public constant _owner = 0x9dbc393ddc18fd27b1d9b1b129059925688d2f2d5818a5ec3ebb750b7c286ea6; //keccak256("_owner") bytes32 public constant requestQPosition = 0x1e344bd070f05f1c5b3f0b1266f4f20d837a0a8190a3a2da8b0375eac2ba86ea; //keccak256("requestQPosition") bytes32 public constant currentTotalTips = 0xd26d9834adf5a73309c4974bf654850bb699df8505e70d4cfde365c417b19dfc; //keccak256("currentTotalTips") bytes32 public constant slotProgress =0x6c505cb2db6644f57b42d87bd9407b0f66788b07d0617a2bc1356a0e69e66f9a; //keccak256("slotProgress") bytes32 public constant pending_owner = 0x44b2657a0f8a90ed8e62f4c4cceca06eacaa9b4b25751ae1ebca9280a70abd68; //keccak256("pending_owner") bytes32 public constant currentRequestId = 0x7584d7d8701714da9c117f5bf30af73b0b88aca5338a84a21eb28de2fe0d93b8; //keccak256("currentRequestId") event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewChallenge( bytes32 indexed _currentChallenge, uint256[5] _currentRequestId, uint256 _difficulty, uint256 _totalTips ); //Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NewValue(uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge); //Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event NonceSubmitted(address indexed _miner, string _nonce, uint256[5] _requestId, uint256[5] _value, bytes32 indexed _currentChallenge); event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner); /*Functions*/ /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { require(_requestId != 0, "RequestId is 0"); require(_tip != 0, "Tip should be greater than 0"); uint256 _count =self.uintVars[requestCount] + 1; if(_requestId == _count){ self.uintVars[requestCount] = _count; } else{ require(_requestId < _count, "RequestId is not less than count"); } TellorTransfer.doTransfer(self, msg.sender, address(this), _tip); //Update the information for the request that should be mined next based on the tip submitted updateOnDeck(self, _requestId, _tip); emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[totalTip]); } /** * @dev This function is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first * 5 values received, pays the miners, the dev share and assigns a new challenge * @param _nonce or solution for the PoW for the requestId * @param _requestId for the current request being mined */ function newBlock(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256[5] memory _requestId) public { TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]]; // If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge //difficulty up or donw by the difference between the target time and how long it took to solve the previous challenge //otherwise it sets it to 1 uint timeDiff = now - self.uintVars[timeOfLastNewValue]; int256 _change = int256(SafeMath.min(1200, timeDiff)); int256 _diff = int256(self.uintVars[difficulty]); _change = (_diff * (int256(self.uintVars[timeTarget]) - _change)) / 4000; if (_change == 0) { _change = 1; } self.uintVars[difficulty] = uint256(SafeMath.max(_diff + _change,1)); //Sets time of value submission rounded to 1 minute bytes32 _currChallenge = self.currentChallenge; uint256 _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[timeOfLastNewValue] = _timeOfLastNewValue; uint[5] memory a; for (uint k = 0; k < 5; k++) { for (uint i = 1; i < 5; i++) { uint256 temp = _tblock.valuesByTimestamp[k][i]; address temp2 = _tblock.minersByValue[k][i]; uint256 j = i; while (j > 0 && temp < _tblock.valuesByTimestamp[k][j - 1]) { _tblock.valuesByTimestamp[k][j] = _tblock.valuesByTimestamp[k][j - 1]; _tblock.minersByValue[k][j] = _tblock.minersByValue[k][j - 1]; j--; } if (j < i) { _tblock.valuesByTimestamp[k][j] = temp; _tblock.minersByValue[k][j] = temp2; } } TellorStorage.Request storage _request = self.requestDetails[_requestId[k]]; //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number a = _tblock.valuesByTimestamp[k]; _request.finalValues[_timeOfLastNewValue] = a[2]; _request.minersByValue[_timeOfLastNewValue] = _tblock.minersByValue[k]; _request.valuesByTimestamp[_timeOfLastNewValue] = _tblock.valuesByTimestamp[k]; delete _tblock.minersByValue[k]; delete _tblock.valuesByTimestamp[k]; _request.requestTimestamps.push(_timeOfLastNewValue); _request.minedBlockNum[_timeOfLastNewValue] = block.number; _request.apiUintVars[totalTip] = 0; } emit NewValue( _requestId, _timeOfLastNewValue, a, self.uintVars[runningTips], _currChallenge ); //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId[0]; //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); address[5] memory miners = self.requestDetails[_requestId[0]].minersByValue[_timeOfLastNewValue]; //payMinersRewards _payReward(self, timeDiff, miners); self.uintVars[_tBlock] ++; uint256[5] memory _topId = TellorStake.getTopRequestIDs(self); for(uint i = 0; i< 5;i++){ self.currentMiners[i].value = _topId[i]; self.requestQ[self.requestDetails[_topId[i]].apiUintVars[requestQPosition]] = 0; self.uintVars[currentTotalTips] += self.requestDetails[_topId[i]].apiUintVars[totalTip]; } //Issue the the next challenge _currChallenge = keccak256(abi.encode(_nonce, _currChallenge, blockhash(block.number - 1))); self.currentChallenge = _currChallenge; // Save hash for next proof emit NewChallenge( _currChallenge, _topId, self.uintVars[difficulty], self.uintVars[currentTotalTips] ); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external { _verifyNonce(self, _nonce); _submitMiningSolution(self, _nonce, _requestId, _value); } function _submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string memory _nonce,uint256[5] memory _requestId, uint256[5] memory _value) internal { //Verifying Miner Eligibility bytes32 _hashMsgSender = keccak256(abi.encode(msg.sender)); require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker"); require(now - self.uintVars[_hashMsgSender] > 15 minutes, "Miner can only win rewards once per 15 min"); require(_requestId[0] == self.currentMiners[0].value,"Request ID is wrong"); require(_requestId[1] == self.currentMiners[1].value,"Request ID is wrong"); require(_requestId[2] == self.currentMiners[2].value,"Request ID is wrong"); require(_requestId[3] == self.currentMiners[3].value,"Request ID is wrong"); require(_requestId[4] == self.currentMiners[4].value,"Request ID is wrong"); self.uintVars[_hashMsgSender] = now; bytes32 _currChallenge = self.currentChallenge; uint256 _slotProgress = self.uintVars[slotProgress]; //Saving the challenge information as unique by using the msg.sender //Checking and updating Miner Status require(self.minersByChallenge[_currChallenge][msg.sender] == false, "Miner already submitted the value"); //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[_currChallenge][msg.sender] = true; //Updating Request TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]]; _tblock.minersByValue[1][_slotProgress]= msg.sender; //Assigng directly is cheaper than using a for loop _tblock.valuesByTimestamp[0][_slotProgress] = _value[0]; _tblock.valuesByTimestamp[1][_slotProgress] = _value[1]; _tblock.valuesByTimestamp[2][_slotProgress] = _value[2]; _tblock.valuesByTimestamp[3][_slotProgress] = _value[3]; _tblock.valuesByTimestamp[4][_slotProgress] = _value[4]; _tblock.minersByValue[0][_slotProgress]= msg.sender; _tblock.minersByValue[1][_slotProgress]= msg.sender; _tblock.minersByValue[2][_slotProgress]= msg.sender; _tblock.minersByValue[3][_slotProgress]= msg.sender; _tblock.minersByValue[4][_slotProgress]= msg.sender; //If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received if (_slotProgress + 1 == 5) { //slotProgress has been incremented, but we're using the variable on stack to save gas newBlock(self, _nonce, _requestId); self.uintVars[slotProgress] = 0; } else{ self.uintVars[slotProgress]++; } emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, _currChallenge); } function _verifyNonce(TellorStorage.TellorStorageStruct storage self,string memory _nonce ) view internal { require(uint256( sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce)))))) ) % self.uintVars[difficulty] == 0 || (now - (now % 1 minutes)) - self.uintVars[timeOfLastNewValue] >= 15 minutes, "Incorrect nonce for current challenge" ); } /** * @dev Internal function to calculate and pay rewards to miners * */ function _payReward(TellorStorage.TellorStorageStruct storage self, uint _timeDiff, address[5] memory miners) internal { //_timeDiff is how many minutes passed since last block uint _currReward = 1e18; uint reward = _timeDiff* _currReward / 300; //each miner get's uint _tip = self.uintVars[currentTotalTips] / 10; uint _devShare = reward / 2; TellorTransfer.doTransfer(self, address(this), miners[0], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[1], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[2], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[3], reward + _tip); TellorTransfer.doTransfer(self, address(this), miners[4], reward + _tip); //update the total supply self.uintVars[total_supply] += _devShare + reward * 5 - (self.uintVars[currentTotalTips] / 2); TellorTransfer.doTransfer(self, address(this), self.addressVars[_owner], _devShare); self.uintVars[currentTotalTips] = 0; } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(TellorStorage.TellorStorageStruct storage self, address payable _pendingOwner) public { require(msg.sender == self.addressVars[_owner], "Sender is not owner"); emit OwnershipProposed(self.addressVars[_owner], _pendingOwner); self.addressVars[pending_owner] = _pendingOwner; } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership(TellorStorage.TellorStorageStruct storage self) public { require(msg.sender == self.addressVars[pending_owner], "Sender is not pending owner"); emit OwnershipTransferred(self.addressVars[_owner], self.addressVars[pending_owner]); self.addressVars[_owner] = self.addressVars[pending_owner]; } /** * @dev This function updates APIonQ and the requestQ when requestData or addTip are ran * @param _requestId being requested * @param _tip is the tip to add */ function updateOnDeck(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; _request.apiUintVars[totalTip] = _request.apiUintVars[totalTip].add(_tip); if(self.currentMiners[0].value == _requestId || self.currentMiners[1].value== _requestId ||self.currentMiners[2].value == _requestId||self.currentMiners[3].value== _requestId || self.currentMiners[4].value== _requestId ){ self.uintVars[currentTotalTips] += _tip; } else { //if the request is not part of the requestQ[51] array //then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if (_request.apiUintVars[requestQPosition] == 0) { uint256 _min; uint256 _index; (_min, _index) = Utilities.getMin(self.requestQ); //we have to zero out the oldOne //if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero //then add it to the requestQ array aand map its index information to the requestId and the apiUintvars if (_request.apiUintVars[totalTip] > _min || _min == 0) { self.requestQ[_index] = _request.apiUintVars[totalTip]; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[requestQPosition] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[requestQPosition] = _index; } // else if the requestid is part of the requestQ[51] then update the tip for it } else{ self.requestQ[_request.apiUintVars[requestQPosition]] += _tip; } } } } pragma solidity ^0.5.16; /** * @title Tellor Oracle System * @dev Oracle contract where miners can submit the proof of work along with the value. * The logic for this contract is in TellorLibrary.sol, TellorDispute.sol, TellorStake.sol, * and TellorTransfer.sol */ contract Tellor { using SafeMath for uint256; using TellorDispute for TellorStorage.TellorStorageStruct; using TellorLibrary for TellorStorage.TellorStorageStruct; using TellorStake for TellorStorage.TellorStorageStruct; using TellorTransfer for TellorStorage.TellorStorageStruct; TellorStorage.TellorStorageStruct tellor; /*Functions*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) external { tellor.beginDispute(_requestId, _timestamp, _minerIndex); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(uint256 _disputeId, bool _supportsDispute) external { tellor.vote(_disputeId, _supportsDispute); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(uint256 _disputeId) external { tellor.tallyVotes(_disputeId); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external { tellor.proposeFork(_propNewTellorAddress); } /** * @dev Add tip to Request value from oracle * @param _requestId being requested to be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the onDeckQueryHash, or the api with the highest payout pool */ function addTip(uint256 _requestId, uint256 _tip) external { tellor.addTip(_requestId, _tip); } /** * @dev This is called by the miner when they submit the PoW solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId is the array of the 5 PSR's being mined * @param _value is an array of 5 values */ function submitMiningSolution(string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external { tellor.submitMiningSolution(_nonce,_requestId, _value); } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external { tellor.proposeOwnership(_pendingOwner); } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external { tellor.claimOwnership(); } /** * @dev This function allows miners to deposit their stake. */ function depositStake() external { tellor.depositStake(); } /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the stake */ function requestStakingWithdraw() external { tellor.requestStakingWithdraw(); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external { tellor.withdrawStake(); } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool) { return tellor.approve(_spender, _amount); } /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool) { return tellor.transfer(_to, _amount); } /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(address _from, address _to, uint256 _amount) external returns (bool) { return tellor.transferFrom(_from, _to, _amount); } /** * @dev Allows users to access the token's name */ function name() external pure returns (string memory) { return "Tellor Tributes"; } /** * @dev Allows users to access the token's symbol */ function symbol() external pure returns (string memory) { return "TRB"; } /** * @dev Allows users to access the number of decimals */ function decimals() external pure returns (uint8) { return 18; } /** * @dev Getter for the current variables that include the 5 requests Id's * @return the challenge, 5 requestsId, difficulty and tip */ function getNewCurrentVariables() external view returns(bytes32 _challenge,uint[5] memory _requestIds,uint256 _difficutly, uint256 _tip){ return tellor.getNewCurrentVariables(); } /** * @dev Getter for the top tipped 5 requests Id's * @return the 5 requestsId */ function getTopRequestIDs() external view returns(uint256[5] memory _requestIds){ return tellor.getTopRequestIDs(); } /** * @dev Getter for the 5 requests Id's next in line to get mined * @return the 5 requestsId */ function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck) { return tellor.getNewVariablesOnDeck(); } /** * @dev Updates the Tellor address after a proposed fork has * passed the vote and day has gone by without a dispute * @param _disputeId the disputeId for the proposed fork */ function updateTellor(uint _disputeId) external{ return tellor.updateTellor(_disputeId); } /** * @dev Allows disputer to unlock the dispute fee * @param _disputeId to unlock fee from */ function unlockDisputeFee (uint _disputeId) external{ return tellor.unlockDisputeFee(_disputeId); } /*******************TEST Functions NOT INCLUDED ON PRODUCTION/MAINNET/RINKEBY******/ // /*This is a cheat for demo purposes, will delete upon actual launch*/ // function theLazyCoon(address _address, uint _amount) external { // tellor.theLazyCoon(_address,_amount); // } // // function testSubmitMiningSolution(string calldata _nonce, uint256 _requestId, uint256 _value) external { // // tellor.testSubmitMiningSolution(_nonce, _requestId, _value); // // } // function testSubmitMiningSolution(string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external { // tellor.testSubmitMiningSolution(_nonce,_requestId, _value); // } /***************END TEST Functions NOT INCLUDED ON PRODUCTION/MAINNET/RINKEBY******/ }
Gets the a value for the latest timestamp available _requestId being requested return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't/
function getLastNewValueById(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256, bool) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; if (_request.requestTimestamps.length != 0) { return (retrieveData(self, _requestId, _request.requestTimestamps[_request.requestTimestamps.length - 1]), true); return (0, false); } }
1,434,155
./full_match/1/0x0000000000F7A60F1C88F317f369e3D8679C6689/sources/contracts/tokens/ERC721/Layerr721.sol
@inheritdoc ILayerr721/
function updateMetadataSpecificTokens(uint256[] calldata tokenIds) external onlyOwner { for(uint256 i; i < tokenIds.length; ) { emit MetadataUpdate(tokenIds[i]); } }
17,130,906
contract complex{ address add; uint aa; uint bb; function thrower() { throw; } function toggle() returns(uint){ if (aa > 0) aa=0; else aa =1; if (bb > 0) bb=0; else bb = 1; return 0x1337; } } contract proxy{ address add; uint aa; uint bb; function proxy(address a){ add = a; } function (){ assembly{ //gas needs to be uint:ed let g := and(gas,0xEFFFFFFF) let o_code := mload(0x40) //Memory end //Address also needs to be masked //Also, important, storage location must be correct // sload(0) is dependant on the order of declaration above let addr := and(sload(0),0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) //Dest address //Get call data (method sig & params) calldatacopy(o_code, 0, calldatasize) //callcode( let retval := call(g , addr //address , 0 //value , o_code //mem in , calldatasize //mem_insz , o_code //reuse mem , 32) //We expect no return data // Check return value // 0 == it threw, so we do aswell by jumping to // bad destination (02) jumpi(0x02,iszero(retval)) // return(p,s) : end execution, return data mem[p..(p+s)) return(o_code,32) } } }
gas needs to be uint:edAddress also needs to be maskedAlso, important, storage location must be correct sload(0) is dependant on the order of declaration aboveGet call data (method sig & params)callcode( Check return value 0 == it threw, so we do aswell by jumping to bad destination (02) return(p,s) : end execution, return data mem[p..(p+s))
function (){ assembly{ let g := and(gas,0xEFFFFFFF) calldatacopy(o_code, 0, calldatasize) let retval := call(g jumpi(0x02,iszero(retval)) return(o_code,32) } }
2,565,336
pragma solidity >=0.5.6; import "./interfaces/ERC721Enumerable.sol"; import "./ERC721BaseTokenSupply.sol"; /** * @title ERC-721 Non-Fungible Token with enumeration extension logic. * @dev See https://eips.ethereum.org/EIPS/eip-721. */ contract ERC721BaseEnumerable is ERC721BaseTokenSupply, ERC721Enumerable { /** * Mapping of the owner to their list of owned token IDs. */ mapping(address => uint256[]) private _ownedTokens; /** * Mapping of the token ID to its index in the owner array of tokens. */ mapping(uint256 => uint256) private _ownedTokenIndex; bytes4 public constant _INTERFACE_ID_ERC_721_ENUMERABLE = bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ bytes4(keccak256('tokenByIndex(uint256)')); /** * @dev The ERC721Enumerable constructor registers the implementation of ERC721Enumerable interface. */ constructor() public { _registerInterface(_INTERFACE_ID_ERC_721_ENUMERABLE); } /** * @dev Gives the current total amount of tokens stored in the contract. * @return uint256 Represents the total amount of tokens. */ function totalSupply() external view returns (uint256) { return _totalSupply(); } /** * @dev Gives the token ID at the supplied index from all the tokens in the contract. * Reverts if the index is greater or equal to the total supply of tokens (i.e. 0 indexed array). * @param index uint256 Represents the index to be queried. * @return uint256 Token ID at the given index in the global token array. */ function tokenByIndex ( uint256 index ) external view returns (uint256) { return _tokenByIndex(index); } /** * @dev Gives the token ID at the given index in the token array of the queried owner. * @param owner address of the queried owner of tokens. * @param index uint256 Represents the index to be accessed in the requested owner's token array. * @return uint256 Token ID at the given index of the tokens array of the queried owned. */ function tokenOfOwnerByIndex ( address owner, uint256 index ) external view returns (uint256) { require(index < _balanceOf(owner), "Index out of bounds."); return _ownedTokens[owner][index]; } /** * @notice Overriden implementation of the balanceOf function (gas optimization - double storage). */ function _balanceOf ( address owner ) internal view returns (uint256) { require(owner != address(0), "Owner with address(0) is unavailable."); return _ownedTokens[owner].length; } /** * @dev Overrides the implementation of the transferFrom function by adding the enumerable functionality. */ function _transferFrom ( address from, address to, uint256 tokenID ) internal { super._transferFrom(from, to, tokenID); __deleteFromOwnedTokens(tokenID); __insertInOwnedTokens(to, tokenID); } /** * @dev Internal function to add a token (unowned) to an account. * @notice Does not emit any transfer event. Overrides parent implementation. */ function _addTokenTo ( address to, uint256 tokenID ) internal { super._addTokenTo(to, tokenID); __insertInOwnedTokens(to, tokenID); } /** * @dev Internal function to remove a token completely. * @notice Does not emit any transfer event. Overrides parent implementation. */ function _removeToken ( uint256 tokenID ) internal { super._removeToken(tokenID); __deleteFromOwnedTokens(tokenID); } /** * @dev Private helper function to insert a token in the owner's enumeration. Performs no checks. */ function __insertInOwnedTokens ( address to, uint256 tokenID ) private { _ownedTokens[to].push(tokenID); // add token to owner array of tokens _ownedTokenIndex[tokenID] = _ownedTokens[to].length - 1; // added token has last index in owner array } /** * @dev Private helper function to delete a token from the owner's enumeration. Performs no checks. */ function __deleteFromOwnedTokens ( uint256 tokenID ) private { address owner = _ownerOf(tokenID); uint256 tokenIndexInOwner = _ownedTokenIndex[tokenID]; uint256 lastTokenIDInOwner = _ownedTokens[owner][_ownedTokens[owner].length - 1]; _ownedTokens[owner][tokenIndexInOwner] = lastTokenIDInOwner; // swap last token with the one to be deleted _ownedTokens[owner].pop(); // delete last token - duplicate _ownedTokenIndex[lastTokenIDInOwner] = tokenIndexInOwner; // update index of previously last token in array _ownedTokenIndex[tokenID] = 0; // clear the token index } }
Internal function to remove a token completely. Does not emit any transfer event. Overrides parent implementation./
function _removeToken ( uint256 tokenID ) internal { super._removeToken(tokenID); __deleteFromOwnedTokens(tokenID); }
1,783,859
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.6.6; import "./ERC20Permit.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract BosonToken is ERC20Permit, AccessControl { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); uint256 private constant ONE_MILLION = 1 * 10**6; constructor( string memory name, string memory symbol, address _initialTokenOwner ) public ERC20Permit(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _mint(_initialTokenOwner, 200 * ONE_MILLION * 1 ether); } /** * @notice When Token contract is paused, no Token interactions are possible (e.g. approve, transfer, transferFrom or permit) * Requirements: * * - Caller must have PAUSER_ROLE */ function pause() public { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause" ); _pause(); } /** * @notice When Token contract is unpaused, all Token interactions can be executed (e.g. approve, transfer, transferFrom or permit) * Requirements: * * - Caller must have PAUSER_ROLE */ function unpause() public { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause" ); _unpause(); } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.6.6; import "./IERC20Permit.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; contract ERC20Permit is IERC20Permit, Pausable { using SafeMath for uint256; uint256 public chainId; string public override name; string public override symbol; // solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; uint256 public override totalSupply; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) public override allowance; // prevents collision of identical structures. Formed in the initialization of the contract // solhint-disable-next-line var-name-mixedcase bytes32 public override DOMAIN_SEPARATOR; // representation of keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public override nonces; event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); modifier onlyOnDeployedNetwork() { uint256 currChainId = getChainId(); require(currChainId == chainId, "Unsupported network"); _; } constructor(string memory _name, string memory _symbol) public { name = _name; symbol = _symbol; chainId = getChainId(); DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this) ) ); } function getChainId() internal pure returns (uint256) { uint256 currChainId; // solhint-disable-next-line assembly { currChainId := chainid() } return currChainId; } /** * @dev Creates `value` tokens and assigns them to `to`, increasing the total supply. * * Emits a {Transfer} event with `from` set to the zero address. */ function _mint(address to, uint256 value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } /** * @dev Destroys `value` tokens from `from`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. */ function _burn(address from, uint256 value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } /** * @dev Sets `value` 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. */ function _approve( address owner, address spender, uint256 value ) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Moves tokens `amount` from `from` to `to`. * * 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. */ function _transfer( address from, address to, uint256 value ) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } /** * @dev Sets `value` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {Approval} event. */ function approve(address spender, uint256 value) external override whenNotPaused returns (bool) { _approve(msg.sender, spender, value); 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 related to race condition * * Emits an {Approval} event indicating the updated allowance. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( msg.sender, spender, allowance[msg.sender][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 related to race condition * * Emits an {Approval} event indicating the updated allowance. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, allowance[msg.sender][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves `value` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 value) external override whenNotPaused returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Moves `value` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 value ) external override whenNotPaused returns (bool) { if (allowance[from][msg.sender] != uint256(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub( value ); } _transfer(from, to, value); return true; } /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * 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 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 override onlyOnDeployedNetwork whenNotPaused { // solhint-disable-next-line require(deadline >= block.timestamp, "ERC20WithPermit: EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "ERC20WithPermit: INVALID_SIGNATURE" ); _approve(owner, spender, value); } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.6.6; interface IERC20Permit { /** * @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 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 Returns the name of the token. */ function name() external pure returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external pure returns (string memory); /** * @dev Returns the number of decimals used to get its user representation. */ function decimals() external pure returns (uint8); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `owner`. */ function balanceOf(address owner) external view returns (uint256); /** * @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}, {permit} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `value` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {Approval} event. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Moves `value` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Moves `value` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 value ) external returns (bool); /** * @dev Prevents collision of identical structures. Formed in the initialization of the contract */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); /** * @dev representation of keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); */ // solhint-disable-next-line func-name-mixedcase function PERMIT_TYPEHASH() external pure returns (bytes32); /** * @dev Gets incremented every time user successfully executes permit function */ function nonces(address owner) external view returns (uint256); /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; 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()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: 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); } /** * @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); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./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 () internal { _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()); } }
Moves tokens `amount` from `from` to `to`. 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./
function _transfer( address from, address to, uint256 value ) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); }
6,078,087