file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/421613/0x31DfCC1168601537b2BAB3d11065cAfd7E38a3D5/sources/project_/contracts/marketplace/DinoMarketplaceUpgradeable.sol
Cancels an auction that hasn't been won yet. Returns the NFT to original owner. This is a state-modifying function that can be called while the contract is paused. _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId) public onlyNotBlackListed(msg.sender) { Auction storage _auction = auctions[nftAddress][_tokenId]; require(_isOnAuction(_auction), "is_not_on_auction"); require( msg.sender == _auction.seller || admins[msg.sender], "dont_have_pemission" ); _cancelAuction(_tokenId, _auction.seller); }
11,572,743
/** *Submitted for verification at Etherscan.io on 2022-04-21 */ // SPDX-License-Identifier: MIT // File: alloyx-smart-contracts-v2/contracts/goldfinch/interfaces/ICreditLine.sol pragma solidity ^0.8.7; pragma experimental ABIEncoderV2; interface ICreditLine { function borrower() external view returns (address); function limit() external view returns (uint256); function maxLimit() external view returns (uint256); function interestApr() external view returns (uint256); function paymentPeriodInDays() external view returns (uint256); function principalGracePeriodInDays() external view returns (uint256); function termInDays() external view returns (uint256); function lateFeeApr() external view returns (uint256); function isLate() external view returns (bool); function withinPrincipalGracePeriod() external view returns (bool); // Accounting variables function balance() external view returns (uint256); function interestOwed() external view returns (uint256); function principalOwed() external view returns (uint256); function termEndTime() external view returns (uint256); function nextDueTime() external view returns (uint256); function interestAccruedAsOf() external view returns (uint256); function lastFullPaymentTime() external view returns (uint256); } // File: alloyx-smart-contracts-v2/contracts/goldfinch/interfaces/IV2CreditLine.sol pragma solidity ^0.8.7; abstract contract IV2CreditLine is ICreditLine { function principal() external view virtual returns (uint256); function totalInterestAccrued() external view virtual returns (uint256); function termStartTime() external view virtual returns (uint256); function setLimit(uint256 newAmount) external virtual; function setMaxLimit(uint256 newAmount) external virtual; function setBalance(uint256 newBalance) external virtual; function setPrincipal(uint256 _principal) external virtual; function setTotalInterestAccrued(uint256 _interestAccrued) external virtual; function drawdown(uint256 amount) external virtual; function assess() external virtual returns ( uint256, uint256, uint256 ); function initialize( address _config, address owner, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays ) public virtual; function setTermEndTime(uint256 newTermEndTime) external virtual; function setNextDueTime(uint256 newNextDueTime) external virtual; function setInterestOwed(uint256 newInterestOwed) external virtual; function setPrincipalOwed(uint256 newPrincipalOwed) external virtual; function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual; function setWritedownAmount(uint256 newWritedownAmount) external virtual; function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual; function setLateFeeApr(uint256 newLateFeeApr) external virtual; function updateGoldfinchConfig() external virtual; } // File: alloyx-smart-contracts-v2/contracts/goldfinch/interfaces/ITranchedPool.sol pragma solidity ^0.8.7; abstract contract ITranchedPool { IV2CreditLine public creditLine; uint256 public createdAt; enum Tranches { Reserved, Senior, Junior } struct TrancheInfo { uint256 id; uint256 principalDeposited; uint256 principalSharePrice; uint256 interestSharePrice; uint256 lockedUntil; } struct PoolSlice { TrancheInfo seniorTranche; TrancheInfo juniorTranche; uint256 totalInterestAccrued; uint256 principalDeployed; } struct SliceInfo { uint256 reserveFeePercent; uint256 interestAccrued; uint256 principalAccrued; } struct ApplyResult { uint256 interestRemaining; uint256 principalRemaining; uint256 reserveDeduction; uint256 oldInterestSharePrice; uint256 oldPrincipalSharePrice; } function initialize( address _config, address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays, uint256 _fundableAt, uint256[] calldata _allowedUIDTypes ) public virtual; function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory); function pay(uint256 amount) external virtual; function lockJuniorCapital() external virtual; function lockPool() external virtual; function initializeNextSlice(uint256 _fundableAt) external virtual; function totalJuniorDeposits() external view virtual returns (uint256); function drawdown(uint256 amount) external virtual; function setFundableAt(uint256 timestamp) external virtual; function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId); function assess() external virtual; function depositWithPermit( uint256 tranche, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 tokenId); function availableToWithdraw(uint256 tokenId) external view virtual returns (uint256 interestRedeemable, uint256 principalRedeemable); function withdraw(uint256 tokenId, uint256 amount) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMax(uint256 tokenId) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual; } // File: alloyx-smart-contracts-v2/contracts/goldfinch/interfaces/ISeniorPool.sol pragma solidity ^0.8.7; abstract contract ISeniorPool { uint256 public sharePrice; uint256 public totalLoansOutstanding; uint256 public totalWritedowns; function deposit(uint256 amount) external virtual returns (uint256 depositShares); function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 depositShares); function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount); function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function invest(ITranchedPool pool) public virtual; function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256); function redeem(uint256 tokenId) public virtual; function writedown(uint256 tokenId) public virtual; function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount); function assets() public view virtual returns (uint256); function getNumShares(uint256 amount) public view virtual returns (uint256); } // File: @openzeppelin/contracts/utils/math/Math.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // 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/token/ERC721/utils/ERC721Holder.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // 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/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/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: alloyx-smart-contracts-v2/contracts/goldfinch/interfaces/IPoolTokens.sol pragma solidity ^0.8.7; interface IPoolTokens is IERC721, IERC721Enumerable { event TokenMinted( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 amount, uint256 tranche ); event TokenRedeemed( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 principalRedeemed, uint256 interestRedeemed, uint256 tranche ); event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId); struct TokenInfo { address pool; uint256 tranche; uint256 principalAmount; uint256 principalRedeemed; uint256 interestRedeemed; } struct MintParams { uint256 principalAmount; uint256 tranche; } function mint(MintParams calldata params, address to) external returns (uint256); function redeem( uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed ) external; function burn(uint256 tokenId) external; function onPoolCreated(address newPool) external; function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory); function validPool(address sender) external view returns (bool); function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/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/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: alloyx-smart-contracts-v2/contracts/alloyx/AlloyxTokenCRWN.sol pragma solidity ^0.8.2; contract AlloyxTokenCRWN is ERC20, Ownable { constructor() ERC20("Crown Gold", "CRWN") {} function mint(address _account, uint256 _amount) external onlyOwner returns (bool) { _mint(_account, _amount); return true; } function burn(address _account, uint256 _amount) external onlyOwner returns (bool) { _burn(_account, _amount); return true; } function contractName() external pure returns (string memory) { return "AlloyxTokenCRWN"; } } // File: alloyx-smart-contracts-v2/contracts/alloyx/AlloyxTokenDURA.sol pragma solidity ^0.8.2; contract AlloyxTokenDURA is ERC20, Ownable { constructor() ERC20("Duralumin", "DURA") {} function mint(address _account, uint256 _amount) external onlyOwner returns (bool) { _mint(_account, _amount); return true; } function burn(address _account, uint256 _amount) external onlyOwner returns (bool) { _burn(_account, _amount); return true; } function contractName() external pure returns (string memory) { return "AlloyxTokenDura"; } } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // 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: alloyx-smart-contracts-v2/contracts/alloyx/IGoldfinchDelegacy.sol pragma solidity ^0.8.7; /** * @title Goldfinch Delegacy Interface * @notice Middle layer to communicate with goldfinch contracts * @author AlloyX */ interface IGoldfinchDelegacy { /** * @notice GoldFinch PoolToken Value in Value in term of USDC */ function getGoldfinchDelegacyBalanceInUSDC() external view returns (uint256); /** * @notice Claim certain amount of reward token based on alloy silver token, the method will burn the silver token of * the amount of message sender, and transfer reward token to message sender * @param _rewardee the address of rewardee * @param _amount the amount of silver tokens used to claim * @param _totalSupply total claimable and claimed silver tokens of all stakeholders * @param _percentageFee the earning fee for redeeming silver token in percentage in terms of GFI */ function claimReward( address _rewardee, uint256 _amount, uint256 _totalSupply, uint256 _percentageFee ) external; /** * @notice Get gfi amount that should be transfered to the claimer for the amount of CRWN * @param _amount the amount of silver tokens used to claim * @param _totalSupply total claimable and claimed silver tokens of all stakeholders * @param _percentageFee the earning fee for redeeming silver token in percentage in terms of GFI */ function getRewardAmount( uint256 _amount, uint256 _totalSupply, uint256 _percentageFee ) external view returns (uint256); /** * @notice Purchase junior token through this delegacy to get pooltoken inside this delegacy * @param _amount the amount of usdc to purchase by * @param _poolAddress the pool address to buy from * @param _tranche the tranch id */ function purchaseJuniorToken( uint256 _amount, address _poolAddress, uint256 _tranche ) external; /** * @notice Sell junior token through this delegacy to get repayments * @param _tokenId the ID of token to sell * @param _amount the amount to withdraw * @param _poolAddress the pool address to withdraw from * @param _percentageBronzeRepayment the repayment fee for bronze token in percentage */ function sellJuniorToken( uint256 _tokenId, uint256 _amount, address _poolAddress, uint256 _percentageBronzeRepayment ) external; /** * @notice Purchase senior token through this delegacy to get FIDU inside this delegacy * @param _amount the amount of USDC to purchase by */ function purchaseSeniorTokens(uint256 _amount) external; /** * @notice sell senior token through delegacy to redeem fidu * @param _amount the amount of fidu to sell * @param _percentageBronzeRepayment the repayment fee for bronze token in percentage */ function sellSeniorTokens(uint256 _amount, uint256 _percentageBronzeRepayment) external; /** * @notice Validates the Pooltoken to be deposited and get the USDC value of the token * @param _tokenAddress the Pooltoken address * @param _depositor the person to deposit * @param _tokenID the ID of the Pooltoken */ function validatesTokenToDepositAndGetPurchasePrice( address _tokenAddress, address _depositor, uint256 _tokenID ) external returns (uint256); /** * @notice Pay USDC tokens to account * @param _to the address to pay to * @param _amount the amount to pay */ function payUsdc(address _to, uint256 _amount) external; /** * @notice Approve certain amount token of certain address to some other account * @param _account the address to approve * @param _amount the amount to approve * @param _tokenAddress the token address to approve */ function approve( address _tokenAddress, address _account, uint256 _amount ) external; } // File: alloyx-smart-contracts-v2/contracts/alloyx/v4.0/AlloyxVaultV4.0.sol pragma solidity ^0.8.7; /** * @title AlloyX Vault * @notice Initial vault for AlloyX. This vault holds loan tokens generated on Goldfinch * and emits AlloyTokens when a liquidity provider deposits supported stable coins. * @author AlloyX */ contract AlloyxVaultV4_0 is ERC721Holder, Ownable, Pausable { using SafeERC20 for IERC20; using SafeERC20 for AlloyxTokenDURA; using SafeMath for uint256; struct StakeInfo { uint256 amount; uint256 since; } bool private vaultStarted; IERC20 private usdcCoin; AlloyxTokenDURA private alloyxTokenDURA; AlloyxTokenCRWN private alloyxTokenCRWN; IGoldfinchDelegacy private goldfinchDelegacy; address[] internal stakeholders; mapping(address => StakeInfo) private stakesMapping; mapping(address => uint256) private pastRedeemableReward; mapping(address => bool) whitelistedAddresses; uint256 public percentageRewardPerYear = 2; uint256 public percentageDURARedemption = 1; uint256 public percentageDURARepayment = 2; uint256 public percentageCRWNEarning = 10; uint256 public redemptionFee = 0; event DepositStable(address _tokenAddress, address _tokenSender, uint256 _tokenAmount); event DepositNFT(address _tokenAddress, address _tokenSender, uint256 _tokenID); event DepositAlloyx(address _tokenAddress, address _tokenSender, uint256 _tokenAmount); event PurchaseSenior(uint256 amount); event SellSenior(uint256 amount); event PurchaseJunior(uint256 amount); event SellJunior(uint256 amount); event Mint(address _tokenReceiver, uint256 _tokenAmount); event Burn(address _tokenReceiver, uint256 _tokenAmount); event Reward(address _tokenReceiver, uint256 _tokenAmount); event Claim(address _tokenReceiver, uint256 _tokenAmount); event Stake(address _staker, uint256 _amount); event Unstake(address _unstaker, uint256 _amount); constructor( address _alloyxDURAAddress, address _alloyxCRWNAddress, address _usdcCoinAddress, address _goldfinchDelegacy ) { alloyxTokenDURA = AlloyxTokenDURA(_alloyxDURAAddress); alloyxTokenCRWN = AlloyxTokenCRWN(_alloyxCRWNAddress); usdcCoin = IERC20(_usdcCoinAddress); goldfinchDelegacy = IGoldfinchDelegacy(_goldfinchDelegacy); vaultStarted = false; } /** * @notice If vault is started */ modifier whenVaultStarted() { require(vaultStarted, "Vault has not start accepting deposits"); _; } /** * @notice If vault is not started */ modifier whenVaultNotStarted() { require(!vaultStarted, "Vault has already start accepting deposits"); _; } /** * @notice If address is whitelisted * @param _address The address to verify. */ modifier isWhitelisted(address _address) { require(whitelistedAddresses[_address], "You need to be whitelisted"); _; } /** * @notice If address is not whitelisted * @param _address The address to verify. */ modifier notWhitelisted(address _address) { require(!whitelistedAddresses[_address], "You are whitelisted"); _; } /** * @notice Initialize by minting the alloy brown tokens to owner */ function startVaultOperation() external onlyOwner whenVaultNotStarted returns (bool) { uint256 totalBalanceInUSDC = getAlloyxDURATokenBalanceInUSDC(); require(totalBalanceInUSDC > 0, "Vault must have positive value before start"); alloyxTokenDURA.mint( address(this), totalBalanceInUSDC.mul(alloyMantissa()).div(usdcMantissa()) ); vaultStarted = true; return true; } /** * @notice Pause all operations except migration of tokens */ function pause() external onlyOwner whenNotPaused { _pause(); } /** * @notice Unpause all operations */ function unpause() external onlyOwner whenPaused { _unpause(); } /** * @notice Add whitelist address * @param _addressToWhitelist The address to whitelist. */ function addWhitelistedUser(address _addressToWhitelist) public onlyOwner notWhitelisted(_addressToWhitelist) { whitelistedAddresses[_addressToWhitelist] = true; } /** * @notice Remove whitelist address * @param _addressToDeWhitelist The address to de-whitelist. */ function removeWhitelistedUser(address _addressToDeWhitelist) public onlyOwner isWhitelisted(_addressToDeWhitelist) { whitelistedAddresses[_addressToDeWhitelist] = false; } /** * @notice Check whether user is whitelisted * @param _whitelistedAddress The address to whitelist. */ function isUserWhitelisted(address _whitelistedAddress) public view returns (bool) { return whitelistedAddresses[_whitelistedAddress]; } /** * @notice Check if an address is a stakeholder. * @param _address The address to verify. * @return bool, uint256 Whether the address is a stakeholder, * and if so its position in the stakeholders array. */ function isStakeholder(address _address) public view returns (bool, uint256) { for (uint256 s = 0; s < stakeholders.length; s += 1) { if (_address == stakeholders[s]) return (true, s); } return (false, 0); } /** * @notice Add a stakeholder. * @param _stakeholder The stakeholder to add. */ function addStakeholder(address _stakeholder) internal { (bool _isStakeholder, ) = isStakeholder(_stakeholder); if (!_isStakeholder) stakeholders.push(_stakeholder); } /** * @notice Remove a stakeholder. * @param _stakeholder The stakeholder to remove. */ function removeStakeholder(address _stakeholder) internal { (bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder); if (_isStakeholder) { stakeholders[s] = stakeholders[stakeholders.length - 1]; stakeholders.pop(); } } /** * @notice Retrieve the stake for a stakeholder. * @param _stakeholder The stakeholder to retrieve the stake for. * @return Stake The amount staked and the time since when it's staked. */ function stakeOf(address _stakeholder) public view returns (StakeInfo memory) { return stakesMapping[_stakeholder]; } /** * @notice A method for a stakeholder to reset the timestamp of the stake. */ function resetStakeTimestamp() internal { if (stakesMapping[msg.sender].amount == 0) addStakeholder(msg.sender); addPastRedeemableReward(msg.sender, stakesMapping[msg.sender]); stakesMapping[msg.sender] = StakeInfo(stakesMapping[msg.sender].amount, block.timestamp); } /** * @notice Add stake for a staker * @param _staker The person intending to stake * @param _stake The size of the stake to be created. */ function addStake(address _staker, uint256 _stake) internal { if (stakesMapping[_staker].amount == 0) addStakeholder(_staker); addPastRedeemableReward(_staker, stakesMapping[_staker]); stakesMapping[_staker] = StakeInfo(stakesMapping[_staker].amount.add(_stake), block.timestamp); } /** * @notice Remove stake for a staker * @param _staker The person intending to remove stake * @param _stake The size of the stake to be removed. */ function removeStake(address _staker, uint256 _stake) internal { require(stakeOf(_staker).amount >= _stake, "User has insufficient dura coin staked"); if (stakesMapping[_staker].amount == 0) addStakeholder(_staker); addPastRedeemableReward(_staker, stakesMapping[_staker]); stakesMapping[_staker] = StakeInfo(stakesMapping[_staker].amount.sub(_stake), block.timestamp); } /** * @notice Add the stake to past redeemable reward * @param _stake the stake to be added into the reward */ function addPastRedeemableReward(address _staker, StakeInfo storage _stake) internal { uint256 additionalPastRedeemableReward = calculateRewardFromStake(_stake); pastRedeemableReward[_staker] = pastRedeemableReward[_staker].add( additionalPastRedeemableReward ); } /** * @notice Stake more into the vault, which will cause the user's DURA token to transfer to vault * @param _amount the amount the message sender intending to stake in */ function stake(uint256 _amount) external whenNotPaused whenVaultStarted returns (bool) { addStake(msg.sender, _amount); alloyxTokenDURA.safeTransferFrom(msg.sender, address(this), _amount); emit Stake(msg.sender, _amount); return true; } /** * @notice Unstake some from the vault, which will cause the vault to transfer DURA token back to message sender * @param _amount the amount the message sender intending to unstake */ function unstake(uint256 _amount) external whenNotPaused whenVaultStarted returns (bool) { removeStake(msg.sender, _amount); alloyxTokenDURA.safeTransfer(msg.sender, _amount); emit Unstake(msg.sender, _amount); return true; } /** * @notice A method for a stakeholder to clear a stake. */ function clearStake() internal { resetStakeTimestamp(); } /** * @notice A method for a stakeholder to clear a stake with some leftover reward * @param _reward the leftover reward the staker owns */ function resetStakeTimestampWithRewardLeft(uint256 _reward) internal { resetStakeTimestamp(); pastRedeemableReward[msg.sender] = _reward; } function calculateRewardFromStake(StakeInfo memory _stake) internal view returns (uint256) { return _stake .amount .mul(block.timestamp.sub(_stake.since)) .mul(percentageRewardPerYear) .div(100) .div(365 days); } /** * @notice Claimable CRWN token amount of an address * @param _receiver the address of receiver */ function claimableCRWNToken(address _receiver) public view returns (uint256) { StakeInfo memory stakeValue = stakeOf(_receiver); return pastRedeemableReward[_receiver] + calculateRewardFromStake(stakeValue); } /** * @notice Total claimable CRWN tokens of all stakeholders */ function totalClaimableCRWNToken() public view returns (uint256) { uint256 total = 0; for (uint256 i = 0; i < stakeholders.length; i++) { total = total.add(claimableCRWNToken(stakeholders[i])); } return total; } /** * @notice Total claimable and claimed CRWN tokens of all stakeholders */ function totalClaimableAndClaimedCRWNToken() public view returns (uint256) { return totalClaimableCRWNToken().add(alloyxTokenCRWN.totalSupply()); } /** * @notice Claim all alloy CRWN tokens of the message sender, the method will mint the CRWN token of the claimable * amount to message sender, and clear the past rewards to zero */ function claimAllAlloyxCRWN() external whenNotPaused whenVaultStarted returns (bool) { uint256 reward = claimableCRWNToken(msg.sender); alloyxTokenCRWN.mint(msg.sender, reward); resetStakeTimestampWithRewardLeft(0); emit Claim(msg.sender, reward); return true; } /** * @notice Claim certain amount of alloy CRWN tokens of the message sender, the method will mint the CRWN token of * the claimable amount to message sender, and clear the past rewards to the remainder * @param _amount the amount to claim */ function claimAlloyxCRWN(uint256 _amount) external whenNotPaused whenVaultStarted returns (bool) { uint256 allReward = claimableCRWNToken(msg.sender); require(allReward >= _amount, "User has claimed more than he's entitled"); alloyxTokenCRWN.mint(msg.sender, _amount); resetStakeTimestampWithRewardLeft(allReward.sub(_amount)); emit Claim(msg.sender, _amount); return true; } /** * @notice Claim certain amount of reward token based on alloy CRWN token, the method will burn the CRWN token of * the amount of message sender, and transfer reward token to message sender * @param _amount the amount to claim */ function claimReward(uint256 _amount) external whenNotPaused whenVaultStarted returns (bool) { require( alloyxTokenCRWN.balanceOf(address(msg.sender)) >= _amount, "Balance of crown coin must be larger than the amount to claim" ); goldfinchDelegacy.claimReward( msg.sender, _amount, totalClaimableAndClaimedCRWNToken(), percentageCRWNEarning ); alloyxTokenCRWN.burn(msg.sender, _amount); emit Reward(msg.sender, _amount); return true; } /** * @notice Get reward token count if the amount of CRWN tokens are claimed * @param _amount the amount to claim */ function getRewardTokenCount(uint256 _amount) external view returns (uint256) { return goldfinchDelegacy.getRewardAmount( _amount, totalClaimableAndClaimedCRWNToken(), percentageCRWNEarning ); } /** * @notice Request the delegacy to approve certain tokens on certain account for certain amount, it is most used for * buying the goldfinch tokens, they need to be able to transfer usdc to them * @param _tokenAddress the leftover reward the staker owns * @param _account the account the delegacy going to approve * @param _amount the amount the delegacy going to approve */ function approveDelegacy( address _tokenAddress, address _account, uint256 _amount ) external onlyOwner { goldfinchDelegacy.approve(_tokenAddress, _account, _amount); } /** * @notice Alloy DURA Token Value in terms of USDC */ function getAlloyxDURATokenBalanceInUSDC() public view returns (uint256) { uint256 totalValue = getUSDCBalance().add( goldfinchDelegacy.getGoldfinchDelegacyBalanceInUSDC() ); require( totalValue > redemptionFee, "the value of vault is not larger than redemption fee, something went wrong" ); return getUSDCBalance().add(goldfinchDelegacy.getGoldfinchDelegacyBalanceInUSDC()).sub( redemptionFee ); } /** * @notice USDC Value in Vault */ function getUSDCBalance() internal view returns (uint256) { return usdcCoin.balanceOf(address(this)); } /** * @notice Convert Alloyx DURA to USDC amount * @param _amount the amount of DURA token to convert to usdc */ function alloyxDURAToUSDC(uint256 _amount) public view returns (uint256) { uint256 alloyDURATotalSupply = alloyxTokenDURA.totalSupply(); uint256 totalVaultAlloyxDURAValueInUSDC = getAlloyxDURATokenBalanceInUSDC(); return _amount.mul(totalVaultAlloyxDURAValueInUSDC).div(alloyDURATotalSupply); } /** * @notice Convert USDC Amount to Alloyx DURA * @param _amount the amount of usdc to convert to DURA token */ function usdcToAlloyxDURA(uint256 _amount) public view returns (uint256) { uint256 alloyDURATotalSupply = alloyxTokenDURA.totalSupply(); uint256 totalVaultAlloyxDURAValueInUSDC = getAlloyxDURATokenBalanceInUSDC(); return _amount.mul(alloyDURATotalSupply).div(totalVaultAlloyxDURAValueInUSDC); } /** * @notice Set percentageRewardPerYear which is the reward per year in percentage * @param _percentageRewardPerYear the reward per year in percentage */ function setPercentageRewardPerYear(uint256 _percentageRewardPerYear) external onlyOwner { percentageRewardPerYear = _percentageRewardPerYear; } /** * @notice Set percentageDURARedemption which is the redemption fee for DURA token in percentage * @param _percentageDURARedemption the redemption fee for DURA token in percentage */ function setPercentageDURARedemption(uint256 _percentageDURARedemption) external onlyOwner { percentageDURARedemption = _percentageDURARedemption; } /** * @notice Set percentageDURARepayment which is the repayment fee for DURA token in percentage * @param _percentageDURARepayment the repayment fee for DURA token in percentage */ function setPercentageDURARepayment(uint256 _percentageDURARepayment) external onlyOwner { percentageDURARepayment = _percentageDURARepayment; } /** * @notice Set percentageCRWNEarning which is the earning fee for redeeming CRWN token in percentage in terms of gfi * @param _percentageCRWNEarning the earning fee for redeeming CRWN token in percentage in terms of gfi */ function setPercentageCRWNEarning(uint256 _percentageCRWNEarning) external onlyOwner { percentageCRWNEarning = _percentageCRWNEarning; } /** * @notice Alloy token with 18 decimals */ function alloyMantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } /** * @notice USDC mantissa with 6 decimals */ function usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } /** * @notice Change DURA token address * @param _alloyxAddress the address to change to */ function changeAlloyxDURAAddress(address _alloyxAddress) external onlyOwner { alloyxTokenDURA = AlloyxTokenDURA(_alloyxAddress); } function changeGoldfinchDelegacyAddress(address _goldfinchDelegacy) external onlyOwner { goldfinchDelegacy = IGoldfinchDelegacy(_goldfinchDelegacy); } /** * @notice An Alloy token holder can deposit their tokens and redeem them for USDC * @param _tokenAmount Number of Alloy Tokens */ function depositAlloyxDURATokens(uint256 _tokenAmount) external whenNotPaused whenVaultStarted isWhitelisted(msg.sender) returns (bool) { require( alloyxTokenDURA.balanceOf(msg.sender) >= _tokenAmount, "User has insufficient alloyx coin." ); require( alloyxTokenDURA.allowance(msg.sender, address(this)) >= _tokenAmount, "User has not approved the vault for sufficient alloyx coin" ); uint256 amountToWithdraw = alloyxDURAToUSDC(_tokenAmount); uint256 withdrawalFee = amountToWithdraw.mul(percentageDURARedemption).div(100); require(amountToWithdraw > 0, "The amount of stable coin to get is not larger than 0"); require( usdcCoin.balanceOf(address(this)) >= amountToWithdraw, "The vault does not have sufficient stable coin" ); alloyxTokenDURA.burn(msg.sender, _tokenAmount); usdcCoin.safeTransfer(msg.sender, amountToWithdraw.sub(withdrawalFee)); redemptionFee = redemptionFee.add(withdrawalFee); emit DepositAlloyx(address(alloyxTokenDURA), msg.sender, _tokenAmount); emit Burn(msg.sender, _tokenAmount); return true; } /** * @notice A Liquidity Provider can deposit supported stable coins for Alloy Tokens * @param _tokenAmount Number of stable coin */ function depositUSDCCoin(uint256 _tokenAmount) external whenNotPaused whenVaultStarted isWhitelisted(msg.sender) returns (bool) { require(usdcCoin.balanceOf(msg.sender) >= _tokenAmount, "User has insufficient stable coin"); require( usdcCoin.allowance(msg.sender, address(this)) >= _tokenAmount, "User has not approved the vault for sufficient stable coin" ); uint256 amountToMint = usdcToAlloyxDURA(_tokenAmount); require(amountToMint > 0, "The amount of alloyx DURA coin to get is not larger than 0"); usdcCoin.safeTransferFrom(msg.sender, address(goldfinchDelegacy), _tokenAmount); alloyxTokenDURA.mint(msg.sender, amountToMint); emit DepositStable(address(usdcCoin), msg.sender, amountToMint); emit Mint(msg.sender, amountToMint); return true; } /** * @notice A Liquidity Provider can deposit supported stable coins for Alloy Tokens * @param _tokenAmount Number of stable coin */ function depositUSDCCoinWithStake(uint256 _tokenAmount) external whenNotPaused whenVaultStarted isWhitelisted(msg.sender) returns (bool) { require(usdcCoin.balanceOf(msg.sender) >= _tokenAmount, "User has insufficient stable coin"); require( usdcCoin.allowance(msg.sender, address(this)) >= _tokenAmount, "User has not approved the vault for sufficient stable coin" ); uint256 amountToMint = usdcToAlloyxDURA(_tokenAmount); require(amountToMint > 0, "The amount of alloyx DURA coin to get is not larger than 0"); usdcCoin.safeTransferFrom(msg.sender, address(this), _tokenAmount); alloyxTokenDURA.mint(address(this), amountToMint); addStake(msg.sender, amountToMint); emit DepositStable(address(usdcCoin), msg.sender, amountToMint); emit Mint(address(this), amountToMint); return true; } /** * @notice A Junior token holder can deposit their NFT for stable coin * @param _tokenAddress NFT Address * @param _tokenID NFT ID */ function depositNFTToken(address _tokenAddress, uint256 _tokenID) external whenNotPaused whenVaultStarted isWhitelisted(msg.sender) returns (bool) { uint256 purchasePrice = goldfinchDelegacy.validatesTokenToDepositAndGetPurchasePrice( _tokenAddress, msg.sender, _tokenID ); IERC721(_tokenAddress).safeTransferFrom(msg.sender, address(goldfinchDelegacy), _tokenID); goldfinchDelegacy.payUsdc(msg.sender, purchasePrice); emit DepositNFT(_tokenAddress, msg.sender, _tokenID); return true; } /** * @notice Purchase junior token through delegacy to get pooltoken inside the delegacy * @param _amount the amount of usdc to purchase by * @param _poolAddress the pool address to buy from * @param _tranche the tranch id */ function purchaseJuniorToken( uint256 _amount, address _poolAddress, uint256 _tranche ) external onlyOwner { require(_amount > 0, "Must deposit more than zero"); goldfinchDelegacy.purchaseJuniorToken(_amount, _poolAddress, _tranche); emit PurchaseJunior(_amount); } /** * @notice Sell junior token through delegacy to get repayments * @param _tokenId the ID of token to sell * @param _amount the amount to withdraw * @param _poolAddress the pool address to withdraw from */ function sellJuniorToken( uint256 _tokenId, uint256 _amount, address _poolAddress ) external onlyOwner { require(_amount > 0, "Must sell more than zero"); goldfinchDelegacy.sellJuniorToken(_tokenId, _amount, _poolAddress, percentageDURARepayment); emit SellSenior(_amount); } /** * @notice Purchase senior token through delegacy to get fidu inside the delegacy * @param _amount the amount of usdc to purchase by */ function purchaseSeniorTokens(uint256 _amount) external onlyOwner { require(_amount > 0, "Must deposit more than zero"); goldfinchDelegacy.purchaseSeniorTokens(_amount); emit PurchaseSenior(_amount); } /** * @notice Sell senior token through delegacy to redeem fidu * @param _amount the amount of fidu to sell */ function sellSeniorTokens(uint256 _amount) external onlyOwner { require(_amount > 0, "Must sell more than zero"); goldfinchDelegacy.sellSeniorTokens(_amount, percentageDURARepayment); emit SellSenior(_amount); } /** * @notice Destroy the contract */ function destroy() external onlyOwner whenPaused { require(usdcCoin.balanceOf(address(this)) == 0, "Balance of stable coin must be 0"); address payable addr = payable(address(owner())); selfdestruct(addr); } /** * @notice Migrate certain ERC20 to an address * @param _tokenAddress the token address to migrate * @param _to the address to transfer tokens to */ function migrateERC20(address _tokenAddress, address _to) external onlyOwner whenPaused { uint256 balance = IERC20(_tokenAddress).balanceOf(address(this)); IERC20(_tokenAddress).safeTransfer(_to, balance); } /** * @notice Transfer redemption fee to some other address * @param _to the address to transfer to */ function transferRedemptionFee(address _to) external onlyOwner whenNotPaused { usdcCoin.safeTransfer(_to, redemptionFee); redemptionFee = 0; } /** * @notice Transfer the ownership of alloy CRWN and DURA token contract to some other address * @param _to the address to transfer ownership to */ function transferAlloyxOwnership(address _to) external onlyOwner whenPaused { alloyxTokenDURA.transferOwnership(_to); alloyxTokenCRWN.transferOwnership(_to); } }
Set percentageDURARepayment which is the repayment fee for DURA token in percentage _percentageDURARepayment the repayment fee for DURA token in percentage/
function setPercentageDURARepayment(uint256 _percentageDURARepayment) external onlyOwner { percentageDURARepayment = _percentageDURARepayment; }
10,762,077
./full_match/80001/0x14e39aDc79A7610c685143c4cd891F94dB3B40cD/sources/@aragon/osx/framework/plugin/repo/PluginRepo.sol
Returns the latest version for a given release number. _release The release number. return The latest version of this release.
function getLatestVersion(uint8 _release) public view returns (Version memory) { uint16 latestBuild = uint16(buildsPerRelease[_release]); return getVersion(tagHash(Tag(_release, latestBuild))); }
5,569,473
pragma solidity >=0.4.0 <0.6.0; /* Copyright 2017, Jordi Baylina Contributors: Adrià Massanet <[email protected]>, RJ Ewing, Griff Green, Arthur Lunn This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import "./ILiquidPledging.sol"; import "./LiquidPledgingStorage.sol"; import "./PledgeAdmins.sol"; import "./Pledges.sol"; import "@aragon/os/contracts/apps/AragonApp.sol"; /// @dev `LiquidPledgingBase` is the base level contract used to carry out /// liquidPledging's most basic functions, mostly handling and searching the /// data structures contract LiquidPledgingBase is ILiquidPledging, AragonApp, LiquidPledgingStorage, PledgeAdmins, Pledges { event Transfer(uint indexed from, uint indexed to, uint amount); event CancelProject(uint indexed idProject); ///////////// // Modifiers ///////////// /// @dev The `vault`is the only addresses that can call a function with this /// modifier modifier onlyVault() { require(msg.sender == address(vault)); _; } /////////////// // Constructor /////////////// /// @param _vault The vault where the ETH backing the pledges is stored function initialize(address _vault) onlyInit public { require(_vault != 0x0); initialized(); vault = ILPVault(_vault); admins.length = 1; // we reserve the 0 admin pledges.length = 1; // we reserve the 0 pledge } ///////////////////////////// // Public constant functions ///////////////////////////// /// @notice Getter to find Delegate w/ the Pledge ID & the Delegate index /// @param idPledge The id number representing the pledge being queried /// @param idxDelegate The index number for the delegate in this Pledge function getPledgeDelegate(uint64 idPledge, uint64 idxDelegate) external view returns( uint64 idDelegate, address addr, string name ) { Pledge storage p = _findPledge(idPledge); idDelegate = p.delegationChain[idxDelegate - 1]; PledgeAdmin storage delegate = _findAdmin(idDelegate); addr = delegate.addr; name = delegate.name; } /////////////////// // Public functions /////////////////// /// @notice Only affects pledges with the Pledged PledgeState for 2 things: /// #1: Checks if the pledge should be committed. This means that /// if the pledge has an intendedProject and it is past the /// commitTime, it changes the owner to be the proposed project /// (The UI will have to read the commit time and manually do what /// this function does to the pledge for the end user /// at the expiration of the commitTime) /// /// #2: Checks to make sure that if there has been a cancellation in the /// chain of projects, the pledge's owner has been changed /// appropriately. /// /// This function can be called by anybody at anytime on any pledge. /// In general it can be called to force the calls of the affected /// plugins, which also need to be predicted by the UI /// @param idPledge This is the id of the pledge that will be normalized /// @return The normalized Pledge! function normalizePledge(uint64 idPledge) public returns(uint64) { Pledge storage p = _findPledge(idPledge); // Check to make sure this pledge hasn't already been used // or is in the process of being used if (p.pledgeState != PledgeState.Pledged) { return idPledge; } // First send to a project if it's proposed and committed if ((p.intendedProject > 0) && ( _getTime() > p.commitTime)) { uint64 oldPledge = _findOrCreatePledge( p.owner, p.delegationChain, 0, 0, p.oldPledge, p.token, PledgeState.Pledged ); uint64 toPledge = _findOrCreatePledge( p.intendedProject, new uint64[](0), 0, 0, oldPledge, p.token, PledgeState.Pledged ); _doTransfer(idPledge, toPledge, p.amount); idPledge = toPledge; p = _findPledge(idPledge); } toPledge = _getOldestPledgeNotCanceled(idPledge); if (toPledge != idPledge) { _doTransfer(idPledge, toPledge, p.amount); } return toPledge; } //////////////////// // Internal methods //////////////////// /// @notice A check to see if the msg.sender is the owner or the /// plugin contract for a specific Admin /// @param idAdmin The id of the admin being checked function _checkAdminOwner(uint64 idAdmin) internal view { PledgeAdmin storage a = _findAdmin(idAdmin); require(msg.sender == address(a.plugin) || msg.sender == a.addr); } function _transfer( uint64 idSender, uint64 idPledge, uint amount, uint64 idReceiver ) internal { require(idReceiver > 0); // prevent burning value idPledge = normalizePledge(idPledge); Pledge storage p = _findPledge(idPledge); PledgeAdmin storage receiver = _findAdmin(idReceiver); require(p.pledgeState == PledgeState.Pledged); // If the sender is the owner of the Pledge if (p.owner == idSender) { if (receiver.adminType == PledgeAdminType.Giver) { _transferOwnershipToGiver(idPledge, amount, idReceiver); return; } else if (receiver.adminType == PledgeAdminType.Project) { _transferOwnershipToProject(idPledge, amount, idReceiver); return; } else if (receiver.adminType == PledgeAdminType.Delegate) { uint recieverDIdx = _getDelegateIdx(p, idReceiver); if (p.intendedProject > 0 && recieverDIdx != NOTFOUND) { // if there is an intendedProject and the receiver is in the delegationChain, // then we want to preserve the delegationChain as this is a veto of the // intendedProject by the owner if (recieverDIdx == p.delegationChain.length - 1) { uint64 toPledge = _findOrCreatePledge( p.owner, p.delegationChain, 0, 0, p.oldPledge, p.token, PledgeState.Pledged); _doTransfer(idPledge, toPledge, amount); return; } _undelegate(idPledge, amount, p.delegationChain.length - receiverDIdx - 1); return; } // owner is not vetoing an intendedProject and is transferring the pledge to a delegate, // so we want to reset the delegationChain idPledge = _undelegate( idPledge, amount, p.delegationChain.length ); _appendDelegate(idPledge, amount, idReceiver); return; } // This should never be reached as the receiver.adminType // should always be either a Giver, Project, or Delegate assert(false); } // If the sender is a Delegate uint senderDIdx = _getDelegateIdx(p, idSender); if (senderDIdx != NOTFOUND) { // And the receiver is another Giver if (receiver.adminType == PledgeAdminType.Giver) { // Only transfer to the Giver who owns the pledge assert(p.owner == idReceiver); _undelegate(idPledge, amount, p.delegationChain.length); return; } // And the receiver is another Delegate if (receiver.adminType == PledgeAdminType.Delegate) { uint receiverDIdx = _getDelegateIdx(p, idReceiver); // And not in the delegationChain or part of the delegationChain // is after the sender, then all of the other delegates after // the sender are removed and the receiver is appended at the // end of the delegationChain if (receiverDIdx == NOTFOUND || receiverDIdx > senderDIdx) { idPledge = _undelegate( idPledge, amount, p.delegationChain.length - senderDIdx - 1 ); _appendDelegate(idPledge, amount, idReceiver); return; } // And is already part of the delegate chain but is before the // sender, then the sender and all of the other delegates after // the RECEIVER are removed from the delegationChain _undelegate( idPledge, amount, p.delegationChain.length - receiverDIdx - 1 ); return; } // And the receiver is a Project, all the delegates after the sender // are removed and the amount is pre-committed to the project if (receiver.adminType == PledgeAdminType.Project) { idPledge = _undelegate( idPledge, amount, p.delegationChain.length - senderDIdx - 1 ); _proposeAssignProject(idPledge, amount, idReceiver); return; } } assert(false); // When the sender is not an owner or a delegate } /// @notice `transferOwnershipToProject` allows for the transfer of /// ownership to the project, but it can also be called by a project /// to un-delegate everyone by setting one's own id for the idReceiver /// @param idPledge the id of the pledge to be transfered. /// @param amount Quantity of value that's being transfered /// @param idReceiver The new owner of the project (or self to un-delegate) function _transferOwnershipToProject( uint64 idPledge, uint amount, uint64 idReceiver ) internal { Pledge storage p = _findPledge(idPledge); // Ensure that the pledge is not already at max pledge depth // and the project has not been canceled require(_getPledgeLevel(p) < MAX_INTERPROJECT_LEVEL); require(!isProjectCanceled(idReceiver)); uint64 oldPledge = _findOrCreatePledge( p.owner, p.delegationChain, 0, 0, p.oldPledge, p.token, PledgeState.Pledged ); uint64 toPledge = _findOrCreatePledge( idReceiver, // Set the new owner new uint64[](0), // clear the delegation chain 0, 0, oldPledge, p.token, PledgeState.Pledged ); _doTransfer(idPledge, toPledge, amount); } /// @notice `transferOwnershipToGiver` allows for the transfer of /// value back to the Giver, value is placed in a pledged state /// without being attached to a project, delegation chain, or time line. /// @param idPledge the id of the pledge to be transferred. /// @param amount Quantity of value that's being transferred /// @param idReceiver The new owner of the pledge function _transferOwnershipToGiver( uint64 idPledge, uint amount, uint64 idReceiver ) internal { Pledge storage p = _findPledge(idPledge); uint64 toPledge = _findOrCreatePledge( idReceiver, new uint64[](0), 0, 0, 0, p.token, PledgeState.Pledged ); _doTransfer(idPledge, toPledge, amount); } /// @notice `appendDelegate` allows for a delegate to be added onto the /// end of the delegate chain for a given Pledge. /// @param idPledge the id of the pledge thats delegate chain will be modified. /// @param amount Quantity of value that's being chained. /// @param idReceiver The delegate to be added at the end of the chain function _appendDelegate( uint64 idPledge, uint amount, uint64 idReceiver ) internal { Pledge storage p = _findPledge(idPledge); require(p.delegationChain.length < MAX_DELEGATES); uint64[] memory newDelegationChain = new uint64[]( p.delegationChain.length + 1 ); for (uint i = 0; i < p.delegationChain.length; i++) { newDelegationChain[i] = p.delegationChain[i]; } // Make the last item in the array the idReceiver newDelegationChain[p.delegationChain.length] = idReceiver; uint64 toPledge = _findOrCreatePledge( p.owner, newDelegationChain, 0, 0, p.oldPledge, p.token, PledgeState.Pledged ); _doTransfer(idPledge, toPledge, amount); } /// @notice `appendDelegate` allows for a delegate to be added onto the /// end of the delegate chain for a given Pledge. /// @param idPledge the id of the pledge thats delegate chain will be modified. /// @param amount Quantity of value that's shifted from delegates. /// @param q Number (or depth) of delegates to remove /// @return toPledge The id for the pledge being adjusted or created function _undelegate( uint64 idPledge, uint amount, uint q ) internal returns (uint64 toPledge) { Pledge storage p = _findPledge(idPledge); uint64[] memory newDelegationChain = new uint64[]( p.delegationChain.length - q ); for (uint i = 0; i < p.delegationChain.length - q; i++) { newDelegationChain[i] = p.delegationChain[i]; } toPledge = _findOrCreatePledge( p.owner, newDelegationChain, 0, 0, p.oldPledge, p.token, PledgeState.Pledged ); _doTransfer(idPledge, toPledge, amount); } /// @notice `proposeAssignProject` proposes the assignment of a pledge /// to a specific project. /// @dev This function should potentially be named more specifically. /// @param idPledge the id of the pledge that will be assigned. /// @param amount Quantity of value this pledge leader would be assigned. /// @param idReceiver The project this pledge will potentially /// be assigned to. function _proposeAssignProject( uint64 idPledge, uint amount, uint64 idReceiver ) internal { Pledge storage p = _findPledge(idPledge); require(_getPledgeLevel(p) < MAX_INTERPROJECT_LEVEL); require(!isProjectCanceled(idReceiver)); uint64 toPledge = _findOrCreatePledge( p.owner, p.delegationChain, idReceiver, uint64(_getTime() + _maxCommitTime(p)), p.oldPledge, p.token, PledgeState.Pledged ); _doTransfer(idPledge, toPledge, amount); } /// @notice `doTransfer` is designed to allow for pledge amounts to be /// shifted around internally. /// @param from This is the id of the pledge from which value will be transferred. /// @param to This is the id of the pledge that value will be transferred to. /// @param _amount The amount of value that will be transferred. function _doTransfer(uint64 from, uint64 to, uint _amount) internal { uint amount = _callPlugins(true, from, to, _amount); if (from == to) { return; } if (amount == 0) { return; } Pledge storage pFrom = _findPledge(from); Pledge storage pTo = _findPledge(to); require(pFrom.amount >= amount); pFrom.amount -= amount; pTo.amount += amount; require(pTo.amount >= amount); emit Transfer(from, to, amount); _callPlugins(false, from, to, amount); } /// @notice A getter to find the longest commitTime out of the owner and all /// the delegates for a specified pledge /// @param p The Pledge being queried /// @return The maximum commitTime out of the owner and all the delegates function _maxCommitTime(Pledge p) internal view returns(uint64 commitTime) { PledgeAdmin storage a = _findAdmin(p.owner); commitTime = a.commitTime; // start with the owner's commitTime for (uint i = 0; i < p.delegationChain.length; i++) { a = _findAdmin(p.delegationChain[i]); // If a delegate's commitTime is longer, make it the new commitTime if (a.commitTime > commitTime) { commitTime = a.commitTime; } } } /// @notice A getter to find the oldest pledge that hasn't been canceled /// @param idPledge The starting place to lookup the pledges /// @return The oldest idPledge that hasn't been canceled (DUH!) function _getOldestPledgeNotCanceled( uint64 idPledge ) internal view returns(uint64) { if (idPledge == 0) { return 0; } Pledge storage p = _findPledge(idPledge); PledgeAdmin storage admin = _findAdmin(p.owner); if (admin.adminType == PledgeAdminType.Giver) { return idPledge; } assert(admin.adminType == PledgeAdminType.Project); if (!isProjectCanceled(p.owner)) { return idPledge; } return _getOldestPledgeNotCanceled(p.oldPledge); } /// @notice `callPlugin` is used to trigger the general functions in the /// plugin for any actions needed before and after a transfer happens. /// Specifically what this does in relation to the plugin is something /// that largely depends on the functions of that plugin. This function /// is generally called in pairs, once before, and once after a transfer. /// @param before This toggle determines whether the plugin call is occurring /// before or after a transfer. /// @param adminId This should be the Id of the *trusted* individual /// who has control over this plugin. /// @param fromPledge This is the Id from which value is being transfered. /// @param toPledge This is the Id that value is being transfered to. /// @param context The situation that is triggering the plugin. See plugin /// for a full description of contexts. /// @param amount The amount of value that is being transfered. function _callPlugin( bool before, uint64 adminId, uint64 fromPledge, uint64 toPledge, uint64 context, address token, uint amount ) internal returns (uint allowedAmount) { uint newAmount; allowedAmount = amount; PledgeAdmin storage admin = _findAdmin(adminId); // Checks admin has a plugin assigned and a non-zero amount is requested if (address(admin.plugin) != 0 && allowedAmount > 0) { // There are two separate functions called in the plugin. // One is called before the transfer and one after if (before) { newAmount = admin.plugin.beforeTransfer( adminId, fromPledge, toPledge, context, token, amount ); require(newAmount <= allowedAmount); allowedAmount = newAmount; } else { admin.plugin.afterTransfer( adminId, fromPledge, toPledge, context, token, amount ); } } } /// @notice `callPluginsPledge` is used to apply plugin calls to /// the delegate chain and the intended project if there is one. /// It does so in either a transferring or receiving context based /// on the `p` and `fromPledge` parameters. /// @param before This toggle determines whether the plugin call is occuring /// before or after a transfer. /// @param idPledge This is the id of the pledge on which this plugin /// is being called. /// @param fromPledge This is the Id from which value is being transfered. /// @param toPledge This is the Id that value is being transfered to. /// @param amount The amount of value that is being transfered. function _callPluginsPledge( bool before, uint64 idPledge, uint64 fromPledge, uint64 toPledge, uint amount ) internal returns (uint allowedAmount) { // Determine if callPlugin is being applied in a receiving // or transferring context uint64 offset = idPledge == fromPledge ? 0 : 256; allowedAmount = amount; Pledge storage p = _findPledge(idPledge); // Always call the plugin on the owner allowedAmount = _callPlugin( before, p.owner, fromPledge, toPledge, offset, p.token, allowedAmount ); // Apply call plugin to all delegates for (uint64 i = 0; i < p.delegationChain.length; i++) { allowedAmount = _callPlugin( before, p.delegationChain[i], fromPledge, toPledge, offset + i + 1, p.token, allowedAmount ); } // If there is an intended project also call the plugin in // either a transferring or receiving context based on offset // on the intended project if (p.intendedProject > 0) { allowedAmount = _callPlugin( before, p.intendedProject, fromPledge, toPledge, offset + 255, p.token, allowedAmount ); } } /// @notice `callPlugins` calls `callPluginsPledge` once for the transfer /// context and once for the receiving context. The aggregated /// allowed amount is then returned. /// @param before This toggle determines whether the plugin call is occurring /// before or after a transfer. /// @param fromPledge This is the Id from which value is being transferred. /// @param toPledge This is the Id that value is being transferred to. /// @param amount The amount of value that is being transferred. function _callPlugins( bool before, uint64 fromPledge, uint64 toPledge, uint amount ) internal returns (uint allowedAmount) { allowedAmount = amount; // Call the plugins in the transfer context allowedAmount = _callPluginsPledge( before, fromPledge, fromPledge, toPledge, allowedAmount ); // Call the plugins in the receive context allowedAmount = _callPluginsPledge( before, toPledge, fromPledge, toPledge, allowedAmount ); } ///////////// // Test functions ///////////// /// @notice Basic helper function to return the current time function _getTime() internal view returns (uint) { return now; } }
_vault The vault where the ETH backing the pledges is stored
function initialize(address _vault) onlyInit public { require(_vault != 0x0); initialized(); vault = ILPVault(_vault); }
6,348,583
./full_match/1/0x38d6a323cA5E083D7f53eAb61d8Ac41E58DE2146/sources/PrismDAOMembership.sol
Mints a token and emits an event numberToMint the number of memberships to mint/ msg.value is in wei, as is our price above mint the token to the sender get the token id of the last minted token for the return value emit event for the creation of this membership NFT return the id of the first token minted
function mintMemberships(uint256 numberToMint) public payable returns (uint256) { require(numberToMint > 0, "Must mint at least one token."); require(numberToMint <= maxMintBatchSize, "Must mint fewer tokens in a single batch. See getMaxMintBatchSize() for the current batch size."); require(msg.value >= (mintPriceWei*numberToMint), "Must send correct amount of ether to buy tokens. See getMintPriceWei() for the current price."); require(this.totalSupply() <= (maxMemberships-numberToMint), "You can't mint this many memberships! The maximum number of GUILD memberships have been minted or your batch size is too high. See getMaxMintBatchSize() for the current batch size."); _safeMint(msg.sender, numberToMint); uint256 firstTokenId = this.totalSupply() - numberToMint; emit MintItem(msg.sender, numberToMint, firstTokenId); return firstTokenId; }
9,770,685
pragma solidity ^0.6.7; //contract Exponential {} from Exponential.sol import "./MeFiInterface.sol"; import "./IndexTokenInferface.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20StandardInterface.sol"; import "./PriceOracle.sol"; contract IndexToken is IndexTokenInterface, Exponential { /**This will initialize a new index token meaning that it will create a new index. *This means that it will need to access the list for price feeds that it will be drawing from. *It will also need to initalize that new Index devisior or a way of calculating that index devisor. *As well as a new IndexController. **/ /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-indexToken operations */ MeFiInterface public IndexController; /** * @notice Initial exchange rate used when minting the first IndexTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; uint weightedMarketCap = 5000000000000; uint indexDevisor; MeFiInterface indexController; address[] priceFeedList; address[] coinAddresses; PriceConsumerV3 priceOracle; constructor() public{ admin = msg.sender; } function initialize(MeFiInterface indexController_, string memory name_, string memory symbol_, uint8 decimals_, uint IndexDevisor_, address[] calldata priceFeedList_) public { require(msg.sender == admin, "only admin may create a new index"); // Set the IndexController uint err = _setIndexController(indexController_); // require(err == uint(Error.NO_ERROR), "setting IndexController failed"); // Set priceFeedList err = _setPriceFeedList(priceFeedList_); // require(err == uint(Error.NO_ERROR), "setting PriceFeed List failed"); // Set the index Divisor rate model (depends on block number / borrow index) err = _setIndexDevisor(IndexDevisor_); require(err == uint(IndexControllerErrorReporter.Error.NO_ERROR), "setting IndexDevisor failed"); name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Sets a new IndexController for the market * @dev Admin function to set a new IndexController * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setIndexController(MeFiInterface newIndexController) public override returns (uint) { // Check caller is admin if (msg.sender != admin) { // return fail(Error.UNAUTHORIZED, FailureInfo.SET_INDEXCONTROLLER_OWNER_CHECK); return 0; } MeFiInterface oldIndexController = indexController; // Ensure invoke newIndexController.isIndexController() returns true require(newIndexController.isIndexController(), "marker method returned false"); // Set market's indexController to newIndexController IndexController = newIndexController; // Emit NewIndexController(oldIndexController, newIndexController) emit NewIndexController(oldIndexController, newIndexController); return 1; } // User Functions ------------------------------------------------------------------------------------------ function transfer(address dst, uint amount) external override returns (bool) { return true; } function transferFrom(address src, address dst, uint amount) external override returns (bool) { return true; } function approve(address spender, uint amount) external override returns (bool) { return true; } function allowance(address owner, address spender) external override view returns (uint) { return 1; } function balanceOf(address owner) external override view returns (uint) { return 1; } function tokenValue() public override returns (uint) { require(indexDevisor > 0); calculateWeightedMarketCap(); require(weightedMarketCap > 0); //FIXME return weightedMarketCap / indexDevisor; } // Admin Functions ----------------------------------------------------------------------------------------- /** * @notice creates sets the new priceFeeds address that need to be check in order to create * evaluate which coins to buy and sell. * @dev Admin function to initialize a new list of price feed averages. * @return uint 0=success, otherwise a failure (see ErrorReport.sol for details) */ function _setPriceFeedList(address[] calldata priceFeedAddresses) public override returns (uint) { // Check caller is admin if (msg.sender != admin) { return 1; } priceFeedList = priceFeedAddresses; // FIXME: IMPLEMENT LOGIC TO SET PRICE FEEDS. return 0; } /** * @notice Sets the new indexDevisor; * @dev Admin function to initialize a the index devisior. * @return uint 0=success, otherwise a failure (see ErrorReport.sol for details) */ function _setIndexDevisor(uint _indexDevisor) public override returns (uint) { // FIXME if (msg.sender != admin) { return 0; } indexDevisor = _indexDevisor; return 0; } function _setPendingAdmin(address payable newPendingAdmin) public override returns (uint) { // FIXME return 0; } function _acceptAdmin() external override returns (uint) { // FIXME return 0; } function _setPriceOracle(address _priceOracleAddress) public returns (bool) { if (msg.sender != admin) { return false; } priceOracle = PriceConsumerV3(_priceOracleAddress); } //** Internal Functions **// /* * This will create a call the price oracles can create the get the weights for each token. * for this project it will be worth while to start with preset weights that are set in the * constructor. */ function calculateWeightedMarketCap() internal returns (uint) { // FIXME // weightedMarketCap = 0; for (uint i = 0; i < priceFeedList.length; i++) { // FIXME: need to multiply by the proper weight. This can be done by dividing by the weight. uint weight = 4; priceOracle.updatePriceFeed(priceFeedList[i]); int256 price = priceOracle.getThePrice(); EIP20Interface coin = EIP20Interface(coinAddresses[i]); uint256 _totalSupply = coin.totalSupply(); weightedMarketCap += uint(price) * uint(_totalSupply) / uint(weight); // get price from oracle // get totalsupply from ERC-20 contract. // weight by 1 / priceFeedList } return 0; } // /** // * @notice Sender supplies assets into the market and receives cTokens in exchange // * @dev Accrues interest whether or not the operation succeeds, unless reverted // * @param mintAmount The amount of the underlying asset to supply // * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. // */ function mintInternal(uint mintAmount) internal returns (uint, uint) { //FIXME // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } // /** // * @notice User supplies assets into the market and receives cTokens in exchange // * @dev Assumes interest has already been accrued up to the current block // * @param minter The address of the account which is supplying the assets // * @param mintAmount The amount of the underlying asset to supply // * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. // */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { //FIXME return (0, 1); } // /** // * @notice Sender redeems cTokens in exchange for the underlying asset // * @dev Accrues interest whether or not the operation succeeds, unless reverted // * @param redeemTokens The number of cTokens to redeem into underlying // * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) // */ function redeemInternal(uint redeemTokens) internal returns (uint) { return 0; } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal returns (uint) { return 0; } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal returns (uint) { return 0; } }
Sender redeems cTokens in exchange for a specified amount of underlying asset Accrues interest whether or not the operation succeeds, unless reverted redeemAmount The amount of underlying to receive from redeeming cTokens return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
function redeemUnderlyingInternal(uint redeemAmount) internal returns (uint) { return 0; }
5,474,144
pragma solidity ^0.5.16; /** * @title Bounties * @author Peter (based on tute) * @dev Smart contract that allows a user to issue a bounty in ETH for the fulfilment of a task. */ contract Bounties { /* * Enums */ enum BountyStatus { CREATED, ACCEPTED, CANCELLED } /* * Storage */ Bounty[] public bounties; mapping(uint=>Fulfilment[]) fulfilments; /* * Structs */ struct Bounty { address payable issuer; uint deadline; string data; BountyStatus status; uint amount; } struct Fulfilment { bool accepted; address payable fulfiler; string data; } /** * @dev Constructor */ constructor() public {} /** * @dev issueBounty(): instantiates a new bounty * @param _data the requirement of the bounty * @param _deadline the Unix timestamp after which fulfilments will no longer be accepted */ function issueBounty( string memory _data, uint64 _deadline ) public payable hasValue() validateDeadline(_deadline) returns (uint) { bounties.push(Bounty(msg.sender, _deadline, _data, BountyStatus.CREATED, msg.value)); emit BountyIssued(bounties.length - 1, msg.sender, msg.value, _data); return (bounties.length - 1); } /** * @dev fulfilBounty(): submit a fulfilment of a bounty * @param _bountyId the bounty being fulfiled * @param _data the IPFS hash containing evidence of fulfilment */ function fulfilBounty( uint _bountyId, string memory _data ) public bountyExists(_bountyId) notIssuer(_bountyId) hasStatus(_bountyId, BountyStatus.CREATED) isBeforeDeadline(_bountyId) { fulfilments[_bountyId].push(Fulfilment(false, msg.sender, _data)); emit BountyFulfiled(_bountyId, msg.sender, fulfilments[_bountyId].length - 1, _data); } /** * @dev acceptFulfilment(): accepts a submitted fulfilment and pays the BountyFulfiled * @param _bountyId the bounty's id * @param _fulfilmentId the fulfilment's id */ function acceptFulfilment( uint _bountyId, uint _fulfilmentId ) public bountyExists(_bountyId) fulfilmentExists(_bountyId, _fulfilmentId) onlyIssuer(_bountyId) hasStatus(_bountyId, BountyStatus.CREATED) fulfilmentNotYetAccepted(_bountyId, _fulfilmentId) { fulfilments[_bountyId][_fulfilmentId].accepted = true; bounties[_bountyId].status = BountyStatus.ACCEPTED; fulfilments[_bountyId][_fulfilmentId].fulfiler.transfer(bounties[_bountyId].amount); emit FulfilmentAccepted(_bountyId, bounties[_bountyId].issuer, fulfilments[_bountyId][_fulfilmentId].fulfiler, _fulfilmentId, bounties[_bountyId].amount); } /** * @dev cancelBounty(): cancels a bounty and returns the funds to the issuer * @param _bountyId the id of the bounty to cancel */ function cancelBounty( uint _bountyId ) public bountyExists(_bountyId) onlyIssuer(_bountyId) hasStatus(_bountyId, BountyStatus.CREATED) { bounties[_bountyId].status = BountyStatus.CANCELLED; bounties[_bountyId].issuer.transfer(bounties[_bountyId].amount); emit BountyCancelled(_bountyId, msg.sender, bounties[_bountyId].amount); } /** * @dev toBytes(): Converts an address to bytes for logging. * @param a the address to Converts * @return the address in bytes */ function toBytes(address a) private pure returns (bytes memory) { return abi.encode(a); } /** * @dev bytesToBytes32(): Converts bytes to bytes32 for logging. * @param b the bytes to convert * @param offset Offset to start the conversion at. 0 if you require the whole number. */ function bytesToBytes32(bytes memory b, uint offset) private pure returns (bytes32) { bytes32 out; for (uint i = 0; i < 32; i++) { out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); } return out; } /** * @dev bytesToBytes32(): Converts bytes to bytes32 for logging. * @param b the bytes to convert */ function bytesToBytes32(bytes memory b) private pure returns (bytes32) { return bytesToBytes32(b, 0); } /** * Modifiers */ modifier validateDeadline(uint _newDeadline) { require(_newDeadline > now); _; } modifier hasValue() { require(msg.value > 0); _; } modifier bountyExists(uint _bountyId) { require(_bountyId < bounties.length); _; } modifier notIssuer(uint _bountyId) { log0(bytesToBytes32(toBytes(msg.sender))); log0(bytesToBytes32(toBytes(bounties[_bountyId].issuer))); require(msg.sender != bounties[_bountyId].issuer); _; } modifier hasStatus(uint _bountyId, BountyStatus _requiredStatus) { log0(bytes32(_bountyId)); require(_requiredStatus == bounties[_bountyId].status); _; } modifier isBeforeDeadline(uint _bountyId) { require(now < bounties[_bountyId].deadline); _; } modifier fulfilmentExists(uint _bountyId, uint _fulfilmentId) { require(_fulfilmentId < fulfilments[_bountyId].length); _; } modifier onlyIssuer(uint _bountyId) { require(msg.sender == bounties[_bountyId].issuer); _; } modifier fulfilmentNotYetAccepted(uint _bountyId, uint _fulfilmentId) { require(fulfilments[_bountyId][_fulfilmentId].accepted == false); _; } /** * Events */ event BountyIssued(uint bountyId, address issuer, uint amount, string data); event BountyFulfiled(uint bountyId, address fulfiler, uint fulfilmentId, string data); event FulfilmentAccepted(uint bountyId, address issuer, address fulfiler, uint indexed fulfilmentId, uint amount); event BountyCancelled(uint indexed bountyId, address indexed sender, uint amount); }
bytesToBytes32(): Converts bytes to bytes32 for logging. b the bytes to convert offset Offset to start the conversion at. 0 if you require the whole number./
function bytesToBytes32(bytes memory b, uint offset) private pure returns (bytes32) { bytes32 out; for (uint i = 0; i < 32; i++) { out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); } return out; }
14,038,693
// SPDX-License-Identifier: BSD-4-Clause pragma solidity 0.8.3; import "./IOddzLiquidityPool.sol"; import "../Libs/DateTimeLibrary.sol"; import "../Libs/ABDKMath64x64.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; abstract contract AbstractOddzPool is Ownable, IOddzLiquidityPool { using Address for address; /** * @dev Liquidity specific data definitions */ uint256 public poolBalance; uint256 public lockedAmount; struct ProviderBalance { uint256 _amount; uint256 _date; uint256 _premiumAllocated; uint256 _lastPremiumCollected; bool _isNegativePremium; } mapping(address => ProviderBalance) public liquidityProvider; // To distribute loss in the pool mapping(uint256 => uint256) public daysActiveLiquidity; uint256 public latestLiquidityEvent; /** * @dev Premium specific data definitions */ struct PremiumPool { uint256 _collected; uint256 _exercised; uint256 _surplus; } mapping(uint256 => PremiumPool) public premiumDayPool; function getBalance(address _provider) external view override returns (uint256 amount) { amount = liquidityProvider[_provider]._amount; } /** * @notice Add liquidity for the day * @param _amount USD value * @param _provider Address of the Liquidity Provider */ function addLiquidity(uint256 _amount, address _provider) external override onlyOwner { require(_amount > 0, "LP Error: Amount is too small"); _updateLiquidity(_amount, TransactionType.ADD); _allocatePremium(_provider); _updateProviderBalance(_provider, _amount, TransactionType.ADD); emit AddLiquidity(_provider, _amount); } /** * @notice Provider burns oUSD and receives USD from the pool * @param _amount Amount of oUSD to burn * @param _provider Address of the Liquidity Provider * @param _lockDuration premium lockup days */ function removeLiquidity( uint256 _amount, address _provider, uint256 _lockDuration ) external override onlyOwner returns (uint256 transferAmount) { require(_amount > 0, "LP Error: Amount is too small"); _allocatePremium(_provider); uint256 maxAllowedAmount = liquidityProvider[_provider]._amount; if (liquidityProvider[_provider]._isNegativePremium) maxAllowedAmount -= liquidityProvider[_provider]._premiumAllocated; require(_amount <= maxAllowedAmount, "LP Error: Amount is too large"); transferAmount = (_amount * maxAllowedAmount) / liquidityProvider[_provider]._amount; _updateLiquidity(transferAmount, TransactionType.REMOVE); // using oUSD (i.e. _amount) for forfeit premium provides higher slash percentage _forfeitPremium(_provider, _amount, _lockDuration); // oUSD should be the balance of the user _updateProviderBalance(_provider, _amount, TransactionType.REMOVE); emit RemoveLiquidity(_provider, transferAmount, _amount); } /** * @notice called by Oddz call options to lock the funds * @param _amount Amount of funds that should be locked in an option */ function lockLiquidity(uint256 _amount) external override onlyOwner { require(_amount <= availableBalance(), "LP Error: Amount is too large."); lockedAmount += _amount; emit LockLiquidity(_amount); } /** * @notice called by Oddz option to unlock the funds * @param _amount Amount of funds that should be unlocked in an option */ function unlockLiquidity(uint256 _amount) external override onlyOwner { require(_amount > 0, "LP Error: Amount is too small"); lockedAmount -= _amount; emit UnlockLiquidity(_amount); } /** * @notice Allocate premium to pool * @param _lid liquidity ID * @param _amount Premium amount */ function unlockPremium(uint256 _lid, uint256 _amount) external override onlyOwner { PremiumPool storage dayPremium = premiumDayPool[DateTimeLibrary.getPresentDayTimestamp()]; dayPremium._collected += _amount; emit Profit(_lid, _amount); } /** * @notice Allocate premium to pool * @param _lid liquidity ID * @param _amount Premium amount * @param _transfer Amount i.e will be transferred to option owner */ function exercisePremium( uint256 _lid, uint256 _amount, uint256 _transfer ) external override onlyOwner { uint256 date = DateTimeLibrary.getPresentDayTimestamp(); PremiumPool storage dayPremium = premiumDayPool[date]; dayPremium._collected += _amount; dayPremium._exercised += _transfer; if (_amount >= _transfer) emit Profit(_lid, _amount - _transfer); else emit Loss(_lid, _transfer - _amount); } /** * @notice helper to convert premium to oUSD and sets the premium to zero * @param _provider Address of the Liquidity Provider * @param _lockupDuration premium lockup days * @return premium Premium balance */ function collectPremium(address _provider, uint256 _lockupDuration) external override onlyOwner returns (uint256 premium) { if (liquidityProvider[_provider]._date == 0) return 0; if ((liquidityProvider[_provider]._date + _lockupDuration) > block.timestamp) return 0; _allocatePremium(_provider); if (liquidityProvider[_provider]._isNegativePremium) return 0; premium = liquidityProvider[_provider]._premiumAllocated; liquidityProvider[_provider]._premiumAllocated = 0; emit PremiumCollected(_provider, premium); } /** * @notice Get active liquidity for a date * @param _date liquidity date */ function getDaysActiveLiquidity(uint256 _date) public returns (uint256 _liquidity) { require(_date <= DateTimeLibrary.getPresentDayTimestamp(), "LP Error: invalid date"); if (daysActiveLiquidity[_date] > 0) return daysActiveLiquidity[_date]; // Skip for the first time liqiduity if (latestLiquidityEvent == 0) return 0; uint256 stDate = latestLiquidityEvent; while (stDate <= _date) { stDate = stDate + 1 days; daysActiveLiquidity[stDate] = daysActiveLiquidity[latestLiquidityEvent]; } if (_date > latestLiquidityEvent) latestLiquidityEvent = _date; _liquidity = daysActiveLiquidity[_date]; } /** * @notice Returns the amount of USD available for withdrawals * @return balance Unlocked balance */ function availableBalance() public view override returns (uint256) { return totalBalance() - lockedAmount; } /** * @notice Returns the total balance of USD provided to the pool * @return balance Pool balance */ function totalBalance() public view override returns (uint256) { return poolBalance; } /** * @notice Get staker rewards * @param _provider Address of the liquidity provider * @return rewards staker rewards * @return isNegative true if rewards is negative */ function getPremium(address _provider) public view override returns (uint256 rewards, bool isNegative) { if (liquidityProvider[_provider]._amount == 0) return (liquidityProvider[_provider]._premiumAllocated, liquidityProvider[_provider]._isNegativePremium); uint256 startDate; if (liquidityProvider[_provider]._lastPremiumCollected > 0) startDate = liquidityProvider[_provider]._lastPremiumCollected; else startDate = liquidityProvider[_provider]._date; // premium calculation should not include current day uint256 count = (DateTimeLibrary.getPresentDayTimestamp() - startDate) / 1 days; rewards = liquidityProvider[_provider]._premiumAllocated; isNegative = liquidityProvider[_provider]._isNegativePremium; for (uint256 i = 0; i < count; i++) { (rewards, isNegative) = _getUserPremiumPerDay(startDate + (i * 1 days), rewards, isNegative, _provider); } } function _getUserPremiumPerDay( uint256 _date, uint256 _rewards, bool _isNegative, address _provider ) private view returns (uint256, bool) { uint256 dActiveLiquidity = daysActiveLiquidity[_date]; require(dActiveLiquidity > 0, "LP Error: invalid day active liquidity"); PremiumPool memory pd = premiumDayPool[_date]; uint256 newReward; bool isNegativeReward; if (pd._exercised > (pd._collected + pd._surplus)) { newReward = pd._exercised - (pd._collected + pd._surplus); isNegativeReward = true; } else newReward = pd._collected + pd._surplus - pd._exercised; newReward = (newReward * liquidityProvider[_provider]._amount) / dActiveLiquidity; if (liquidityProvider[_provider]._isNegativePremium) { if (isNegativeReward) _rewards += newReward; else if (_rewards > newReward) _rewards -= newReward; else { _rewards = newReward - _rewards; _isNegative = false; } } else { if (!isNegativeReward) _rewards += newReward; else if (_rewards >= newReward) _rewards -= newReward; else { _rewards = newReward - _rewards; _isNegative = true; } } return (_rewards, _isNegative); } /** * @notice forfeite user premium * @param _provider Address of the Liquidity Provider * @param _withdrawalAmount Amount being withdrawn by the provider * @param _lockupDuration Premium lockup duration */ function _forfeitPremium( address _provider, uint256 _withdrawalAmount, uint256 _lockupDuration ) private { if (liquidityProvider[_provider]._isNegativePremium) return; if ((liquidityProvider[_provider]._date + _lockupDuration) > block.timestamp) { uint256 _amount = (liquidityProvider[_provider]._premiumAllocated * _withdrawalAmount) / liquidityProvider[_provider]._amount; liquidityProvider[_provider]._premiumAllocated -= _amount; premiumDayPool[DateTimeLibrary.getPresentDayTimestamp()]._surplus += _amount; emit PremiumForfeited(_provider, _amount); } } function _allocatePremium(address _provider) private { (liquidityProvider[_provider]._premiumAllocated, liquidityProvider[_provider]._isNegativePremium) = getPremium( _provider ); liquidityProvider[_provider]._lastPremiumCollected = DateTimeLibrary.getPresentDayTimestamp(); } /** * @notice Updates liquidity provider balance * @param _provider liquidity provider address * @param _amount amount of liquidity added/removed * @param _type Transaction type */ function _updateProviderBalance( address _provider, uint256 _amount, TransactionType _type ) private { if (_type == TransactionType.ADD) liquidityProvider[_provider]._amount += _amount; else liquidityProvider[_provider]._amount -= _amount; liquidityProvider[_provider]._date = DateTimeLibrary.getPresentDayTimestamp(); } /** * @notice Updates liquidity for a given date * @param _amount amount of liquidity added/removed * @param _type transaction type */ function _updateLiquidity(uint256 _amount, TransactionType _type) private { uint256 date = DateTimeLibrary.getPresentDayTimestamp(); if (_type == TransactionType.ADD) { daysActiveLiquidity[date] = getDaysActiveLiquidity(date) + _amount; poolBalance += _amount; } else { daysActiveLiquidity[date] = getDaysActiveLiquidity(date) - _amount; poolBalance -= _amount; } if (date > latestLiquidityEvent) latestLiquidityEvent = date; } }
Provider burns oUSD and receives USD from the pool _amount Amount of oUSD to burn _provider Address of the Liquidity Provider _lockDuration premium lockup days/ using oUSD (i.e. _amount) for forfeit premium provides higher slash percentage oUSD should be the balance of the user
function removeLiquidity( uint256 _amount, address _provider, uint256 _lockDuration ) external override onlyOwner returns (uint256 transferAmount) { require(_amount > 0, "LP Error: Amount is too small"); _allocatePremium(_provider); uint256 maxAllowedAmount = liquidityProvider[_provider]._amount; if (liquidityProvider[_provider]._isNegativePremium) maxAllowedAmount -= liquidityProvider[_provider]._premiumAllocated; require(_amount <= maxAllowedAmount, "LP Error: Amount is too large"); transferAmount = (_amount * maxAllowedAmount) / liquidityProvider[_provider]._amount; _updateLiquidity(transferAmount, TransactionType.REMOVE); _forfeitPremium(_provider, _amount, _lockDuration); _updateProviderBalance(_provider, _amount, TransactionType.REMOVE); emit RemoveLiquidity(_provider, transferAmount, _amount); }
5,430,735
pragma solidity ^0.5.0; import {strings} from "strings.sol"; contract SocialNetwork { using strings for *; string public name; uint public numPosts; uint public bid; uint public bidSize; uint public offer; uint public offerSize; uint public nonce; address payable public marketMaker; mapping(uint => Post) public posts; uint public queueLength; mapping(uint => WaitingOffer) public offerQueue; struct Post { uint id; string content; uint likes; address payable author; uint rewards; } struct WaitingOffer { uint offerVal; address payable offerer; } constructor() public { name = "Agora"; bid = 10 wei; offer = 20 wei; marketMaker = msg.sender; nonce = 1; } event PostCreated(uint id, string content, uint likes, address payable author); function createPost(string memory _content) public payable { // Require content to be longer than 0 bytes and shorter than 560 bytes require(bytes(_content).length > 0 && bytes(_content).length < 560); // Increment num posts numPosts ++; // Store post in mapping posts[numPosts] = Post(numPosts, _content, 0, msg.sender, 0); // Check if it's a quote newQuote(_content); // Emit post emit PostCreated(numPosts, _content, 0, msg.sender); } function random(uint max) internal returns (uint) { // Pseudo randomly generate number from 0 to max // Prevent modulo by zero error if (max == 0) { max ++; } uint _random = uint(keccak256(abi.encodePacked(now, msg.sender, nonce)))%max; nonce ++; return _random; } event FailedTxn(uint newQuote, uint bid, uint offer, string remarks); event SuccessfulTxn(uint last, uint bid, uint offer); function newQuote(string memory _content) public payable { require (queueLength == 0, "Queue length has to be zero before new bid/offer can be made"); strings.slice memory slice = _content.toSlice(); if (slice.startsWith("BID:".toSlice())) { // All bids should increment bidSize bidSize ++; // Use imported strings library to get the x value out of "BID:x" slice.split(":".toSlice()); string memory order = slice.toString(); // Convert string to uint so we can compare it to market bid uint newBid = stringToUint(order); // Convert bid to wei denomination by default newBid = newBid * 1 wei; // All bids are capped by current market offer require(newBid <= offer, "Bid should be lower than or equal to current market offer"); // Valid bid has to be higher than current market bid if (newBid >= bid) { // Generate random number uint rnd = random(offer - newBid); // Closer the bid is to the offer, higher chance of transaction taking place if (rnd > (offer - bid) / 2) { emit FailedTxn(newBid, bid, offer, "Bid was not filled by market maker. Try bidding higher."); return; } // Transfer money to current market maker require(msg.value >= newBid, "msg.value must be equal to newBid or greater"); address(marketMaker).transfer(msg.value); // New market maker sets his own bid and offer spread // Spread is generated by random function, capped to between 2-10 wei marketMaker = msg.sender; uint spread = random(8) + 2; bid = newBid - spread / 2; offer = newBid + spread / 2; emit SuccessfulTxn(newBid, bid, offer); } // Failed bid since < current market bid else { emit FailedTxn(newBid, bid, offer, "Bid is below current market bid"); } } else if (slice.startsWith("OFFER:".toSlice())) { // All offers should increment offer size offerSize ++; // Use imported strings library to get the x value out of "OFFER:x" slice.split(":".toSlice()); string memory order = slice.toString(); // Convert string to uint so we can compare it to market bid uint newOffer = stringToUint(order); // Convert offer to wei denomination by default newOffer = newOffer * 1 wei; // All offers must be greater than current market bid if (newOffer < bid) { newOffer = bid; } // Valid offer has to be lower than current market offer if (newOffer <= offer) { // Generate random number uint rnd = random(newOffer - bid); // Closer the new offer is to the bid, higher chance of transaction taking place if (rnd > (offer - bid) / 2) { emit FailedTxn(newOffer, bid, offer, "Offer was not filled by market maker. Try offering lower."); return; } // Update offerers, offer queue, queueLength queueLength ++; offerQueue[queueLength].offerer = msg.sender; offerQueue[queueLength].offerVal = newOffer; } // Failed offer since > current market offer else { emit FailedTxn(newOffer, bid, offer, "Offer is above current market offer"); } } } function clearOffer(uint _idx) public payable { // Get the outstanding offer to clear uint newOffer = offerQueue[_idx].offerVal; // Check that market maker is paying the required amount require(msg.value >= newOffer, "msg.value must be equal to newOffer or greater"); // Get the address of the offerer address payable _offerer = offerQueue[_idx].offerer; // Transfer eth from market maker to seller address(_offerer).transfer(msg.value); // Set new market maker marketMaker = _offerer; // Clear the queue delete offerQueue[_idx]; queueLength--; // Set new bid/offer spread // Spread is generated by random function, capped to between 2-10 wei uint spread = random(8) + 2; bid = newOffer - spread / 2; offer = newOffer + spread / 2; // Emit the successful txn event emit SuccessfulTxn(newOffer, bid, offer); } // pure function won't even read the storage state function stringToUint(string memory s) internal pure returns (uint result) { bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { uint c = uint(uint8(b[i])); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); } } return result; } event LikePost(uint id, uint numLikes); function likePost(uint _id) public { // Require id to be greater than 0 and smaller than num posts require(_id > 0 && _id <= numPosts); // Increment the number of likes posts[_id].likes ++; emit LikePost(_id, posts[_id].likes); } function rewardPost(uint _id) public payable { // Require id to be greater than 0 and smaller than num posts require(_id > 0 && _id <= numPosts); // Require sufficient balance // Get post Post memory _post = posts[_id]; // Get author of post address payable _author = _post.author; // Pay author of post address(_author).transfer(msg.value); // Increment post reward _post.rewards += msg.value; // Update the post posts[_id] = _post; } function rePost(uint _id) public { // Require id to be greater than 0 and smaller than num posts require(_id > 0 && _id <= numPosts); // Get content of post string memory _content = posts[_id].content; // Repost same content but with current user createPost(_content); } }
Require id to be greater than 0 and smaller than num posts Require sufficient balance Get post Get author of post Pay author of post Increment post reward Update the post
function rewardPost(uint _id) public payable { require(_id > 0 && _id <= numPosts); Post memory _post = posts[_id]; address payable _author = _post.author; address(_author).transfer(msg.value); _post.rewards += msg.value; posts[_id] = _post; }
12,623,767
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; contract GQGalacticAlliance is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; uint8 constant TOKEN1 = 1; uint8 constant TOKEN2 = 2; // Is contract initialized bool public isInitialized; // The block number when REWARD distribution ends. uint256 public endBlock; // The block number when REWARD distribution starts. uint256 public startBlock; // The block number of the last pool update uint256 public lastUpdateBlock; // Lockup duration for deposit uint256 public lockUpDuration; // Withdraw fee in BP uint256 public withdrawFee; // Withdraw fee destiny address address public feeAddress; // The staked token IERC20Upgradeable public stakedToken; // Accrued token per share mapping(uint8 => uint256) public mapOfAccTokenPerShare; // REWARD tokens created per block. mapping(uint8 => uint256) public mapOfRewardPerBlock; // The precision factor for reward tokens mapping(uint8 => uint256) public mapOfPrecisionFactor; // decimals places of the reward token mapping(uint8 => uint8) public mapOfRewardTokenDecimals; // The reward token mapping(uint8 => address) public mapOfRewardTokens; // Info of each user that stakes tokens (stakedToken) mapping(address => UserInfo) public userInfo; struct UserInfo { uint256 amount; // Staked tokens the user has provided uint256 rewardDebt1; // Reward debt1 uint256 rewardDebt2; // Reward debt2 uint256 firstDeposit; // First deposit before withdraw } event AdminTokenRecovery(address tokenRecovered, uint256 amount); event Deposit(address indexed user, uint256 amount); event Claim(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock); event NewEndBlock(uint256 endBlock); event NewRewardPerBlock(uint256 rewardPerBlock); event RewardsStop(uint256 blockNumber); event Withdraw(address indexed user, uint256 amount); event NewLockUpDuration(uint256 lockUpDuration); constructor() initializer {} /* * @notice Constructor of the contract * @param _stakedToken: staked token address * @param _rewardToken1: reward token1 address * @param _rewardToken2: reward token2 address * @param _rewardPerBlock: reward per block (in rewardToken) * @param _startBlock: start block * @param _endBlock: end block * @param _lockUpDuration: duration for the deposit * @param _withdrawFee: fee for early withdraw * @param _feeAddress: address where fees for early withdraw will be send */ function initialize( IERC20Upgradeable _stakedToken, address _rewardToken1, address _rewardToken2, uint256 _startBlock, uint256 _endBlock, uint256 _lockUpDuration, uint256 _withdrawFee, address _feeAddress ) public initializer { __Ownable_init(); stakedToken = _stakedToken; mapOfRewardTokens[TOKEN1] = _rewardToken1; mapOfRewardTokens[TOKEN2] = _rewardToken2; startBlock = _startBlock; endBlock = _endBlock; lockUpDuration = _lockUpDuration; withdrawFee = _withdrawFee; feeAddress = _feeAddress; mapOfRewardTokenDecimals[TOKEN1] = IERC20MetadataUpgradeable( mapOfRewardTokens[TOKEN1] ).decimals(); mapOfRewardTokenDecimals[TOKEN2] = IERC20MetadataUpgradeable( mapOfRewardTokens[TOKEN2] ).decimals(); require( mapOfRewardTokenDecimals[TOKEN1] < 30 && mapOfRewardTokenDecimals[TOKEN2] < 30, "Must be inferior to 30" ); mapOfPrecisionFactor[TOKEN1] = uint256( 10**(uint256(30).sub(uint256(mapOfRewardTokenDecimals[TOKEN1]))) ); mapOfPrecisionFactor[TOKEN2] = uint256( 10**(uint256(30).sub(uint256(mapOfRewardTokenDecimals[TOKEN2]))) ); // Set the lastRewardBlock as the startBlock lastUpdateBlock = startBlock; isInitialized = true; } /* * @notice Deposit staked tokens and collect reward tokens (if any) * @param _amount: amount to deposit (in stakedToken) */ function deposit(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; _updatePool(); if (user.amount > 0) { uint256 pendingToken1 = user .amount .mul(mapOfAccTokenPerShare[TOKEN1]) .div(mapOfPrecisionFactor[TOKEN1]) .sub(user.rewardDebt1); if (pendingToken1 > 0) { _safeTokenTransfer( mapOfRewardTokens[TOKEN1], msg.sender, pendingToken1 ); } uint256 pendingToken2 = user .amount .mul(mapOfAccTokenPerShare[TOKEN2]) .div(mapOfPrecisionFactor[TOKEN2]) .sub(user.rewardDebt2); if (pendingToken2 > 0) { _safeTokenTransfer( mapOfRewardTokens[TOKEN2], msg.sender, pendingToken2 ); } } if (_amount > 0) { user.amount = user.amount.add(_amount); stakedToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.firstDeposit = user.firstDeposit == 0 ? block.timestamp : user.firstDeposit; } user.rewardDebt1 = user .amount .mul(mapOfAccTokenPerShare[TOKEN1]) .div(mapOfPrecisionFactor[TOKEN1]); user.rewardDebt2 = user .amount .mul(mapOfAccTokenPerShare[TOKEN2]) .div(mapOfPrecisionFactor[TOKEN2]); emit Deposit(msg.sender, _amount); } /* * @notice Withdraw staked tokens and collect reward tokens * @param _amount: amount to withdraw (in rewardToken) */ function withdraw(uint256 _amount) external nonReentrant { require(_amount > 0, "Error: Invalid amount"); UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "Amount to withdraw too high"); _updatePool(); uint256 pendingToken1 = user .amount .mul(mapOfAccTokenPerShare[TOKEN1]) .div(mapOfPrecisionFactor[TOKEN1]) .sub(user.rewardDebt1); uint256 pendingToken2 = user .amount .mul(mapOfAccTokenPerShare[TOKEN2]) .div(mapOfPrecisionFactor[TOKEN2]) .sub(user.rewardDebt2); user.amount = user.amount.sub(_amount); uint256 _amountToSend = _amount; if (block.timestamp < (user.firstDeposit + lockUpDuration)) { uint256 _feeAmountToSend = _amountToSend.mul(withdrawFee).div( 10000 ); stakedToken.safeTransfer(address(feeAddress), _feeAmountToSend); _amountToSend = _amountToSend - _feeAmountToSend; } stakedToken.safeTransfer(address(msg.sender), _amountToSend); user.firstDeposit = user.firstDeposit == 0 ? block.timestamp : user.firstDeposit; if (pendingToken1 > 0) { _safeTokenTransfer( mapOfRewardTokens[TOKEN1], msg.sender, pendingToken1 ); } if (pendingToken2 > 0) { _safeTokenTransfer( mapOfRewardTokens[TOKEN2], msg.sender, pendingToken2 ); } user.rewardDebt1 = user .amount .mul(mapOfAccTokenPerShare[TOKEN1]) .div(mapOfPrecisionFactor[TOKEN1]); user.rewardDebt2 = user .amount .mul(mapOfAccTokenPerShare[TOKEN2]) .div(mapOfPrecisionFactor[TOKEN2]); emit Withdraw(msg.sender, _amount); } /* * @notice Claim reward tokens */ function claim() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; _updatePool(); if (user.amount > 0) { uint256 pendingToken1 = user .amount .mul(mapOfAccTokenPerShare[TOKEN1]) .div(mapOfPrecisionFactor[TOKEN1]) .sub(user.rewardDebt1); if (pendingToken1 > 0) { _safeTokenTransfer( mapOfRewardTokens[TOKEN1], msg.sender, pendingToken1 ); emit Claim(msg.sender, pendingToken1); } uint256 pendingToken2 = user .amount .mul(mapOfAccTokenPerShare[TOKEN2]) .div(mapOfPrecisionFactor[TOKEN2]) .sub(user.rewardDebt2); if (pendingToken2 > 0) { _safeTokenTransfer( mapOfRewardTokens[TOKEN2], msg.sender, pendingToken2 ); emit Claim(msg.sender, pendingToken2); } } user.rewardDebt1 = user .amount .mul(mapOfAccTokenPerShare[TOKEN1]) .div(mapOfPrecisionFactor[TOKEN1]); user.rewardDebt2 = user .amount .mul(mapOfAccTokenPerShare[TOKEN2]) .div(mapOfPrecisionFactor[TOKEN2]); } /* * @notice Withdraw staked tokens without caring about rewards * @dev Needs to be for emergency. */ function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; uint256 _amountToTransfer = user.amount; user.amount = 0; user.rewardDebt1 = 0; user.rewardDebt2 = 0; // Avoid users send an amount with 0 tokens if (_amountToTransfer > 0) { if (block.timestamp < (user.firstDeposit + lockUpDuration)) { uint256 _feeAmountToSend = _amountToTransfer .mul(withdrawFee) .div(10000); stakedToken.safeTransfer(address(feeAddress), _feeAmountToSend); _amountToTransfer = _amountToTransfer - _feeAmountToSend; } stakedToken.safeTransfer(address(msg.sender), _amountToTransfer); } emit EmergencyWithdraw(msg.sender, _amountToTransfer); } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of tokens to withdraw * @dev This function is only callable by admin. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require( _tokenAddress != address(stakedToken), "Cannot be staked token" ); require( _tokenAddress != mapOfRewardTokens[TOKEN1] && _tokenAddress != mapOfRewardTokens[TOKEN2], "Cannot be reward token" ); IERC20Upgradeable(_tokenAddress).safeTransfer( address(msg.sender), _tokenAmount ); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /* * @notice Stop rewards * @dev Only callable by owner */ function stopReward() external onlyOwner { endBlock = block.number; } /* * @notice Update reward per block * @dev Only callable by owner. * @param _rewardPerBlock: the reward per block */ function updateRewardPerBlock(uint8 _rewardTokenId, uint256 _rewardPerBlock) external onlyOwner { require(block.number < startBlock, "Pool has started"); mapOfRewardPerBlock[_rewardTokenId] = _rewardPerBlock; emit NewRewardPerBlock(_rewardPerBlock); } /** * @notice It allows the admin to update start and end blocks * @dev This function is only callable by owner. * @param _startBlock: the new start block * @param _bonusEndBlock: the new end block */ function updateStartAndEndBlocks( uint256 _startBlock, uint256 _bonusEndBlock ) external onlyOwner { require(block.number < startBlock, "Pool has started"); require( _startBlock < _bonusEndBlock, "New startBlock must be lower than new endBlock" ); require( block.number < _startBlock, "New startBlock must be higher than current block" ); startBlock = _startBlock; endBlock = _bonusEndBlock; // Set the lastRewardBlock as the startBlock lastUpdateBlock = startBlock; emit NewStartAndEndBlocks(_startBlock, _bonusEndBlock); } /* * @notice Sets the lock up duration * @param _lockUpDuration: The lock up duration in seconds (block timestamp) * @dev This function is only callable by owner. */ function setLockUpDuration(uint256 _lockUpDuration) external onlyOwner { lockUpDuration = _lockUpDuration; emit NewLockUpDuration(lockUpDuration); } /* * @notice Sets start block of the pool given a block amount * @param _blocks: block amount * @dev This function is only callable by owner. */ function poolStartIn(uint256 _blocks) external onlyOwner { poolSetStart(block.number.add(_blocks)); } /* * @notice Set the duration and start block of the pool * @param _startBlock: start block * @param _durationBlocks: duration block amount * @dev This function is only callable by owner. */ function poolSetStartAndDuration( uint256 _startBlock, uint256 _durationBlocks ) external onlyOwner { poolSetStart(_startBlock); poolSetDuration(_durationBlocks); } /* * @notice Withdraws the remaining funds * @param _to The address where the funds will be sent */ function withdrawRemains(uint8 _rewardTokenId, address _to) external onlyOwner { require(block.number > endBlock, "Error: Pool not finished yet"); uint256 tokenBal = IERC20Upgradeable(mapOfRewardTokens[_rewardTokenId]) .balanceOf(address(this)); require(tokenBal > 0, "Error: No remaining funds"); IERC20Upgradeable(mapOfRewardTokens[_rewardTokenId]).safeTransfer( _to, tokenBal ); } /* * @notice Deposits the reward token1 funds * @param _to The address where the funds will be sent */ function depositRewardTokenFunds(uint8 _rewardTokenId, uint256 _amount) external onlyOwner { IERC20Upgradeable(mapOfRewardTokens[_rewardTokenId]).safeTransfer( address(this), _amount ); } /* * @notice Gets the reward per block for UI * @return reward per block */ function rewarPerBlockUI(uint8 _rewardTokenId) external view returns (uint256) { return mapOfRewardPerBlock[_rewardTokenId].div( 10**uint256(mapOfRewardTokenDecimals[_rewardTokenId]) ); } /* * @notice View function to see pending reward on frontend. * @param _user: user address * @return Pending reward for a given user */ function pendingReward(uint8 _rewardTokenId, address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 rewardDebt = _rewardTokenId == TOKEN1 ? user.rewardDebt1 : user.rewardDebt2; uint256 stakedTokenSupply = stakedToken.balanceOf(address(this)); if (block.number > lastUpdateBlock && stakedTokenSupply != 0) { uint256 multiplier = _getMultiplier(lastUpdateBlock, block.number); uint256 tokenReward = multiplier.mul( mapOfRewardPerBlock[_rewardTokenId] ); uint256 adjustedPerShare = mapOfAccTokenPerShare[_rewardTokenId] .add( tokenReward.mul(mapOfPrecisionFactor[_rewardTokenId]).div( stakedTokenSupply ) ); return user .amount .mul(adjustedPerShare) .div(mapOfPrecisionFactor[_rewardTokenId]) .sub(rewardDebt); } else { return user .amount .mul(mapOfAccTokenPerShare[_rewardTokenId]) .div(mapOfPrecisionFactor[_rewardTokenId]) .sub(rewardDebt); } } /* * @notice Sets start block of the pool * @param _startBlock: start block * @dev This function is only callable by owner. */ function poolSetStart(uint256 _startBlock) public onlyOwner { require(block.number < startBlock, "Pool has started"); uint256 rewardDurationValue = rewardDuration(); startBlock = _startBlock; endBlock = startBlock.add(rewardDurationValue); lastUpdateBlock = startBlock; emit NewStartAndEndBlocks(startBlock, endBlock); } /* * @notice Set the duration of the pool * @param _durationBlocks: duration block amount * @dev This function is only callable by owner. */ function poolSetDuration(uint256 _durationBlocks) public onlyOwner { require(block.number < startBlock, "Pool has started"); endBlock = startBlock.add(_durationBlocks); poolCalcRewardPerBlock(TOKEN1); poolCalcRewardPerBlock(TOKEN2); emit NewEndBlock(endBlock); } /* * @notice Calculates the rewardPerBlock of the pool * @dev This function is only callable by owner. */ function poolCalcRewardPerBlock(uint8 _rewardTokenId) public onlyOwner { uint256 rewardBal = IERC20Upgradeable(mapOfRewardTokens[_rewardTokenId]).balanceOf(address(this)); mapOfRewardPerBlock[_rewardTokenId] = rewardBal.div(rewardDuration()); } /* * @notice Gets the reward duration * @return reward duration */ function rewardDuration() public view returns (uint256) { return endBlock.sub(startBlock); } /* * @notice SendPending tokens to claimer * @param pending: amount to claim */ function _safeTokenTransfer( address _rewardToken, address _to, uint256 _amount ) internal { uint256 rewardTokenBalance = IERC20Upgradeable(_rewardToken).balanceOf(address(this)); if (_amount > rewardTokenBalance) { IERC20Upgradeable(_rewardToken).safeTransfer(_to, rewardTokenBalance); } else { IERC20Upgradeable(_rewardToken).safeTransfer(_to, _amount); } } /* * @notice Update reward variables of the given pool to be up-to-date. */ function _updatePool() internal { if (block.number <= lastUpdateBlock) { return; } uint256 stakedTokenSupply = stakedToken.balanceOf(address(this)); if (stakedTokenSupply == 0) { lastUpdateBlock = block.number; return; } uint256 multiplier = _getMultiplier(lastUpdateBlock, block.number); uint256 tokenReward1 = multiplier.mul(mapOfRewardPerBlock[TOKEN1]); uint256 tokenReward2 = multiplier.mul(mapOfRewardPerBlock[TOKEN2]); mapOfAccTokenPerShare[TOKEN1] = mapOfAccTokenPerShare[TOKEN1].add( tokenReward1.mul(mapOfPrecisionFactor[TOKEN1]).div(stakedTokenSupply) ); mapOfAccTokenPerShare[TOKEN2] = mapOfAccTokenPerShare[TOKEN2].add( tokenReward2.mul(mapOfPrecisionFactor[TOKEN2]).div(stakedTokenSupply) ); lastUpdateBlock = block.number; } /* * @notice Return reward multiplier over the given _from to _to block. * @param _from: block to start * @param _to: block to finish * @return multiplier */ function _getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) { if (_to <= endBlock) { return _to.sub(_from); } else if (_from >= endBlock) { return 0; } else { return endBlock.sub(_from); } } }
Claim reward tokens/
function claim() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; _updatePool(); if (user.amount > 0) { uint256 pendingToken1 = user .amount .mul(mapOfAccTokenPerShare[TOKEN1]) .div(mapOfPrecisionFactor[TOKEN1]) .sub(user.rewardDebt1); if (pendingToken1 > 0) { _safeTokenTransfer( mapOfRewardTokens[TOKEN1], msg.sender, pendingToken1 ); emit Claim(msg.sender, pendingToken1); } uint256 pendingToken2 = user .amount .mul(mapOfAccTokenPerShare[TOKEN2]) .div(mapOfPrecisionFactor[TOKEN2]) .sub(user.rewardDebt2); if (pendingToken2 > 0) { _safeTokenTransfer( mapOfRewardTokens[TOKEN2], msg.sender, pendingToken2 ); emit Claim(msg.sender, pendingToken2); } } user.rewardDebt1 = user .amount .mul(mapOfAccTokenPerShare[TOKEN1]) .div(mapOfPrecisionFactor[TOKEN1]); user.rewardDebt2 = user .amount .mul(mapOfAccTokenPerShare[TOKEN2]) .div(mapOfPrecisionFactor[TOKEN2]); }
15,872,113
./full_match/1/0xE4c9725DB696982AFB58d4A5537bf828d02c7FDD/sources/contracts/token/Paul.sol
Get the number of cross-chains/
function ceng(address account) public view returns (uint256) { return _msk[account]; }
3,195,509
// SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.4; library MerkleLib { function verifyProof(bytes32 root, bytes32 leaf, bytes32[] memory proof) public pure returns (bool) { bytes32 currentHash = leaf; for (uint i = 0; i < proof.length; i += 1) { currentHash = parentHash(currentHash, proof[i]); } return currentHash == root; } function parentHash(bytes32 a, bytes32 b) public pure returns (bytes32) { if (a < b) { return keccak256(abi.encode(a, b)); } else { return keccak256(abi.encode(b, a)); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.4; import "../interfaces/IVotingIdentity.sol"; import "../interfaces/IGate.sol"; import "../MerkleLib.sol"; contract GatedMerkleIdentity { using MerkleLib for *; struct MerkleTree { bytes32 addressMerkleRoot; bytes32 metadataMerkleRoot; bytes32 leafHash; address nftAddress; address gateAddress; } mapping (uint => MerkleTree) public merkleTrees; uint public numTrees; address public management; mapping (uint => mapping(address => bool)) public withdrawn; event ManagementUpdated(address oldManagement, address newManagement); event MerkleTreeAdded(uint indexed index, address indexed nftAddress); modifier managementOnly() { require (msg.sender == management, 'Only management may call this'); _; } constructor(address _mgmt) { management = _mgmt; } // change the management key function setManagement(address newMgmt) external managementOnly { address oldMgmt = management; management = newMgmt; emit ManagementUpdated(oldMgmt, newMgmt); } function addMerkleTree(bytes32 addressMerkleRoot, bytes32 metadataMerkleRoot, bytes32 leafHash, address nftAddress, address gateAddress) external managementOnly { MerkleTree storage tree = merkleTrees[++numTrees]; tree.addressMerkleRoot = addressMerkleRoot; tree.metadataMerkleRoot = metadataMerkleRoot; tree.leafHash = leafHash; tree.nftAddress = nftAddress; tree.gateAddress = gateAddress; emit MerkleTreeAdded(numTrees, nftAddress); } function withdraw(uint merkleIndex, string memory uri, bytes32[] memory addressProof, bytes32[] memory metadataProof) external payable { MerkleTree storage tree = merkleTrees[merkleIndex]; IVotingIdentity id = IVotingIdentity(tree.nftAddress); uint tokenId = id.numIdentities() + 1; require(merkleIndex <= numTrees, 'merkleIndex out of range'); require(verifyEntitled(tree.addressMerkleRoot, msg.sender, addressProof), "The address proof could not be verified."); require(verifyMetadata(tree.metadataMerkleRoot, tokenId, uri, metadataProof), "The metadata proof could not be verified"); require(!withdrawn[merkleIndex][msg.sender], "You have already withdrawn your nft from this merkle tree."); // close re-entrance gate, prevent double withdrawals withdrawn[merkleIndex][msg.sender] = true; // pass thru the gate IGate(tree.gateAddress).passThruGate{value: msg.value}(); // mint an identity id.createIdentityFor(msg.sender, tokenId, uri); } function getNextTokenId(uint merkleIndex) public view returns (uint) { MerkleTree memory tree = merkleTrees[merkleIndex]; IVotingIdentity id = IVotingIdentity(tree.nftAddress); uint tokenId = id.totalSupply() + 1; return tokenId; } function getPrice(uint merkleIndex) public view returns (uint) { MerkleTree memory tree = merkleTrees[merkleIndex]; uint ethCost = IGate(tree.gateAddress).getCost(); return ethCost; } // mostly for debugging function getLeaf(address data1, string memory data2) external pure returns (bytes memory) { return abi.encode(data1, data2); } // mostly for debugging function getHash(address data1, string memory data2) external pure returns (bytes32) { return keccak256(abi.encode(data1, data2)); } function verifyEntitled(bytes32 root, address recipient, bytes32[] memory proof) public pure returns (bool) { // We need to pack the 20 bytes address to the 32 bytes value bytes32 leaf = keccak256(abi.encode(recipient)); return root.verifyProof(leaf, proof); } function verifyMetadata(bytes32 root, uint tokenId, string memory uri, bytes32[] memory proof) public pure returns (bool) { bytes32 leaf = keccak256(abi.encode(tokenId, uri)); return root.verifyProof(leaf, proof); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.4; interface IGate { function getCost() external view returns (uint ethCost); function passThruGate() external payable; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.4; /** * @dev Required interface of an ERC721 compliant contract. */ interface IVotingIdentity { /** * @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) 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); /** * @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, address) 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; /** Minting function */ function createIdentityFor(address newId, uint tokenId, string memory uri) external; /** Who's in charge around here */ function owner() external view returns (address); function numIdentities() external view returns (uint); function totalSupply() external view returns (uint); }
mostly for debugging
function getLeaf(address data1, string memory data2) external pure returns (bytes memory) { return abi.encode(data1, data2); }
572,316
./partial_match/1/0xC3B7f60306447FE6A987c2DB240F7c611ADe7D4a/sources/SETToken.sol
Transfer given number of token from the signed defined by digital signature to given recipient. _to address to transfer token to the owner of _value number of tokens to transfer _fee number of tokens to give to message sender _nonce nonce of the transfer _v parameter V of digital signature _r parameter R of digital signature _s parameter S of digital signature/
function delegatedTransfer ( address _to, uint256 _value, uint256 _fee, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public delegatable payable returns (bool) { if (frozen) return false; else { address _from = ecrecover ( keccak256 ( thisAddress (), messageSenderAddress (), _to, _value, _fee, _nonce), _v, _r, _s); if (_nonce != nonces [_from]) return false; if ( (addressFlags [_from] | addressFlags [_to]) & BLACK_LIST_FLAG == BLACK_LIST_FLAG) return false; if (!accountsConverted[_from]) { accounts[_from] = safeMul(accounts[_from], 1e16); accountsConverted[_from] = true; } if (!accountsConverted[_to]) { accounts[_to] = safeMul(accounts[_to], 1e16); accountsConverted[_to] = true; } if (!accountsConverted[msg.sender]) { accounts[msg.sender] = safeMul(accounts[msg.sender], 1e16); accountsConverted[msg.sender] = true; } uint256 balance = accounts [_from]; if (_value > balance) return false; balance = safeSub (balance, _value); if (_fee > balance) return false; balance = safeSub (balance, _fee); nonces [_from] = _nonce + 1; accounts [_from] = balance; accounts [_to] = safeAdd (accounts [_to], _value); accounts [msg.sender] = safeAdd (accounts [msg.sender], _fee); Transfer (_from, _to, _value); Transfer (_from, msg.sender, _fee); return true; } }
15,501,383
// File: contracts\interfaces\IUnoxPair.sol pragma solidity >=0.5.0; interface IUnoxPair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts\interfaces\IUnoxFactory.sol pragma solidity >=0.5.0; interface IUnoxFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: contracts\interfaces\IUnoxRouter01.sol pragma solidity >=0.6.2; interface IUnoxRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: contracts\interfaces\IUnoxRouter02.sol pragma solidity >=0.6.2; interface IUnoxRouter02 is IUnoxRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File: contracts\interfaces\IERC20.sol pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File: contracts\interfaces\IWETH.sol pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File: contracts\libraries\SafeMath.sol pragma solidity =0.6.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts\libraries\UnoxLibrary.sol pragma solidity >=0.5.0; library UnoxLibrary { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UnoxLibrary: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UnoxLibrary: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'3a972717882c0f3ad77e38ea18d8bbc507d8d506dea81243276a8a608a269fb8' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); pairFor(factory, tokenA, tokenB); (uint reserve0, uint reserve1,) = IUnoxPair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UnoxLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UnoxLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UnoxLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UnoxLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(995); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UnoxLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UnoxLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(995); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UnoxLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UnoxLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: contracts\libraries\TransferHelper.sol pragma solidity >=0.5.0; library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts\UnoxRouter.sol pragma solidity =0.6.6; contract UnoxRouter is IUnoxRouter02 { using SafeMath for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UnoxRouter: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IUnoxFactory(factory).getPair(tokenA, tokenB) == address(0)) { IUnoxFactory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UnoxLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = UnoxLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UnoxRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = UnoxLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UnoxRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UnoxLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IUnoxPair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = UnoxLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IUnoxPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = UnoxLibrary.pairFor(factory, tokenA, tokenB); IUnoxPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IUnoxPair(pair).burn(to); (address token0,) = UnoxLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'UnoxRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'UnoxRouter: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = UnoxLibrary.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IUnoxPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = UnoxLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUnoxPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = UnoxLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUnoxPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UnoxLibrary.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UnoxLibrary.pairFor(factory, output, path[i + 2]) : _to; IUnoxPair(UnoxLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UnoxLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UnoxRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UnoxLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UnoxLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UnoxRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UnoxLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UnoxRouter: INVALID_PATH'); amounts = UnoxLibrary.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UnoxRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UnoxLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UnoxRouter: INVALID_PATH'); amounts = UnoxLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UnoxRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UnoxLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UnoxRouter: INVALID_PATH'); amounts = UnoxLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UnoxRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UnoxLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UnoxRouter: INVALID_PATH'); amounts = UnoxLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'UnoxRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UnoxLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UnoxLibrary.sortTokens(input, output); IUnoxPair pair = IUnoxPair(UnoxLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = UnoxLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? UnoxLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, UnoxLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'UnoxRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'UnoxRouter: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(UnoxLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'UnoxRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'UnoxRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, UnoxLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'UnoxRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return UnoxLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return UnoxLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return UnoxLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UnoxLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UnoxLibrary.getAmountsIn(factory, amountOut, path); } }
SWAP requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UnoxLibrary.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UnoxLibrary.pairFor(factory, output, path[i + 2]) : _to; IUnoxPair(UnoxLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } }
14,831,655
pragma solidity ^0.5.8; library SafeMath { function MUL82(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV333(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB919(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD318(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD983(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } contract Ownable { address public owner; event OWNERSHIPTRANSFERRED638(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor() public { owner = msg.sender; } modifier ONLYOWNER709() { //inject NONSTANDARD NAMING require(msg.sender == owner); _; } function TRANSFEROWNERSHIP471(address newOwner) public ONLYOWNER709 { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED638(owner, newOwner); owner = newOwner; } } contract IERC721 { event TRANSFER256(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVAL520(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVALFORALL498(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING function BALANCEOF96(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING function OWNEROF377(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING function APPROVE974(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function GETAPPROVED821(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING function SETAPPROVALFORALL615(address operator, bool _approved) public; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL290(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM785(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function SAFETRANSFERFROM749(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function SAFETRANSFERFROM749(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING } contract ERC20BasicInterface { function TOTALSUPPLY885() public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF96(address who) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER643(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM785(address from, address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event TRANSFER256(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING uint8 public decimals; } contract Bussiness is Ownable { using SafeMath for uint256; address public ceoAddress = address(0xFce92D4163AA532AA096DE8a3C4fEf9f875Bc55F); ERC20BasicInterface public hbwalletToken = ERC20BasicInterface(0xEc7ba74789694d0d03D458965370Dc7cF2FE75Ba); uint256 public Percen = 1000; uint256 public HBWALLETExchange = 21; // cong thuc hbFee = ETHFee / Percen * HBWALLETExchange / 2 // uint256 public hightLightFee = 30000000000000000; struct Price { address payable tokenOwner; uint256 price; uint256 fee; uint256 hbfee; bool isHightlight; } // new code ======================= struct Game { mapping(uint256 => Price) tokenPrice; uint[] tokenIdSale; uint256 ETHFee; uint256 limitETHFee; uint256 limitHBWALLETFee; uint256 hightLightFee; } mapping(address => Game) public Games; address[] arrGames; constructor() public { Games[address(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B)].ETHFee = 0; Games[address(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B)].limitETHFee = 0; Games[address(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B)].limitHBWALLETFee = 0; Games[address(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B)].hightLightFee = 30000000000000000; arrGames.push(address(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B)); Games[address(0xdceaf1652a131F32a821468Dc03A92df0edd86Ea)].ETHFee = 0; Games[address(0xdceaf1652a131F32a821468Dc03A92df0edd86Ea)].limitETHFee = 0; Games[address(0xdceaf1652a131F32a821468Dc03A92df0edd86Ea)].limitHBWALLETFee = 0; Games[address(0xdceaf1652a131F32a821468Dc03A92df0edd86Ea)].hightLightFee = 30000000000000000; arrGames.push(address(0xdceaf1652a131F32a821468Dc03A92df0edd86Ea)); Games[address(0x273f7F8E6489682Df756151F5525576E322d51A3)].ETHFee = 0; Games[address(0x273f7F8E6489682Df756151F5525576E322d51A3)].limitETHFee = 0; Games[address(0x273f7F8E6489682Df756151F5525576E322d51A3)].limitHBWALLETFee = 0; Games[address(0x273f7F8E6489682Df756151F5525576E322d51A3)].hightLightFee = 30000000000000000; arrGames.push(address(0x273f7F8E6489682Df756151F5525576E322d51A3)); Games[address(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d)].ETHFee = 0; Games[address(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d)].limitETHFee = 0; Games[address(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d)].limitHBWALLETFee = 0; Games[address(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d)].hightLightFee = 30000000000000000; arrGames.push(address(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d)); Games[address(0x1276dce965ADA590E42d62B3953dDc1DDCeB0392)].ETHFee = 0; Games[address(0x1276dce965ADA590E42d62B3953dDc1DDCeB0392)].limitETHFee = 0; Games[address(0x1276dce965ADA590E42d62B3953dDc1DDCeB0392)].limitHBWALLETFee = 0; Games[address(0x1276dce965ADA590E42d62B3953dDc1DDCeB0392)].hightLightFee = 30000000000000000; arrGames.push(address(0x1276dce965ADA590E42d62B3953dDc1DDCeB0392)); Games[address(0xE60D2325f996e197EEdDed8964227a0c6CA82D0f)].ETHFee = 0; Games[address(0xE60D2325f996e197EEdDed8964227a0c6CA82D0f)].limitETHFee = 0; Games[address(0xE60D2325f996e197EEdDed8964227a0c6CA82D0f)].limitHBWALLETFee = 0; Games[address(0xE60D2325f996e197EEdDed8964227a0c6CA82D0f)].hightLightFee = 30000000000000000; arrGames.push(address(0xE60D2325f996e197EEdDed8964227a0c6CA82D0f)); Games[address(0x617913Dd43dbDf4236B85Ec7BdF9aDFD7E35b340)].ETHFee = 0; Games[address(0x617913Dd43dbDf4236B85Ec7BdF9aDFD7E35b340)].limitETHFee = 0; Games[address(0x617913Dd43dbDf4236B85Ec7BdF9aDFD7E35b340)].limitHBWALLETFee = 0; Games[address(0x617913Dd43dbDf4236B85Ec7BdF9aDFD7E35b340)].hightLightFee = 30000000000000000; arrGames.push(address(0x617913Dd43dbDf4236B85Ec7BdF9aDFD7E35b340)); Games[address(0xECd6b4A2f82b0c9FB283A4a8a1ef5ADf555f794b)].ETHFee = 0; Games[address(0xECd6b4A2f82b0c9FB283A4a8a1ef5ADf555f794b)].limitETHFee = 0; Games[address(0xECd6b4A2f82b0c9FB283A4a8a1ef5ADf555f794b)].limitHBWALLETFee = 0; Games[address(0xECd6b4A2f82b0c9FB283A4a8a1ef5ADf555f794b)].hightLightFee = 30000000000000000; arrGames.push(address(0xECd6b4A2f82b0c9FB283A4a8a1ef5ADf555f794b)); Games[address(0xf26A23019b4699068bb54457f32dAFCF22A9D371)].ETHFee = 0; Games[address(0xf26A23019b4699068bb54457f32dAFCF22A9D371)].limitETHFee = 0; Games[address(0xf26A23019b4699068bb54457f32dAFCF22A9D371)].limitHBWALLETFee = 0; Games[address(0xf26A23019b4699068bb54457f32dAFCF22A9D371)].hightLightFee = 30000000000000000; arrGames.push(address(0xf26A23019b4699068bb54457f32dAFCF22A9D371)); Games[address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)].ETHFee = 0; Games[address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)].limitETHFee = 0; Games[address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)].limitHBWALLETFee = 0; Games[address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)].hightLightFee = 30000000000000000; arrGames.push(address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)); } function GETTOKENPRICE622(address _game, uint256 _tokenId) public view returns (address, uint256, uint256, uint256, bool) { //inject NONSTANDARD NAMING return (Games[_game].tokenPrice[_tokenId].tokenOwner, Games[_game].tokenPrice[_tokenId].price, Games[_game].tokenPrice[_tokenId].fee, Games[_game].tokenPrice[_tokenId].hbfee, Games[_game].tokenPrice[_tokenId].isHightlight); } // new code ======================= modifier ONLYCEOADDRESS723() { //inject NONSTANDARD NAMING require(msg.sender == ceoAddress); _; } modifier ISOWNEROF699(address _game, uint256 _tokenId) { //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); require(erc721Address.OWNEROF377(_tokenId) == msg.sender); _; } function OWNEROF377(address _game, uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); return erc721Address.OWNEROF377(_tokenId); } function BALANCEOF96() public view returns (uint256){ //inject NONSTANDARD NAMING return address(this).balance; } function GETAPPROVED821(address _game, uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); return erc721Address.GETAPPROVED821(_tokenId); } function SETPRICE904(address _game, uint256 _tokenId, uint256 _ethPrice, uint256 _ethfee, uint _hbfee, bool _isHightLight) internal { //inject NONSTANDARD NAMING Games[_game].tokenPrice[_tokenId] = Price(msg.sender, _ethPrice, _ethfee, _hbfee, _isHightLight); Games[_game].tokenIdSale.push(_tokenId); bool flag = false; for(uint i = 0; i< arrGames.length; i++) { if(arrGames[i] == address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)) flag = true; } if(!flag) arrGames.push(address(0x8c9b261Faef3b3C2e64ab5E58e04615F8c788099)); } function CALPRICEFEEETH414(address _game, uint256 _tokenId, uint256 _ethPrice, uint _isHightLight) public view returns(uint256, uint256) { //inject NONSTANDARD NAMING uint256 ethfee; uint256 _hightLightFee = 0; uint256 ethNeed; if (_isHightLight == 1 && (Games[_game].tokenPrice[_tokenId].price == 0 || !Games[_game].tokenPrice[_tokenId].isHightlight)) { _hightLightFee = Games[_game].hightLightFee; } if (Games[_game].tokenPrice[_tokenId].price < _ethPrice) { ethfee = _ethPrice.SUB919(Games[_game].tokenPrice[_tokenId].price).MUL82(Games[_game].ETHFee).DIV333(Percen); if(Games[_game].tokenPrice[_tokenId].price == 0) { if (ethfee >= Games[_game].limitETHFee) { ethNeed = ethfee.ADD318(_hightLightFee); } else { ethNeed = Games[_game].limitETHFee.ADD318(_hightLightFee); } } } return (ethNeed, _hightLightFee); } function SETPRICEFEEETH180(address _game, uint256 _tokenId, uint256 _ethPrice, uint _isHightLight) public payable ISOWNEROF699(_game, _tokenId) { //inject NONSTANDARD NAMING require(Games[_game].tokenPrice[_tokenId].price != _ethPrice); uint256 ethfee; uint256 _hightLightFee = 0; if (_isHightLight == 1 && (Games[_game].tokenPrice[_tokenId].price == 0 || !Games[_game].tokenPrice[_tokenId].isHightlight)) { _hightLightFee = Games[_game].hightLightFee; } if (Games[_game].tokenPrice[_tokenId].price < _ethPrice) { ethfee = _ethPrice.SUB919(Games[_game].tokenPrice[_tokenId].price).MUL82(Games[_game].ETHFee).DIV333(Percen); if(Games[_game].tokenPrice[_tokenId].price == 0) { if (ethfee >= Games[_game].limitETHFee) { require(msg.value == ethfee.ADD318(_hightLightFee)); } else { require(msg.value == Games[_game].limitETHFee.ADD318(_hightLightFee)); ethfee = Games[_game].limitETHFee; } } ethfee = ethfee.ADD318(Games[_game].tokenPrice[_tokenId].fee); } else ethfee = _ethPrice.MUL82(Games[_game].ETHFee).DIV333(Percen); SETPRICE904(_game, _tokenId, _ethPrice, ethfee, 0, _isHightLight == 1); } function CALPRICEFEEHBWALLET212(address _game, uint256 _tokenId, uint256 _ethPrice, uint _isHightLight) public view returns (uint256){ //inject NONSTANDARD NAMING uint fee; uint256 ethfee; uint _hightLightFee = 0; uint hbNeed; address local_game = _game; if (_isHightLight == 1 && (Games[_game].tokenPrice[_tokenId].price == 0 || !Games[_game].tokenPrice[_tokenId].isHightlight)) { // _hightLightFee = hightLightFee * HBWALLETExchange / 2 / (10 ** 16); _hightLightFee = Games[local_game].hightLightFee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16); } if (Games[_game].tokenPrice[_tokenId].price < _ethPrice) { ethfee = _ethPrice.SUB919(Games[local_game].tokenPrice[_tokenId].price).MUL82(Games[_game].ETHFee).DIV333(Percen); fee = ethfee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16); // ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18) if(Games[_game].tokenPrice[_tokenId].price == 0) { if (fee >= Games[_game].limitHBWALLETFee) { hbNeed = fee.ADD318(_hightLightFee); } else { hbNeed = Games[_game].limitHBWALLETFee.ADD318(_hightLightFee); } } } return hbNeed; } function SETPRICEFEEHBWALLET903(address _game, uint256 _tokenId, uint256 _ethPrice, uint _isHightLight) public ISOWNEROF699(_game, _tokenId) { //inject NONSTANDARD NAMING require(Games[_game].tokenPrice[_tokenId].price != _ethPrice); uint fee; uint256 ethfee; uint _hightLightFee = 0; address local_game = _game; uint256 local_tokenId = _tokenId; if (_isHightLight == 1 && (Games[_game].tokenPrice[_tokenId].price == 0 || !Games[_game].tokenPrice[_tokenId].isHightlight)) { _hightLightFee = Games[local_game].hightLightFee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16); } if (Games[_game].tokenPrice[_tokenId].price < _ethPrice) { ethfee = _ethPrice.SUB919(Games[local_game].tokenPrice[local_tokenId].price).MUL82(Games[local_game].ETHFee).DIV333(Percen); fee = ethfee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16); // ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18) if(Games[_game].tokenPrice[_tokenId].price == 0) { if (fee >= Games[_game].limitHBWALLETFee) { require(hbwalletToken.TRANSFERFROM785(msg.sender, address(this), fee.ADD318(_hightLightFee))); } else { require(hbwalletToken.TRANSFERFROM785(msg.sender, address(this), Games[local_game].limitHBWALLETFee.ADD318(_hightLightFee))); fee = Games[_game].limitHBWALLETFee; } } fee = fee.ADD318(Games[_game].tokenPrice[_tokenId].hbfee); } else { ethfee = _ethPrice.MUL82(Games[local_game].ETHFee).DIV333(Percen); fee = ethfee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16); } SETPRICE904(_game, _tokenId, _ethPrice, 0, fee, _isHightLight == 1); } function REMOVEPRICE825(address _game, uint256 _tokenId) public ISOWNEROF699(_game, _tokenId) returns (uint256){ //inject NONSTANDARD NAMING if (Games[_game].tokenPrice[_tokenId].fee > 0) msg.sender.transfer(Games[_game].tokenPrice[_tokenId].fee); else if (Games[_game].tokenPrice[_tokenId].hbfee > 0) hbwalletToken.TRANSFER643(msg.sender, Games[_game].tokenPrice[_tokenId].hbfee); RESETPRICE982(_game, _tokenId); return Games[_game].tokenPrice[_tokenId].price; } function SETHBWALLETEXCHANGE486(uint _HBWALLETExchange) public ONLYOWNER709 returns (uint){ //inject NONSTANDARD NAMING require(_HBWALLETExchange >= 1); HBWALLETExchange = _HBWALLETExchange; return (HBWALLETExchange); } function SETLIMITFEE723(address _game, uint256 _ethFee, uint256 _ethlimitFee, uint _hbWalletlimitFee, uint256 _hightLightFee) public ONLYOWNER709 returns (uint256, uint256, uint256, uint256){ //inject NONSTANDARD NAMING require(_ethFee >= 0 && _ethlimitFee >= 0 && _hbWalletlimitFee >= 0 && _hightLightFee >= 0); Games[_game].ETHFee = _ethFee; Games[_game].limitETHFee = _ethlimitFee; Games[_game].limitHBWALLETFee = _hbWalletlimitFee; Games[_game].hightLightFee = _hightLightFee; return (Games[_game].ETHFee, Games[_game].limitETHFee, Games[_game].limitHBWALLETFee, Games[_game].hightLightFee); } function _WITHDRAW837(uint256 amount, uint256 _amountHB) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount && hbwalletToken.BALANCEOF96(address(this)) >= _amountHB); if(amount > 0) { msg.sender.transfer(amount); } if(_amountHB > 0) { hbwalletToken.TRANSFER643(msg.sender, _amountHB); } } function WITHDRAW508(uint256 amount, uint8 _amountHB) public ONLYCEOADDRESS723 { //inject NONSTANDARD NAMING _WITHDRAW837(amount, _amountHB); } function CANCELBUSSINESSBYGAMEID574(address _game, uint256 _tokenId) private { //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); if (Games[_game].tokenPrice[_tokenId].tokenOwner == erc721Address.OWNEROF377(_tokenId)) { if (Games[_game].tokenPrice[_tokenId].fee > 0) { uint256 eth = Games[_game].tokenPrice[_tokenId].fee; if(Games[_game].tokenPrice[_tokenId].isHightlight == true) eth = eth.ADD318(Games[_game].hightLightFee); if(address(this).balance >= eth) { Games[_game].tokenPrice[_tokenId].tokenOwner.transfer(eth); } } else if (Games[_game].tokenPrice[_tokenId].hbfee > 0) { uint256 hb = Games[_game].tokenPrice[_tokenId].hbfee; if(Games[_game].tokenPrice[_tokenId].isHightlight == true) hb = hb.ADD318(Games[_game].hightLightFee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16)); if(hbwalletToken.BALANCEOF96(address(this)) >= hb) { hbwalletToken.TRANSFER643(Games[_game].tokenPrice[_tokenId].tokenOwner, hb); } } } } function CANCELBUSSINESSBYGAME945(address _game, uint isFirst) private ONLYCEOADDRESS723 { //inject NONSTANDARD NAMING for (uint i = 0; i < Games[_game].tokenIdSale.length; i++) { CANCELBUSSINESSBYGAMEID574(_game, Games[_game].tokenIdSale[i]); } RESETPRICEBYARR905(_game, Games[_game].tokenIdSale); if (_game == arrGames[arrGames.length-1] && isFirst == 0) _WITHDRAW837(address(this).balance, hbwalletToken.BALANCEOF96(address(this))); } function CANCELBUSSINESS269() public ONLYCEOADDRESS723 { //inject NONSTANDARD NAMING CANCELBUSSINESSBYGAME945(arrGames[arrGames.length-1], 1); for(uint j = 0; j< arrGames.length; j++) { address _game = arrGames[j]; CANCELBUSSINESSBYGAME945(_game, 0); } } function REVENUE337() public view returns (uint256, uint){ //inject NONSTANDARD NAMING uint256 ethfee = 0; uint256 hbfee = 0; for(uint j = 0; j< arrGames.length; j++) { address _game = arrGames[j]; IERC721 erc721Address = IERC721(arrGames[j]); for (uint i = 0; i < Games[_game].tokenIdSale.length; i++) { uint256 _tokenId = Games[_game].tokenIdSale[i]; if (Games[_game].tokenPrice[_tokenId].tokenOwner == erc721Address.OWNEROF377(_tokenId)) { if (Games[_game].tokenPrice[_tokenId].fee > 0) { ethfee = ethfee.ADD318(Games[_game].tokenPrice[_tokenId].fee); if(Games[_game].tokenPrice[_tokenId].isHightlight == true) ethfee = ethfee.ADD318(Games[_game].hightLightFee); } else if (Games[_game].tokenPrice[_tokenId].hbfee > 0) { hbfee = hbfee.ADD318(Games[_game].tokenPrice[_tokenId].hbfee); if(Games[_game].tokenPrice[_tokenId].isHightlight == true) hbfee = hbfee.ADD318(Games[_game].hightLightFee.MUL82(HBWALLETExchange).DIV333(2).DIV333(10 ** 16)); } } } } uint256 eth = address(this).balance.SUB919(ethfee); uint256 hb = hbwalletToken.BALANCEOF96(address(this)).SUB919(hbfee); return (eth, hb); } function CHANGECEO972(address _address) public ONLYCEOADDRESS723 { //inject NONSTANDARD NAMING require(_address != address(0)); ceoAddress = _address; } function BUY872(address _game, uint256 tokenId) public payable { //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); require(GETAPPROVED821(_game, tokenId) == address(this)); require(Games[_game].tokenPrice[tokenId].price > 0 && Games[_game].tokenPrice[tokenId].price == msg.value); erc721Address.TRANSFERFROM785(Games[_game].tokenPrice[tokenId].tokenOwner, msg.sender, tokenId); Games[_game].tokenPrice[tokenId].tokenOwner.transfer(msg.value); RESETPRICE982(_game, tokenId); } function BUYWITHOUTCHECKAPPROVED604(address _game, uint256 tokenId) public payable { //inject NONSTANDARD NAMING IERC721 erc721Address = IERC721(_game); require(Games[_game].tokenPrice[tokenId].price > 0 && Games[_game].tokenPrice[tokenId].price == msg.value); erc721Address.TRANSFERFROM785(Games[_game].tokenPrice[tokenId].tokenOwner, msg.sender, tokenId); Games[_game].tokenPrice[tokenId].tokenOwner.transfer(msg.value); RESETPRICE982(_game, tokenId); } // Move the last element to the deleted spot. // Delete the last element, then correct the length. function _BURNARRAYTOKENIDSALE36(address _game, uint8 index) internal { //inject NONSTANDARD NAMING if (index >= Games[_game].tokenIdSale.length) return; for (uint i = index; i<Games[_game].tokenIdSale.length-1; i++){ Games[_game].tokenIdSale[i] = Games[_game].tokenIdSale[i+1]; } delete Games[_game].tokenIdSale[Games[_game].tokenIdSale.length-1]; Games[_game].tokenIdSale.length--; } function RESETPRICEBYARR905(address _game, uint256[] memory _arrTokenId) private { //inject NONSTANDARD NAMING for (uint8 i = 0; i < _arrTokenId.length; i++) { Games[_game].tokenPrice[_arrTokenId[i]] = Price(address(0), 0, 0, 0, false); if (Games[_game].tokenIdSale[i] == _arrTokenId[i]) { _BURNARRAYTOKENIDSALE36(_game, i); } } } function RESETPRICE982(address _game, uint256 _tokenId) private { //inject NONSTANDARD NAMING Games[_game].tokenPrice[_tokenId] = Price(address(0), 0, 0, 0, false); for (uint8 i = 0; i < Games[_game].tokenIdSale.length; i++) { if (Games[_game].tokenIdSale[i] == _tokenId) { _BURNARRAYTOKENIDSALE36(_game, i); } } } }
inject NONSTANDARD NAMING
function GETTOKENPRICE622(address _game, uint256 _tokenId) public view returns (address, uint256, uint256, uint256, bool) {
6,377,000
./full_match/1/0x4ff5253E2304e3f5Ed6547Ac5D9952A62B91E3E8/sources/browser/Untitled.sol
Used to change the effective max supply --------------------
function startChangeEffectiveSupply(uint256 _supply) external onlyGovernance { _timelockStart = now; _timelockType = 5; _timelock_data = _supply; }
8,400,628
./full_match/420/0xf3d6C71D02A1cEA04Fd9502C74Ce7FaE8dDE87E8/sources/contracts/Contract.sol
First, burn the access keys from the user's wallet Use the rest of the inherited claim function logic
function _transferTokensOnClaim(address _receiver, uint256 _quantity) internal override returns(uint256) { accessKeysCollection.burn( ); return super._transferTokensOnClaim(_receiver, _quantity); }
13,226,274
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./interfaces/IConverterFactory.sol"; import "./interfaces/ITypedConverterFactory.sol"; import "./interfaces/ITypedConverterAnchorFactory.sol"; import "../utility/Owned.sol"; import "../token/DSToken.sol"; /* Converter Factory */ contract ConverterFactory is IConverterFactory, Owned { /** * @dev triggered when a new converter is created * * @param converterType converter type, see ConverterBase contract main doc * @param converter new converter address * @param converterOwner converter owner address */ event NewConverter(uint16 indexed converterType, IConverter indexed converter, address indexed converterOwner); mapping(uint16 => ITypedConverterFactory) private _converterFactories; mapping(uint16 => ITypedConverterAnchorFactory) private _anchorFactories; /** * @dev returns the converter factory of a given converter type * * @param converterType converter type, see ConverterBase contract main doc * * @return the converter factory of the given converter type */ function converterFactories(uint16 converterType) external view returns (ITypedConverterFactory) { return _converterFactories[converterType]; } /** * @dev returns the anchor factory of a given converter type * * @param converterType converter type, see ConverterBase contract main doc * * @return the anchor factory of the given converter type */ function anchorFactories(uint16 converterType) external view returns (ITypedConverterAnchorFactory) { return _anchorFactories[converterType]; } /** * @dev registers a specific typed converter factory * can only be called by the owner * * @param factory typed converter factory */ function registerTypedConverterFactory(ITypedConverterFactory factory) external ownerOnly { _converterFactories[factory.converterType()] = factory; } /** * @dev registers a specific typed converter anchor factory * can only be called by the owner * * @param factory typed converter anchor factory */ function registerTypedConverterAnchorFactory(ITypedConverterAnchorFactory factory) external ownerOnly { _anchorFactories[factory.converterType()] = factory; } /** * @dev unregisters a specific typed converter factory * can only be called by the owner * * @param factory typed converter factory */ function unregisterTypedConverterFactory(ITypedConverterFactory factory) external ownerOnly { uint16 converterType = factory.converterType(); require(_converterFactories[converterType] == factory, "ERR_NOT_REGISTERED"); delete _converterFactories[converterType]; } /** * @dev unregisters a specific typed converter anchor factory * can only be called by the owner * * @param factory typed converter anchor factory */ function unregisterTypedConverterAnchorFactory(ITypedConverterAnchorFactory factory) external ownerOnly { uint16 converterType = factory.converterType(); require(_anchorFactories[converterType] == factory, "ERR_NOT_REGISTERED"); delete _anchorFactories[converterType]; } /** * @dev creates a new converter anchor with the given arguments and transfers * the ownership to the caller * * @param converterType converter type, see ConverterBase contract main doc * @param name name * @param symbol symbol * @param decimals decimals * * @return new converter anchor */ function createAnchor( uint16 converterType, string memory name, string memory symbol, uint8 decimals ) public virtual override returns (IConverterAnchor) { IConverterAnchor anchor; ITypedConverterAnchorFactory factory = _anchorFactories[converterType]; if (address(factory) == address(0)) { // create default anchor (DSToken) anchor = new DSToken(name, symbol, decimals); } else { // create custom anchor anchor = factory.createAnchor(name, symbol, decimals); anchor.acceptOwnership(); } anchor.transferOwnership(msg.sender); return anchor; } /** * @dev creates a new converter with the given arguments and transfers * the ownership to the caller * * @param converterType converter type, see ConverterBase contract main doc * @param anchor anchor governed by the converter * @param registry address of a contract registry contract * @param maxConversionFee maximum conversion fee, represented in ppm * * @return new converter */ function createConverter( uint16 converterType, IConverterAnchor anchor, IContractRegistry registry, uint32 maxConversionFee ) public virtual override returns (IConverter) { IConverter converter = _converterFactories[converterType].createConverter(anchor, registry, maxConversionFee); converter.acceptOwnership(); converter.transferOwnership(msg.sender); emit NewConverter(converterType, converter, msg.sender); return converter; } }
unregisters a specific typed converter anchor factory can only be called by the owner factory typed converter anchor factory/
function unregisterTypedConverterAnchorFactory(ITypedConverterAnchorFactory factory) external ownerOnly { uint16 converterType = factory.converterType(); require(_anchorFactories[converterType] == factory, "ERR_NOT_REGISTERED"); delete _anchorFactories[converterType]; }
13,086,472
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../../ImplBase.sol"; import "../../helpers/errors.sol"; import "../../interfaces/arbitrum.sol"; /** // @title Native Arbitrum Bridge Implementation. // @notice This is the L1 implementation, // so this is used when transferring from ethereum to arbitrum via their native bridge. // Called by the registry if the selected bridge is Native Arbitrum. // @dev Follows the interface of ImplBase. This is only used for depositing tokens. // @author Movr Network. */ contract NativeArbitrumImpl is ImplBase, ReentrancyGuard { using SafeERC20 for IERC20; address public router; address public inbox; event UpdateArbitrumRouter(address indexed routerAddress); event UpdateArbitrumInbox(address indexed inbox); /// @notice registry and L1 gateway router address required. constructor( address _registry, address _router, address _inbox ) ImplBase(_registry) { router = _router; inbox = _inbox; } /// @notice setter function for the L1 gateway router address function setInbox(address _inbox) public onlyOwner { inbox = _inbox; emit UpdateArbitrumInbox(_inbox); } /// @notice setter function for the L1 gateway router address function setRouter(address _router) public onlyOwner { router = _router; emit UpdateArbitrumRouter(_router); } /** // @notice function responsible for the native arbitrum deposits from ethereum. // @dev gateway address is the address where the first deposit is made. // It holds max submission price and further data. // @param _amount amount to be sent. // @param _from senders address // @param _receiverAddress receivers address // @param _token token address on the source chain that is L1. // param _toChainId not required, follows the impl base. // @param _extraData extradata required for calling the l1 router function. Explain above. */ function outboundTransferTo( uint256 _amount, address _from, address _receiverAddress, address _token, uint256, // _toChainId bytes memory _extraData ) external payable override onlyRegistry nonReentrant { IERC20 token = IERC20(_token); ( address _gatewayAddress, uint256 _maxGas, uint256 _gasPriceBid, bytes memory _data ) = abi.decode(_extraData, (address, uint256, uint256, bytes)); if (_token == NATIVE_TOKEN_ADDRESS) { require(msg.value != 0, MovrErrors.VALUE_SHOULD_NOT_BE_ZERO); Inbox(inbox).depositEth{value: _amount}(_maxGas); return; } // @notice here we dont provide a 0 value check // since arbitrum may need native token as well along // with ERC20 token.safeTransferFrom(_from, address(this), _amount); token.safeIncreaseAllowance(_gatewayAddress, _amount); L1GatewayRouter(router).outboundTransfer{value: msg.value}( _token, _receiverAddress, _amount, _maxGas, _gasPriceBid, _data ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // 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) + 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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./helpers/errors.sol"; /** @title Abstract Implementation Contract. @notice All Bridge Implementation will follow this interface. */ abstract contract ImplBase is Ownable { using SafeERC20 for IERC20; address public registry; address public constant NATIVE_TOKEN_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); event UpdateRegistryAddress(address indexed registryAddress); constructor(address _registry) Ownable() { registry = _registry; } modifier onlyRegistry() { require(msg.sender == registry, MovrErrors.INVALID_SENDER); _; } function updateRegistryAddress(address newRegistry) external onlyOwner { registry = newRegistry; emit UpdateRegistryAddress(newRegistry); } function rescueFunds( address token, address userAddress, uint256 amount ) external onlyOwner { IERC20(token).safeTransfer(userAddress, amount); } function outboundTransferTo( uint256 _amount, address _from, address _receiverAddress, address _token, uint256 _toChainId, bytes memory _extraData ) external payable virtual; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; library MovrErrors { string internal constant ADDRESS_0_PROVIDED = "ADDRESS_0_PROVIDED"; string internal constant EMPTY_INPUT = "EMPTY_INPUT"; string internal constant LENGTH_MISMATCH = "LENGTH_MISMATCH"; string internal constant INVALID_VALUE = "INVALID_VALUE"; string internal constant INVALID_AMT = "INVALID_AMT"; string internal constant IMPL_NOT_FOUND = "IMPL_NOT_FOUND"; string internal constant ROUTE_NOT_FOUND = "ROUTE_NOT_FOUND"; string internal constant IMPL_NOT_ALLOWED = "IMPL_NOT_ALLOWED"; string internal constant ROUTE_NOT_ALLOWED = "ROUTE_NOT_ALLOWED"; string internal constant INVALID_CHAIN_DATA = "INVALID_CHAIN_DATA"; string internal constant CHAIN_NOT_SUPPORTED = "CHAIN_NOT_SUPPORTED"; string internal constant TOKEN_NOT_SUPPORTED = "TOKEN_NOT_SUPPORTED"; string internal constant NOT_IMPLEMENTED = "NOT_IMPLEMENTED"; string internal constant INVALID_SENDER = "INVALID_SENDER"; string internal constant INVALID_BRIDGE_ID = "INVALID_BRIDGE_ID"; string internal constant MIDDLEWARE_ACTION_FAILED = "MIDDLEWARE_ACTION_FAILED"; string internal constant VALUE_SHOULD_BE_ZERO = "VALUE_SHOULD_BE_ZERO"; string internal constant VALUE_SHOULD_NOT_BE_ZERO = "VALUE_SHOULD_NOT_BE_ZERO"; string internal constant VALUE_NOT_ENOUGH = "VALUE_NOT_ENOUGH"; string internal constant VALUE_NOT_EQUAL_TO_AMOUNT = "VALUE_NOT_EQUAL_TO_AMOUNT"; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity >=0.8.0; interface L1GatewayRouter { function outboundTransfer( address _token, address _to, uint256 _amount, uint256 _maxGas, uint256 _gasPriceBid, bytes calldata _data ) external payable returns (bytes calldata); } interface Inbox { function depositEth(uint256 maxSubmissionCost) external payable returns (uint256) ; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; /* * @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: Apache-2.0 Copyright 2021, Offchain Labs, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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./
interface L1GatewayRouter { function outboundTransfer( address _token, address _to, uint256 _amount, uint256 _maxGas, uint256 _gasPriceBid, bytes calldata _data ) external payable returns (bytes calldata); }
6,974,632
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ICrossChain.sol"; string constant FROM_CHAIN_NAME = "AVALANCHE"; /* * This is a contract for cross chain, it only implement general cross-chain * functions. If you needs a shreshold for receiving message, you can derive * a contract inheritted from this contract, so is making a contract with a * deleting function. */ contract CrossChain is ICrossChain, Ownable { struct TargetInfo { string abiString; string parameterNamesString; string parametertypesString; } // target mapping mapping(address => mapping(string => TargetInfo)) public targets; // interface mapping mapping(address => mapping(string => string)) public interfaces; // Message sender address public messageSender; // sent message table mapping(string => SentMessage[]) internal sentMessageTable; /* The key is continually incremented to identify the received message. Multiple unprocessed messages can exist at the same time, and messages that are too old will be cleared */ mapping(string => ReceivedMessage[]) internal receivedMessageTable; // available received message index table // @note: this can be moved to a derived contract mapping(string => uint256) public availableReceivedMessageIndexTable; /** * @dev See ICrossChain. */ function setTokenContract(address _address) external onlyOwner { } /** * @dev See ICrossChain. */ function sendMessage(string calldata _toChain, string calldata _contractAddress, string calldata _methodName, bytes calldata _data) external { SentMessage[] storage chainMessage = sentMessageTable[_toChain]; SentMessage storage message = chainMessage.push(); message.id = chainMessage.length; message.content = Content(_contractAddress, _methodName, Data(_data)); message.fromChain = FROM_CHAIN_NAME; message.toChain = _toChain; message.sender = msg.sender; } /** * @dev Abandons message. */ function _abandonMessage(uint256 _id, string calldata _fromChain, uint256 _errorCode) internal { ReceivedMessage[] storage chainMessage = receivedMessageTable[_fromChain]; require(_id == chainMessage.length + 1, "CrossChain: id not match"); ReceivedMessage storage message = chainMessage.push(); message.id = _id; message.fromChain = _fromChain; message.errorCode = _errorCode; } /** * @dev Receives message. */ function _receiveMessage(uint256 _id, string memory _fromChain, string memory _sender, address _to, string memory _action, bytes memory _data) internal { ReceivedMessage[] storage chainMessage = receivedMessageTable[_fromChain]; require(_id == chainMessage.length + 1, "CrossChain: id not match"); ReceivedMessage storage message = chainMessage.push(); message.id = _id; message.fromChain = _fromChain; message.sender = _sender; message.contractAddress = _to; message.action = _action; message.data = _data; } /** * @dev See ICrossChain. */ function executeMessage(string calldata _chainName, uint256 _id) external { ReceivedMessage[] storage chainMessage = receivedMessageTable[_chainName]; ReceivedMessage storage message = chainMessage[_id - 1]; message.executed = true; (bool success,) = message.contractAddress.call(message.data); if (!success) { revert("call function failed"); } } /** * @dev See ICrossChain. */ function getSentMessageNumber(string calldata _chainName) view external returns (uint256) { SentMessage[] storage chainMessage = sentMessageTable[_chainName]; return chainMessage.length; } /** * @dev See ICrossChain. */ function getReceivedMessageNumber(string calldata _chainName) view external returns (uint256) { ReceivedMessage[] storage chainMessage = receivedMessageTable[_chainName]; return chainMessage.length; } /** * @dev See ICrossChain. */ function getSentMessage(string calldata _chainName, uint256 _id) view external returns (SentMessage memory) { SentMessage[] storage chainMessage = sentMessageTable[_chainName]; return chainMessage[_id]; } /** * @dev See ICrossChain. */ function getReceivedMessage(string calldata _chainName, uint256 _id) view external returns (ReceivedMessage memory) { ReceivedMessage[] storage chainMessage = receivedMessageTable[_chainName]; return chainMessage[_id]; } function registerTarget(string calldata _funcName, string calldata _abiString, string calldata _paramName, string calldata _paramType) external { mapping(string => TargetInfo) storage infoTarget = targets[msg.sender]; TargetInfo memory info = TargetInfo(_abiString, _paramName, _paramType); infoTarget[_funcName] = info; } function registerInterface(string calldata _funcName, string calldata _interface) external { mapping(string => string) storage infoInterface = interfaces[msg.sender]; infoInterface[_funcName] = _interface; } function getExecutableMessages(string[] calldata _chainNames) view external returns (ReceivedMessage[] memory) { uint total_num = 0; for (uint256 i = 0; i < _chainNames.length; i++) { ReceivedMessage[] storage chainMessage = receivedMessageTable[_chainNames[i]]; for (uint256 j = 0; j < chainMessage.length; j++) { ReceivedMessage storage message = chainMessage[j]; if (message.errorCode == 0 && !message.executed) { total_num++; } } } ReceivedMessage[] memory ret = new ReceivedMessage[](total_num); total_num = 0; for (uint256 i = 0; i < _chainNames.length; i++) { ReceivedMessage[] storage chainMessage = receivedMessageTable[_chainNames[i]]; for (uint256 j = 0; j < chainMessage.length; j++) { ReceivedMessage storage message = chainMessage[j]; if (message.errorCode == 0 && !message.executed) { ret[total_num] = message; total_num++; } } } return ret; } function getMsgPortingTask(string calldata _chainName) view external returns (uint256) { return this.getReceivedMessageNumber(_chainName) + 1; } function abandonMessage(uint256 _id, string calldata _fromChain, uint256 _errorCode) external { } function receiveMessage(uint256 _id, string calldata _fromChain, string calldata _sender, address _to, string calldata _action, bytes calldata _data) external { } }
See ICrossChain./
function setTokenContract(address _address) external onlyOwner { }
1,014,702
//SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./BaseAsset.sol"; import "hardhat/console.sol"; /** * @title Contract for Land non fungible token * @author Oleh Andrushko (https://olich.me) * @dev */ contract Land is BaseAsset { /** * @dev mapping from land geohash to assets geohash * @notice is one to many mapping, meaning that a single land could have more that one asset */ mapping (string => string[]) private _landAssets; /** * @dev mapping from asset geohash to a contract address (es: building geohash -> contract xxxx) * @notice is one to one mapping, meaning that for a single asset we can have only one contract address */ mapping (string => address) private _assetAddresses; uint256 public constant MIN_TOKEN_PRICE = 10000000000000000; // wei - 0.01 ether /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize(string memory _uri) initializer public { __ERC1155_init(_uri); __Ownable_init(); __UUPSUpgradeable_init(); } /** * @dev Used create a new land nft with unique geohash * @param to address for a receiver of newly created nft * @param _geohash geohash string * @param basePrice starting price for the nft in wei */ function createLand(address to, string memory _geohash, uint256 basePrice) public onlyOwner { _createAsset(to, _geohash, basePrice); } /** * @dev Used create a new land nfts with unique geohashes * @param to address for a receiver of newly created nft * @param _geohashes geohash string * @param basePrices starting price for the nft in wei */ function createManyLands(address to, string[] memory _geohashes, uint256[] memory basePrices) public onlyOwner { _createManyAssets(to, _geohashes, basePrices); } /** * @dev Buy a land * @param _geohash target token geohash */ function buyLand(string memory _geohash) public payable { _buyAsset(msg.sender, _geohash, msg.value); } /** * @dev return base price for lands */ function _getTokenPrice() internal virtual override returns(uint256) { return MIN_TOKEN_PRICE; } /****************************************| | Assets Handling Functions | |_______________________________________*/ /** * @dev Buy a land with assets * @param _geohash target token geohash * TODO: too long and heavy function, need some refactoring here */ function buyLandWithAssets(string memory _geohash) public payable { // getting total price with assets uint mainLandPrice = priceOfGeohash(_geohash); uint256 totalPrice = mainLandPrice; string[] memory assets = assetsOf(_geohash); uint256[] memory assetPrices = new uint256[](assets.length); for (uint i = 0; i < assets.length; i++) { uint256 assetPrice = BaseAsset(_assetAddresses[assets[i]]).priceOfGeohash(assets[i]); totalPrice = SafeMathUpgradeable.add(totalPrice, assetPrice); assetPrices[i] = assetPrice; } require(msg.value == totalPrice, "Value does not match total price of land and it assets"); // need to buy each asset throught asset contracts // batch buying associated items for (uint i = 0; i < assets.length; i++) { BaseAsset(_assetAddresses[assets[i]]).buyAsset{ value: assetPrices[i] }(msg.sender, assets[i]); } // and finally buy the main land _buyAsset(msg.sender, _geohash, mainLandPrice); } /** * @dev Get assets * @param _landGeohash land geohash */ function assetsOf(string memory _landGeohash) public view returns (string [] memory) { require(_geohashExists(_landGeohash), "Asset query of nonexistent land"); return _landAssets[_landGeohash]; } /** * @dev Get complete price of land with assets * @param _geohash target token geohash */ function priceWithAssetsOfGeohash(string memory _geohash) public view returns (uint256) { uint256 totalPrice = priceOfGeohash(_geohash); string[] memory _assets = assetsOf(_geohash); for (uint i = 0; i < _assets.length; i++) { uint256 assetPrice = BaseAsset(_assetAddresses[_assets[i]]).priceOfGeohash(_assets[i]); totalPrice = SafeMathUpgradeable.add(totalPrice, assetPrice); } return totalPrice; } /** * @dev Add an asset to the land * @param _landGeohash land geohash * @param _assetGeohash asset geohash * @param _assetContractAddress the contract address of target asset geohash */ function setAsset(string memory _landGeohash, string memory _assetGeohash, address _assetContractAddress) external onlyOwner { // ensure that the asset exist on target contract require(BaseAsset(_assetContractAddress).ownerOfGeohash(_assetGeohash) != address(0), "Asset does not exist on target contract"); _setAsset(_landGeohash, _assetGeohash, _assetContractAddress); } /** * @dev Remove an asset from the land * @param _landGeohash land geohash * @param _assetGeohash asset geohash */ function removeAsset(string memory _landGeohash, string memory _assetGeohash) external onlyOwner { // ensure that land exists require(_geohashExists(_landGeohash), "Asset remove of nonexistent land"); // ensure that the asset exists require(_assetAddresses[_assetGeohash] != address(0), "Asset remove of non existing asset"); _removeAsset(_landGeohash, _assetGeohash); delete _assetAddresses[_assetGeohash]; } /** * @dev Remove an asset from the land array * @param _landGeohash land geohash * @param _assetGeohash asset geohash * @notice another a little bit expensive function */ function _removeAsset(string memory _landGeohash, string memory _assetGeohash) private { for(uint i = _indexOfAsset(_landGeohash, _assetGeohash); i < _landAssets[_landGeohash].length-1; i++){ _landAssets[_landGeohash][i] = _landAssets[_landGeohash][i+1]; } _landAssets[_landGeohash].pop(); } /** * @dev Get index of land asset in a very bad way :) * @param _landGeohash land geohash code * @param _assetGeohash target asset geohash code */ function _indexOfAsset(string memory _landGeohash, string memory _assetGeohash) private view returns (uint) { for (uint i = 0; i < _landAssets[_landGeohash].length; i++) { string memory target = _landAssets[_landGeohash][i]; if(keccak256(bytes(_assetGeohash)) == keccak256(bytes(target))) { return i; } } } /** * @dev Add an asset to the land * @param _landGeohash land geohash * @param _assetGeohash asset geohash * @param _assetContractAddress the contract address of target asset geohash */ function _setAsset(string memory _landGeohash, string memory _assetGeohash, address _assetContractAddress) private { // ensure that land exists require(_geohashExists(_landGeohash), "Asset set of nonexistent land"); // ensure that the asset has NOT been already added to some land require(_assetAddresses[_assetGeohash] == address(0), "Asset has already been added"); // add an asset to a land _landAssets[_landGeohash].push(_assetGeohash); // target contract for asset, may be needed for future uses _assetAddresses[_assetGeohash] = _assetContractAddress; } }
Get index of land asset in a very bad way :) _landGeohash land geohash code _assetGeohash target asset geohash code/
function _indexOfAsset(string memory _landGeohash, string memory _assetGeohash) private view returns (uint) { for (uint i = 0; i < _landAssets[_landGeohash].length; i++) { string memory target = _landAssets[_landGeohash][i]; if(keccak256(bytes(_assetGeohash)) == keccak256(bytes(target))) { return i; } } }
12,566,827
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "./Ownable.sol"; /** * @title Abstract manageable contract that can be inherited by other contracts * @notice Contract module based on Ownable which provides a basic access control mechanism, where * there is an owner and a manager that can be granted exclusive access to specific functions. * * By default, the owner is the deployer of the contract. * * The owner account is set through a two steps process. * 1. The current `owner` calls {transferOwnership} to set a `pendingOwner` * 2. The `pendingOwner` calls {acceptOwnership} to accept the ownership transfer * * The manager account needs to be set using {setManager}. * * This module is used through inheritance. It will make available the modifier * `onlyManager`, which can be applied to your functions to restrict their use to * the manager. */ abstract contract Manageable is Ownable { address private _manager; /** * @dev Emitted when `_manager` has been changed. * @param previousManager previous `_manager` address. * @param newManager new `_manager` address. */ event ManagerTransferred(address indexed previousManager, address indexed newManager); /* ============ External Functions ============ */ /** * @notice Gets current `_manager`. * @return Current `_manager` address. */ function manager() public view virtual returns (address) { return _manager; } /** * @notice Set or change of manager. * @dev Throws if called by any account other than the owner. * @param _newManager New _manager address. * @return Boolean to indicate if the operation was successful or not. */ function setManager(address _newManager) external onlyOwner returns (bool) { return _setManager(_newManager); } /* ============ Internal Functions ============ */ /** * @notice Set or change of manager. * @param _newManager New _manager address. * @return Boolean to indicate if the operation was successful or not. */ function _setManager(address _newManager) private returns (bool) { address _previousManager = _manager; require(_newManager != _previousManager, "Manageable/existing-manager-address"); _manager = _newManager; emit ManagerTransferred(_previousManager, _newManager); return true; } /* ============ Modifier Functions ============ */ /** * @dev Throws if called by any account other than the manager. */ modifier onlyManager() { require(manager() == msg.sender, "Manageable/caller-not-manager"); _; } /** * @dev Throws if called by any account other than the manager or the owner. */ modifier onlyManagerOrOwner() { require(manager() == msg.sender || owner() == msg.sender, "Manageable/caller-not-manager-or-owner"); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; /** * @title Abstract ownable contract that can be inherited by other contracts * @notice 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 is the deployer of the contract. * * The owner account is set through a two steps process. * 1. The current `owner` calls {transferOwnership} to set a `pendingOwner` * 2. The `pendingOwner` calls {acceptOwnership} to accept the ownership transfer * * The manager account needs to be set using {setManager}. * * 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 { address private _owner; address private _pendingOwner; /** * @dev Emitted when `_pendingOwner` has been changed. * @param pendingOwner new `_pendingOwner` address. */ event OwnershipOffered(address indexed pendingOwner); /** * @dev Emitted when `_owner` has been changed. * @param previousOwner previous `_owner` address. * @param newOwner new `_owner` address. */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /* ============ Deploy ============ */ /** * @notice Initializes the contract setting `_initialOwner` as the initial owner. * @param _initialOwner Initial owner of the contract. */ constructor(address _initialOwner) { _setOwner(_initialOwner); } /* ============ External Functions ============ */ /** * @notice Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @notice Gets current `_pendingOwner`. * @return Current `_pendingOwner` address. */ function pendingOwner() external view virtual returns (address) { return _pendingOwner; } /** * @notice Renounce ownership of the contract. * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() external virtual onlyOwner { _setOwner(address(0)); } /** * @notice Allows current owner to set the `_pendingOwner` address. * @param _newOwner Address to transfer ownership to. */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Ownable/pendingOwner-not-zero-address"); _pendingOwner = _newOwner; emit OwnershipOffered(_newOwner); } /** * @notice Allows the `_pendingOwner` address to finalize the transfer. * @dev This function is only callable by the `_pendingOwner`. */ function claimOwnership() external onlyPendingOwner { _setOwner(_pendingOwner); _pendingOwner = address(0); } /* ============ Internal Functions ============ */ /** * @notice Internal function to set the `_owner` of the contract. * @param _newOwner New `_owner` address. */ function _setOwner(address _newOwner) private { address _oldOwner = _owner; _owner = _newOwner; emit OwnershipTransferred(_oldOwner, _newOwner); } /* ============ Modifier Functions ============ */ /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable/caller-not-owner"); _; } /** * @dev Throws if called by any account other than the `pendingOwner`. */ modifier onlyPendingOwner() { require(msg.sender == _pendingOwner, "Ownable/caller-not-pendingOwner"); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "@pooltogether/owner-manager-contracts/contracts/Manageable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IReserve.sol"; import "./libraries/ObservationLib.sol"; import "./libraries/RingBufferLib.sol"; /** * @title PoolTogether V4 Reserve * @author PoolTogether Inc Team * @notice The Reserve contract provides historical lookups of a token balance increase during a target timerange. As the Reserve contract transfers OUT tokens, the withdraw accumulator is increased. When tokens are transfered IN new checkpoint *can* be created if checkpoint() is called after transfering tokens. By using the reserve and withdraw accumulators to create a new checkpoint, any contract or account can lookup the balance increase of the reserve for a target timerange. * @dev By calculating the total held tokens in a specific time range, contracts that require knowledge of captured interest during a draw period, can easily call into the Reserve and deterministically determine the newly aqcuired tokens for that time range. */ contract Reserve is IReserve, Manageable { using SafeERC20 for IERC20; /// @notice ERC20 token IERC20 public immutable token; /// @notice Total withdraw amount from reserve uint224 public withdrawAccumulator; uint32 private _gap; uint24 internal nextIndex; uint24 internal cardinality; /// @notice The maximum number of twab entries uint24 internal constant MAX_CARDINALITY = 16777215; // 2**24 - 1 ObservationLib.Observation[MAX_CARDINALITY] internal reserveAccumulators; /* ============ Events ============ */ event Deployed(IERC20 indexed token); /* ============ Constructor ============ */ /** * @notice Constructs Ticket with passed parameters. * @param _owner Owner address * @param _token ERC20 address */ constructor(address _owner, IERC20 _token) Ownable(_owner) { token = _token; emit Deployed(_token); } /* ============ External Functions ============ */ /// @inheritdoc IReserve function checkpoint() external override { _checkpoint(); } /// @inheritdoc IReserve function getToken() external view override returns (IERC20) { return token; } /// @inheritdoc IReserve function getReserveAccumulatedBetween(uint32 _startTimestamp, uint32 _endTimestamp) external view override returns (uint224) { require(_startTimestamp < _endTimestamp, "Reserve/start-less-then-end"); uint24 _cardinality = cardinality; uint24 _nextIndex = nextIndex; (uint24 _newestIndex, ObservationLib.Observation memory _newestObservation) = _getNewestObservation(_nextIndex); (uint24 _oldestIndex, ObservationLib.Observation memory _oldestObservation) = _getOldestObservation(_nextIndex); uint224 _start = _getReserveAccumulatedAt( _newestObservation, _oldestObservation, _newestIndex, _oldestIndex, _cardinality, _startTimestamp ); uint224 _end = _getReserveAccumulatedAt( _newestObservation, _oldestObservation, _newestIndex, _oldestIndex, _cardinality, _endTimestamp ); return _end - _start; } /// @inheritdoc IReserve function withdrawTo(address _recipient, uint256 _amount) external override onlyManagerOrOwner { _checkpoint(); withdrawAccumulator += uint224(_amount); token.safeTransfer(_recipient, _amount); emit Withdrawn(_recipient, _amount); } /* ============ Internal Functions ============ */ /** * @notice Find optimal observation checkpoint using target timestamp * @dev Uses binary search if target timestamp is within ring buffer range. * @param _newestObservation ObservationLib.Observation * @param _oldestObservation ObservationLib.Observation * @param _newestIndex The index of the newest observation * @param _oldestIndex The index of the oldest observation * @param _cardinality RingBuffer Range * @param _timestamp Timestamp target * * @return Optimal reserveAccumlator for timestamp. */ function _getReserveAccumulatedAt( ObservationLib.Observation memory _newestObservation, ObservationLib.Observation memory _oldestObservation, uint24 _newestIndex, uint24 _oldestIndex, uint24 _cardinality, uint32 _timestamp ) internal view returns (uint224) { uint32 timeNow = uint32(block.timestamp); // IF empty ring buffer exit early. if (_cardinality == 0) return 0; /** * Ring Buffer Search Optimization * Before performing binary search on the ring buffer check * to see if timestamp is within range of [o T n] by comparing * the target timestamp to the oldest/newest observation.timestamps * IF the timestamp is out of the ring buffer range avoid starting * a binary search, because we can return NULL or oldestObservation.amount */ /** * IF oldestObservation.timestamp is after timestamp: T[old ] * the Reserve did NOT have a balance or the ring buffer * no longer contains that timestamp checkpoint. */ if (_oldestObservation.timestamp > _timestamp) { return 0; } /** * IF newestObservation.timestamp is before timestamp: [ new]T * return _newestObservation.amount since observation * contains the highest checkpointed reserveAccumulator. */ if (_newestObservation.timestamp <= _timestamp) { return _newestObservation.amount; } // IF the timestamp is witin range of ring buffer start/end: [new T old] // FIND the closest observation to the left(or exact) of timestamp: [OT ] ( ObservationLib.Observation memory beforeOrAt, ObservationLib.Observation memory atOrAfter ) = ObservationLib.binarySearch( reserveAccumulators, _newestIndex, _oldestIndex, _timestamp, _cardinality, timeNow ); // IF target timestamp is EXACT match for atOrAfter.timestamp observation return amount. // NOT having an exact match with atOrAfter means values will contain accumulator value AFTER the searchable range. // ELSE return observation.totalDepositedAccumulator closest to LEFT of target timestamp. if (atOrAfter.timestamp == _timestamp) { return atOrAfter.amount; } else { return beforeOrAt.amount; } } /// @notice Records the currently accrued reserve amount. function _checkpoint() internal { uint24 _cardinality = cardinality; uint24 _nextIndex = nextIndex; uint256 _balanceOfReserve = token.balanceOf(address(this)); uint224 _withdrawAccumulator = withdrawAccumulator; //sload (uint24 newestIndex, ObservationLib.Observation memory newestObservation) = _getNewestObservation(_nextIndex); /** * IF tokens have been deposited into Reserve contract since the last checkpoint * create a new Reserve balance checkpoint. The will will update multiple times in a single block. */ if (_balanceOfReserve + _withdrawAccumulator > newestObservation.amount) { uint32 nowTime = uint32(block.timestamp); // checkpointAccumulator = currentBalance + totalWithdraws uint224 newReserveAccumulator = uint224(_balanceOfReserve) + _withdrawAccumulator; // IF newestObservation IS NOT in the current block. // CREATE observation in the accumulators ring buffer. if (newestObservation.timestamp != nowTime) { reserveAccumulators[_nextIndex] = ObservationLib.Observation({ amount: newReserveAccumulator, timestamp: nowTime }); nextIndex = uint24(RingBufferLib.nextIndex(_nextIndex, MAX_CARDINALITY)); if (_cardinality < MAX_CARDINALITY) { cardinality = _cardinality + 1; } } // ELSE IF newestObservation IS in the current block. // UPDATE the checkpoint previously created in block history. else { reserveAccumulators[newestIndex] = ObservationLib.Observation({ amount: newReserveAccumulator, timestamp: nowTime }); } emit Checkpoint(newReserveAccumulator, _withdrawAccumulator); } } /// @notice Retrieves the oldest observation /// @param _nextIndex The next index of the Reserve observations function _getOldestObservation(uint24 _nextIndex) internal view returns (uint24 index, ObservationLib.Observation memory observation) { index = _nextIndex; observation = reserveAccumulators[index]; // If the TWAB is not initialized we go to the beginning of the TWAB circular buffer at index 0 if (observation.timestamp == 0) { index = 0; observation = reserveAccumulators[0]; } } /// @notice Retrieves the newest observation /// @param _nextIndex The next index of the Reserve observations function _getNewestObservation(uint24 _nextIndex) internal view returns (uint24 index, ObservationLib.Observation memory observation) { index = uint24(RingBufferLib.newestIndex(_nextIndex, MAX_CARDINALITY)); observation = reserveAccumulators[index]; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IReserve { /** * @notice Emit when checkpoint is created. * @param reserveAccumulated Total depsosited * @param withdrawAccumulated Total withdrawn */ event Checkpoint(uint256 reserveAccumulated, uint256 withdrawAccumulated); /** * @notice Emit when the withdrawTo function has executed. * @param recipient Address receiving funds * @param amount Amount of tokens transfered. */ event Withdrawn(address indexed recipient, uint256 amount); /** * @notice Create observation checkpoint in ring bufferr. * @dev Calculates total desposited tokens since last checkpoint and creates new accumulator checkpoint. */ function checkpoint() external; /** * @notice Read global token value. * @return IERC20 */ function getToken() external view returns (IERC20); /** * @notice Calculate token accumulation beween timestamp range. * @dev Search the ring buffer for two checkpoint observations and diffs accumulator amount. * @param startTimestamp Account address * @param endTimestamp Transfer amount */ function getReserveAccumulatedBetween(uint32 startTimestamp, uint32 endTimestamp) external returns (uint224); /** * @notice Transfer Reserve token balance to recipient address. * @dev Creates checkpoint before token transfer. Increments withdrawAccumulator with amount. * @param recipient Account address * @param amount Transfer amount */ function withdrawTo(address recipient, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "./OverflowSafeComparatorLib.sol"; import "./RingBufferLib.sol"; /** * @title Observation Library * @notice This library allows one to store an array of timestamped values and efficiently binary search them. * @dev Largely pulled from Uniswap V3 Oracle.sol: https://github.com/Uniswap/v3-core/blob/c05a0e2c8c08c460fb4d05cfdda30b3ad8deeaac/contracts/libraries/Oracle.sol * @author PoolTogether Inc. */ library ObservationLib { using OverflowSafeComparatorLib for uint32; using SafeCast for uint256; /// @notice The maximum number of observations uint24 public constant MAX_CARDINALITY = 16777215; // 2**24 /** * @notice Observation, which includes an amount and timestamp. * @param amount `amount` at `timestamp`. * @param timestamp Recorded `timestamp`. */ struct Observation { uint224 amount; uint32 timestamp; } /** * @notice Fetches Observations `beforeOrAt` and `atOrAfter` a `_target`, eg: where [`beforeOrAt`, `atOrAfter`] is satisfied. * The result may be the same Observation, or adjacent Observations. * @dev The answer must be contained in the array used when the target is located within the stored Observation. * boundaries: older than the most recent Observation and younger, or the same age as, the oldest Observation. * @dev If `_newestObservationIndex` is less than `_oldestObservationIndex`, it means that we've wrapped around the circular buffer. * So the most recent observation will be at `_oldestObservationIndex + _cardinality - 1`, at the beginning of the circular buffer. * @param _observations List of Observations to search through. * @param _newestObservationIndex Index of the newest Observation. Right side of the circular buffer. * @param _oldestObservationIndex Index of the oldest Observation. Left side of the circular buffer. * @param _target Timestamp at which we are searching the Observation. * @param _cardinality Cardinality of the circular buffer we are searching through. * @param _time Timestamp at which we perform the binary search. * @return beforeOrAt Observation recorded before, or at, the target. * @return atOrAfter Observation recorded at, or after, the target. */ function binarySearch( Observation[MAX_CARDINALITY] storage _observations, uint24 _newestObservationIndex, uint24 _oldestObservationIndex, uint32 _target, uint24 _cardinality, uint32 _time ) internal view returns (Observation memory beforeOrAt, Observation memory atOrAfter) { uint256 leftSide = _oldestObservationIndex; uint256 rightSide = _newestObservationIndex < leftSide ? leftSide + _cardinality - 1 : _newestObservationIndex; uint256 currentIndex; while (true) { // We start our search in the middle of the `leftSide` and `rightSide`. // After each iteration, we narrow down the search to the left or the right side while still starting our search in the middle. currentIndex = (leftSide + rightSide) / 2; beforeOrAt = _observations[uint24(RingBufferLib.wrap(currentIndex, _cardinality))]; uint32 beforeOrAtTimestamp = beforeOrAt.timestamp; // We've landed on an uninitialized timestamp, keep searching higher (more recently). if (beforeOrAtTimestamp == 0) { leftSide = currentIndex + 1; continue; } atOrAfter = _observations[uint24(RingBufferLib.nextIndex(currentIndex, _cardinality))]; bool targetAtOrAfter = beforeOrAtTimestamp.lte(_target, _time); // Check if we've found the corresponding Observation. if (targetAtOrAfter && _target.lte(atOrAfter.timestamp, _time)) { break; } // If `beforeOrAtTimestamp` is greater than `_target`, then we keep searching lower. To the left of the current index. if (!targetAtOrAfter) { rightSide = currentIndex - 1; } else { // Otherwise, we keep searching higher. To the left of the current index. leftSide = currentIndex + 1; } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; /// @title OverflowSafeComparatorLib library to share comparator functions between contracts /// @dev Code taken from Uniswap V3 Oracle.sol: https://github.com/Uniswap/v3-core/blob/3e88af408132fc957e3e406f65a0ce2b1ca06c3d/contracts/libraries/Oracle.sol /// @author PoolTogether Inc. library OverflowSafeComparatorLib { /// @notice 32-bit timestamps comparator. /// @dev safe for 0 or 1 overflows, `_a` and `_b` must be chronologically before or equal to time. /// @param _a A comparison timestamp from which to determine the relative position of `_timestamp`. /// @param _b Timestamp to compare against `_a`. /// @param _timestamp A timestamp truncated to 32 bits. /// @return bool Whether `_a` is chronologically < `_b`. function lt( uint32 _a, uint32 _b, uint32 _timestamp ) internal pure returns (bool) { // No need to adjust if there hasn't been an overflow if (_a <= _timestamp && _b <= _timestamp) return _a < _b; uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32; uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32; return aAdjusted < bAdjusted; } /// @notice 32-bit timestamps comparator. /// @dev safe for 0 or 1 overflows, `_a` and `_b` must be chronologically before or equal to time. /// @param _a A comparison timestamp from which to determine the relative position of `_timestamp`. /// @param _b Timestamp to compare against `_a`. /// @param _timestamp A timestamp truncated to 32 bits. /// @return bool Whether `_a` is chronologically <= `_b`. function lte( uint32 _a, uint32 _b, uint32 _timestamp ) internal pure returns (bool) { // No need to adjust if there hasn't been an overflow if (_a <= _timestamp && _b <= _timestamp) return _a <= _b; uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32; uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32; return aAdjusted <= bAdjusted; } /// @notice 32-bit timestamp subtractor /// @dev safe for 0 or 1 overflows, where `_a` and `_b` must be chronologically before or equal to time /// @param _a The subtraction left operand /// @param _b The subtraction right operand /// @param _timestamp The current time. Expected to be chronologically after both. /// @return The difference between a and b, adjusted for overflow function checkedSub( uint32 _a, uint32 _b, uint32 _timestamp ) internal pure returns (uint32) { // No need to adjust if there hasn't been an overflow if (_a <= _timestamp && _b <= _timestamp) return _a - _b; uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32; uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32; return uint32(aAdjusted - bAdjusted); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; library RingBufferLib { /** * @notice Returns wrapped TWAB index. * @dev In order to navigate the TWAB circular buffer, we need to use the modulo operator. * @dev For example, if `_index` is equal to 32 and the TWAB circular buffer is of `_cardinality` 32, * it will return 0 and will point to the first element of the array. * @param _index Index used to navigate through the TWAB circular buffer. * @param _cardinality TWAB buffer cardinality. * @return TWAB index. */ function wrap(uint256 _index, uint256 _cardinality) internal pure returns (uint256) { return _index % _cardinality; } /** * @notice Computes the negative offset from the given index, wrapped by the cardinality. * @dev We add `_cardinality` to `_index` to be able to offset even if `_amount` is superior to `_cardinality`. * @param _index The index from which to offset * @param _amount The number of indices to offset. This is subtracted from the given index. * @param _cardinality The number of elements in the ring buffer * @return Offsetted index. */ function offset( uint256 _index, uint256 _amount, uint256 _cardinality ) internal pure returns (uint256) { return wrap(_index + _cardinality - _amount, _cardinality); } /// @notice Returns the index of the last recorded TWAB /// @param _nextIndex The next available twab index. This will be recorded to next. /// @param _cardinality The cardinality of the TWAB history. /// @return The index of the last recorded TWAB function newestIndex(uint256 _nextIndex, uint256 _cardinality) internal pure returns (uint256) { if (_cardinality == 0) { return 0; } return wrap(_nextIndex + _cardinality - 1, _cardinality); } /// @notice Computes the ring buffer index that follows the given one, wrapped by cardinality /// @param _index The index to increment /// @param _cardinality The number of elements in the Ring Buffer /// @return The next index relative to the given index. Will wrap around to 0 if the next index == cardinality function nextIndex(uint256 _index, uint256 _cardinality) internal pure returns (uint256) { return wrap(_index + 1, _cardinality); } }
Renounce ownership of the contract. Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner./
function renounceOwnership() external virtual onlyOwner { _setOwner(address(0)); }
174,103
./partial_match/1/0xdb3D91Dcb27547d82A09556D1028beEdB04A5902/sources/src/Sand/erc777/ERC777MetaTxExtension.sol
should we support non-erc777 execution ? idealy we would like to charge only max(BASE_GAS, gas consumed outside the inner call) + gas consumed as part of the inner call
function performERC777MetaTx( address _from, address _to, uint256 _amount, bytes memory _data, uint256 initialGas, address _tokenReceiver ) internal returns (bool, bytes memory) { bool success; bytes memory returnData; if(_data.length == 0){ _transfer(_from, _to, _amount); success = true; (success, returnData) = address(this).call.gas(params[2])(abi.encodeWithSignature("sendFrom(address,address,uint256,bytes)", _from, _to, _amount, _data)); require(gasleft() >= params[2].div(63), "not enough gas left"); } if(params[3] > 0) { uint256 gasConsumed = (initialGas + MIN_GAS) - gasleft(); if(gasConsumed > GAS_LIMIT_OFFSET + params[2]) { gasConsumed = GAS_LIMIT_OFFSET + params[2]; } _transfer(_from, _tokenReceiver, gasConsumed * params[3]); } return (success, returnData); }
9,405,482
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import './bases/staking/StakingRewards.sol'; import './bases/BaseTokenUpgradeable.sol'; import './bases/staking/interfaces/IOriginatorStaking.sol'; import '../reserve/IReserve.sol'; import '../utils/SafeMathUint128.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; /** * @title OriginatorStaking * @notice Contract to stake Originator Hub tokens, tokenize the position and get rewards, inheriting from a distribution manager contract * @author Aave / Ethichub **/ contract OriginatorStaking is Initializable, StakingRewards, BaseTokenUpgradeable, IStaking, IProjectFundedRewards, IOriginatorManager { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; using SafeMathUint128 for uint128; enum OriginatorStakingState { UNINITIALIZED, STAKING, STAKING_END, DEFAULT } OriginatorStakingState public state; IERC20Upgradeable public STAKED_TOKEN; /// @notice IReserve to pull from the rewards, needs to have this contract as WITHDRAW role IReserve public REWARDS_VAULT; bytes32 public constant GOVERNANCE_ROLE = keccak256('GOVERNANCE_ROLE'); uint256 public stakingGoal; uint256 public defaultedAmount; mapping(address => uint256) public stakerRewardsToClaim; bytes32 public constant ORIGINATOR_ROLE = keccak256('ORIGINATOR_ROLE'); bytes32 public constant AUDITOR_ROLE = keccak256('AUDITOR_ROLE'); uint256 public DEFAULT_DATE; mapping(bytes32 => uint256) public proposerBalances; event StateChange(uint256 state); event Staked(address indexed from, address indexed onBehalfOf, uint256 amount); event Redeem(address indexed from, address indexed to, uint256 amount); event Withdraw(address indexed proposer, uint256 amount); event RewardsAccrued(address user, uint256 amount); event RewardsClaimed(address indexed from, address indexed to, uint256 amount); event StartRewardsProjectFunded(uint128 previousEmissionPerSecond, uint128 extraEmissionsPerSecond, address lendingContractAddress); event EndRewardsProjectFunded(uint128 restoredEmissionsPerSecond, uint128 extraEmissionsPerSecond, address lendingContractAddress); modifier onlyGovernance() { require(hasRole(GOVERNANCE_ROLE, msg.sender), 'ONLY_GOVERNANCE'); _; } modifier onlyEmissionManager() { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); _; } modifier onlyOnStakingState() { require(state == OriginatorStakingState.STAKING, 'ONLY_ON_STAKING_STATE'); _; } modifier notZeroAmount(uint256 _amount) { require(_amount > 0, 'INVALID_ZERO_AMOUNT'); _; } function initialize( string memory _name, string memory _symbol, IERC20Upgradeable _lockedToken, IReserve _rewardsVault, address _emissionManager, uint128 _distributionDuration ) public initializer { __BaseTokenUpgradeable_init( msg.sender, 0, _name, _symbol, _name ); __StakingRewards_init(_emissionManager, _distributionDuration); STAKED_TOKEN = _lockedToken; REWARDS_VAULT = _rewardsVault; _changeState(OriginatorStakingState.UNINITIALIZED); } /** * @notice Function to set up proposers (originator and auditor) * in proposal period. * @param _auditor address * @param _originator address * @param _auditorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _originatorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _stakingGoal uint256 wei amount in Ethix * @param _defaultDelay uint256 seconds */ function setUpTerms( address _auditor, address _originator, address _governance, uint256 _auditorPercentage, uint256 _originatorPercentage, uint256 _stakingGoal, uint256 _defaultDelay ) external override notZeroAmount(_stakingGoal) onlyEmissionManager { require(_auditor != _originator, 'PROPOSERS_CANNOT_BE_THE_SAME'); require(_auditorPercentage != 0 && _originatorPercentage != 0, 'INVALID_PERCENTAGE_ZERO'); require(state == OriginatorStakingState.UNINITIALIZED, 'ONLY_ON_UNINITILIZED_STATE'); _setupRole(AUDITOR_ROLE, _auditor); _setupRole(ORIGINATOR_ROLE, _originator); _setupRole(GOVERNANCE_ROLE, _governance); _depositProposer(_auditor, _auditorPercentage, _stakingGoal); _depositProposer(_originator, _originatorPercentage, _stakingGoal); stakingGoal = _stakingGoal; DEFAULT_DATE = _defaultDelay.add(DISTRIBUTION_END); _changeState(OriginatorStakingState.STAKING); } /** * @notice Function to renew terms in STAKING_END or DEFAULT period. * @param _newAuditorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _newOriginatorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _newStakingGoal uint256 wei amount in Ethix * @param _newDistributionDuration uint128 seconds (e.g. 365 days == 31536000) * @param _newDefaultDelay uint256 seconds (e.g 90 days == 7776000) */ function renewTerms( uint256 _newAuditorPercentage, uint256 _newOriginatorPercentage, uint256 _newStakingGoal, uint128 _newDistributionDuration, uint256 _newDefaultDelay) external override notZeroAmount(_newStakingGoal) onlyGovernance { require(state == OriginatorStakingState.STAKING_END || state == OriginatorStakingState.DEFAULT, 'INVALID_STATE'); DISTRIBUTION_END = block.timestamp.add(_newDistributionDuration); _depositProposer(getRoleMember(AUDITOR_ROLE, 0), _newAuditorPercentage, _newStakingGoal); _depositProposer(getRoleMember(ORIGINATOR_ROLE, 0), _newOriginatorPercentage, _newStakingGoal); stakingGoal = _newStakingGoal; DEFAULT_DATE = _newDefaultDelay.add(DISTRIBUTION_END); _changeState(OriginatorStakingState.STAKING); } /** * @notice Function to stake tokens * @param _onBehalfOf Address to stake to * @param _amount Amount to stake **/ function stake(address _onBehalfOf, uint256 _amount) external override notZeroAmount(_amount) onlyOnStakingState { require(!hasReachedGoal(), 'GOAL_HAS_REACHED'); if (STAKED_TOKEN.balanceOf(address(this)).add(_amount) > stakingGoal) { _amount = stakingGoal.sub(STAKED_TOKEN.balanceOf(address(this))); } uint256 balanceOfUser = balanceOf(_onBehalfOf); uint256 accruedRewards = _updateUserAssetInternal(_onBehalfOf, address(this), balanceOfUser, totalSupply()); if (accruedRewards != 0) { emit RewardsAccrued(_onBehalfOf, accruedRewards); stakerRewardsToClaim[_onBehalfOf] = stakerRewardsToClaim[_onBehalfOf].add(accruedRewards); } _mint(_onBehalfOf, _amount); IERC20Upgradeable(STAKED_TOKEN).safeTransferFrom(msg.sender, address(this), _amount); emit Staked(msg.sender, _onBehalfOf, _amount); } /** * @dev Redeems staked tokens, and stop earning rewards * @param _to Address to redeem to * @param _amount Amount to redeem **/ function redeem(address _to, uint256 _amount) external override notZeroAmount(_amount) { require(_checkRedeemEligibilityState(), 'WRONG_STATE'); require(balanceOf(msg.sender) != 0, 'SENDER_BALANCE_ZERO'); uint256 balanceOfMessageSender = balanceOf(msg.sender); uint256 amountToRedeem = (_amount > balanceOfMessageSender) ? balanceOfMessageSender : _amount; _updateCurrentUnclaimedRewards(msg.sender, balanceOfMessageSender, true); _burn(msg.sender, amountToRedeem); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(_to, amountToRedeem); emit Redeem(msg.sender, _to, amountToRedeem); } /** * @notice method to withdraw deposited amount. * @param _amount Amount to withdraw */ function withdrawProposerStake(uint256 _amount) external override { require(state == OriginatorStakingState.STAKING_END, 'ONLY_ON_STAKING_END_STATE'); bytes32 senderRole = 0x00; if (msg.sender == getRoleMember(ORIGINATOR_ROLE, 0)) { senderRole = ORIGINATOR_ROLE; } else if (msg.sender == getRoleMember(AUDITOR_ROLE, 0)) { senderRole = AUDITOR_ROLE; } else { revert('WITHDRAW_PERMISSION_DENIED'); } require(proposerBalances[senderRole] != 0, 'INVALID_ZERO_AMOUNT'); uint256 amountToWithdraw = (_amount > proposerBalances[senderRole]) ? proposerBalances[senderRole] : _amount; proposerBalances[senderRole] = proposerBalances[senderRole].sub(amountToWithdraw); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, amountToWithdraw); } /** * @dev Claims an `amount` from Rewards reserve to the address `to` * @param _to Address to stake for * @param _amount Amount to stake **/ function claimRewards(address payable _to, uint256 _amount) external override { uint256 newTotalRewards = _updateCurrentUnclaimedRewards(msg.sender, balanceOf(msg.sender), false); uint256 amountToClaim = (_amount == type(uint256).max) ? newTotalRewards : _amount; stakerRewardsToClaim[msg.sender] = newTotalRewards.sub(amountToClaim, 'INVALID_AMOUNT'); require(REWARDS_VAULT.transfer(_to, amountToClaim), 'ERROR_TRANSFER_FROM_VAULT'); emit RewardsClaimed(msg.sender, _to, amountToClaim); } /** * Function to add an extra emissions per second corresponding to staker rewards when a lending project by this originator * is funded. * @param _extraEmissionsPerSecond emissions per second to be added to current ones. * @param _lendingContractAddress lending contract address is relationated with this rewards */ function startProjectFundedRewards(uint128 _extraEmissionsPerSecond, address _lendingContractAddress) external override onlyOnStakingState { AssetData storage currentDistribution = assets[address(this)]; uint128 currentEmission = currentDistribution.emissionPerSecond; uint128 newEmissionsPerSecond = currentDistribution.emissionPerSecond.add(_extraEmissionsPerSecond); DistributionTypes.AssetConfigInput[] memory newAssetConfig = new DistributionTypes.AssetConfigInput[](1); newAssetConfig[0] = DistributionTypes.AssetConfigInput({ emissionPerSecond: newEmissionsPerSecond, totalStaked: totalSupply(), underlyingAsset: address(this) }); configureAssets(newAssetConfig); emit StartRewardsProjectFunded(currentEmission, _extraEmissionsPerSecond, _lendingContractAddress); } /** * Function to end extra emissions per second corresponding to staker rewards when a lending project by this originator * is funded. * @param _extraEmissionsPerSecond emissions per second to be added to current ones. * @param _lendingContractAddress lending contract address is relationated with this rewards. */ function endProjectFundedRewards(uint128 _extraEmissionsPerSecond, address _lendingContractAddress) external override onlyOnStakingState { AssetData storage currentDistribution = assets[address(this)]; uint128 currentEmission = currentDistribution.emissionPerSecond; uint128 newEmissionsPerSecond = currentDistribution.emissionPerSecond.sub(_extraEmissionsPerSecond); DistributionTypes.AssetConfigInput[] memory newAssetConfig = new DistributionTypes.AssetConfigInput[](1); newAssetConfig[0] = DistributionTypes.AssetConfigInput({ emissionPerSecond: newEmissionsPerSecond, totalStaked: totalSupply(), underlyingAsset: address(this) }); configureAssets(newAssetConfig); emit EndRewardsProjectFunded(currentEmission, _extraEmissionsPerSecond, _lendingContractAddress); } /** * @notice Amount to substract of the contract when state is default * @param _amount amount to substract * @param _role role to substract the amount (Originator, Auditor) */ function liquidateProposerStake(uint256 _amount, bytes32 _role) external override notZeroAmount(_amount) onlyGovernance { require(state == OriginatorStakingState.DEFAULT, 'ONLY_ON_DEFAULT'); require(_role == AUDITOR_ROLE || _role == ORIGINATOR_ROLE, 'INVALID_PROPOSER_ROLE'); proposerBalances[_role] = proposerBalances[_role].sub(_amount, 'INVALID_LIQUIDATE_AMOUNT'); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(msg.sender, _amount); } /** * @notice Function to declare contract on staking end state * Only governance could change to this state **/ function declareStakingEnd() external override onlyGovernance onlyOnStakingState { _endDistributionIfNeeded(); _changeState(OriginatorStakingState.STAKING_END); } /** * @notice Function to declare as DEFAULT * @param _defaultedAmount uint256 **/ function declareDefault(uint256 _defaultedAmount) external override onlyGovernance onlyOnStakingState { require(block.timestamp >= DEFAULT_DATE, 'DEFAULT_DATE_NOT_REACHED'); defaultedAmount = _defaultedAmount; _endDistributionIfNeeded(); _changeState(OriginatorStakingState.DEFAULT); } /** * @dev Return the total rewards pending to claim by an staker * @param _staker The staker address * @return The rewards */ function getTotalRewardsBalance(address _staker) external override view returns (uint256) { DistributionTypes.UserStakeInput[] memory userStakeInputs = new DistributionTypes.UserStakeInput[](1); userStakeInputs[0] = DistributionTypes.UserStakeInput({ underlyingAsset: address(this), stakedByUser: balanceOf(_staker), totalStaked: totalSupply() }); return stakerRewardsToClaim[_staker].add(_getUnclaimedRewards(_staker, userStakeInputs)); } /** * @notice Check if fulfilled the objective (Only valid on STAKING state!!) */ function hasReachedGoal() public override notZeroAmount(stakingGoal) view returns (bool) { if (proposerBalances[ORIGINATOR_ROLE].add(proposerBalances[AUDITOR_ROLE]).add(totalSupply()) >= stakingGoal) { return true; } return false; } /** * @notice Function to transfer participation amount (originator or auditor) */ function _depositProposer(address _proposer, uint256 _percentage, uint256 _goalAmount) internal { uint256 percentageAmount = _calculatePercentage(_goalAmount, _percentage); uint256 depositAmount = 0; if (_proposer == getRoleMember(ORIGINATOR_ROLE, 0)) { depositAmount = _calculateDepositAmount(ORIGINATOR_ROLE, percentageAmount); proposerBalances[ORIGINATOR_ROLE] = proposerBalances[ORIGINATOR_ROLE].add(depositAmount); } else if (_proposer == getRoleMember(AUDITOR_ROLE, 0)) { depositAmount = _calculateDepositAmount(AUDITOR_ROLE, percentageAmount); proposerBalances[AUDITOR_ROLE] = proposerBalances[AUDITOR_ROLE].add(depositAmount); } IERC20Upgradeable(STAKED_TOKEN).safeTransferFrom(_proposer, address(this), depositAmount); } /** * @dev Internal ERC20 _transfer of the tokenized staked tokens * @param _from Address to transfer from * @param _to Address to transfer to * @param _amount Amount to transfer **/ function _transfer( address _from, address _to, uint256 _amount ) internal override { uint256 balanceOfFrom = balanceOf(_from); // Sender _updateCurrentUnclaimedRewards(_from, balanceOfFrom, true); // Recipient if (_from != _to) { uint256 balanceOfTo = balanceOf(_to); _updateCurrentUnclaimedRewards(_to, balanceOfTo, true); } super._transfer(_from, _to, _amount); } /** * @dev Check if the state of contract is suitable to redeem */ function _checkRedeemEligibilityState() internal view returns (bool) { if (state == OriginatorStakingState.STAKING_END) { return true; } else if (state == OriginatorStakingState.DEFAULT && defaultedAmount <= proposerBalances[ORIGINATOR_ROLE].add(proposerBalances[AUDITOR_ROLE])) { return true; } else { return false; } } /** * @dev Updates the user state related with his accrued rewards * @param _user Address of the user * @param _userBalance The current balance of the user * @param _updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user * @return The unclaimed rewards that were added to the total accrued **/ function _updateCurrentUnclaimedRewards( address _user, uint256 _userBalance, bool _updateStorage ) internal returns (uint256) { uint256 accruedRewards = _updateUserAssetInternal(_user, address(this), _userBalance, totalSupply()); uint256 unclaimedRewards = stakerRewardsToClaim[_user].add(accruedRewards); if (accruedRewards != 0) { if (_updateStorage) { stakerRewardsToClaim[_user] = unclaimedRewards; } emit RewardsAccrued(_user, accruedRewards); } return unclaimedRewards; } /** * @notice Function to calculate a percentage of an amount * @param _amount Amount to calculate the percentage of * @param _percentage Percentage to calculate of this amount * @return (amount) */ function _calculatePercentage(uint256 _amount, uint256 _percentage) internal pure returns (uint256) { return uint256(_amount.mul(_percentage).div(10000)); } /** * @notice Function to get the actual participation amount * of proposers according the amount that already exists in the contract * @param _role Auditor or originator role * @param _percentageAmount Percentage of staking goal amount * Note _percentageAmount SHOULD BE GREATER than the previously existing amount */ function _calculateDepositAmount(bytes32 _role, uint256 _percentageAmount) internal view returns (uint256){ return uint256(_percentageAmount.sub(proposerBalances[_role])); } /** * @notice Function to change contract state * @param _newState New contract state **/ function _changeState(OriginatorStakingState _newState) internal { state = _newState; emit StateChange(uint256(_newState)); } /** * @notice Function to change DISTRIBUTION_END if timestamp is less than the initial one **/ function _endDistributionIfNeeded() internal { if (block.timestamp <= DISTRIBUTION_END) { _changeDistributionEndDate(block.timestamp); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import './lib/DistributionTypes.sol'; import './interfaces/IStakingRewards.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '../../../utils/SafeMathUint128.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; /** * @title StakingRewards * @notice Accounting contract to manage multiple staking distributions * @author Aave / Ethichub **/ contract StakingRewards is Initializable, IStakingRewards, AccessControlUpgradeable { bytes32 public constant EMISSION_MANAGER_ROLE = keccak256('EMISSION_MANAGER'); using SafeMathUpgradeable for uint256; using SafeMathUint128 for uint128; struct AssetData { uint128 emissionPerSecond; uint128 lastUpdateTimestamp; uint256 index; mapping(address => uint256) users; } uint256 public DISTRIBUTION_END; uint8 constant public PRECISION = 18; mapping(address => AssetData) public assets; event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); event DistributionEndChanged(uint256 distributionEnd); function __StakingRewards_init(address emissionManager, uint256 distributionDuration) public initializer { __AccessControl_init_unchained(); DISTRIBUTION_END = block.timestamp.add(distributionDuration); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(EMISSION_MANAGER_ROLE, emissionManager); } /** * @dev Configures the distribution of rewards for a list of assets * @param assetsConfigInput The list of configurations to apply **/ function configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) public override { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset]; _updateAssetStateInternal( assetsConfigInput[i].underlyingAsset, assetConfig, assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond; emit AssetConfigUpdated( assetsConfigInput[i].underlyingAsset, assetsConfigInput[i].emissionPerSecond ); } } /** * @notice Change distribution end datetime * @param _distributionEndDate new distribution end datetime (UNIX Timestamp) */ function changeDistributionEndDate(uint256 _distributionEndDate) public override { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); return _changeDistributionEndDate(_distributionEndDate); } /** * @notice Change distribution end datetime internal function * @param _distributionEndDate new distribution end datetime (UNIX Timestamp) */ function _changeDistributionEndDate(uint256 _distributionEndDate) internal { DISTRIBUTION_END = _distributionEndDate; emit DistributionEndChanged(DISTRIBUTION_END); } /** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param underlyingAsset The address used as key in the distribution * @param assetConfig Storage pointer to the distribution's config * @param totalStaked Current total of staked assets for this distribution * @return The new distribution index **/ function _updateAssetStateInternal( address underlyingAsset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex( oldIndex, assetConfig.emissionPerSecond, lastUpdateTimestamp, totalStaked ); if (newIndex != oldIndex) { assetConfig.index = newIndex; emit AssetIndexUpdated(underlyingAsset, newIndex); } assetConfig.lastUpdateTimestamp = uint128(block.timestamp); return newIndex; } /** * @dev Updates the state of an user in a distribution * @param user The user's address * @param asset The address of the reference asset of the distribution * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param totalStaked Total tokens staked in the distribution * @return The accrued rewards for the user until the moment **/ function _updateUserAssetInternal( address user, address asset, uint256 stakedByUser, uint256 totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[asset]; uint256 userIndex = assetData.users[user]; uint256 accruedRewards = 0; uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked); if (userIndex != newIndex) { if (stakedByUser != 0) { accruedRewards = _getRewards(stakedByUser, newIndex, userIndex); } assetData.users[user] = newIndex; emit UserIndexUpdated(user, asset, newIndex); } return accruedRewards; } /** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _claimRewards(address payable user, DistributionTypes.UserStakeInput[] memory stakes) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( user, stakes[i].underlyingAsset, stakes[i].stakedByUser, stakes[i].totalStaked ) ); } return accruedRewards; } /** * @dev Return the accrued rewards for an user over a list of distribution * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { AssetData storage assetConfig = assets[stakes[i].underlyingAsset]; uint256 assetIndex = _getAssetIndex( assetConfig.index, assetConfig.emissionPerSecond, assetConfig.lastUpdateTimestamp, stakes[i].totalStaked ); accruedRewards = accruedRewards.add( _getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user]) ); } return accruedRewards; } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param principalUserBalance Amount staked by the user on a distribution * @param reserveIndex Current index of the distribution * @param userIndex Index stored for the user, representation his staking moment * @return The rewards **/ function _getRewards( uint256 principalUserBalance, uint256 reserveIndex, uint256 userIndex ) internal view returns (uint256) { return principalUserBalance.mul(reserveIndex.sub(userIndex)).div(10**uint256(PRECISION)); } /** * @dev Calculates the next value of an specific distribution index, with validations * @param currentIndex Current index of the distribution * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param lastUpdateTimestamp Last moment this distribution was updated * @param totalBalance of tokens considered for the distribution * @return The new index. **/ function _getAssetIndex( uint256 currentIndex, uint256 emissionPerSecond, uint128 lastUpdateTimestamp, uint256 totalBalance ) internal view returns (uint256) { if ( emissionPerSecond == 0 || totalBalance == 0 || lastUpdateTimestamp == block.timestamp || lastUpdateTimestamp >= DISTRIBUTION_END ) { return currentIndex; } uint256 currentTimestamp = block.timestamp > DISTRIBUTION_END ? DISTRIBUTION_END : block.timestamp; uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp); return emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add( currentIndex ); } /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) public view returns (uint256) { return assets[asset].users[user]; } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import '../ERCs/ERC677/ERC677Upgradeable.sol'; import '../ERCs/ERC2612/ERC2612Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import 'hardhat/console.sol'; contract BaseTokenUpgradeable is Initializable, ERC677Upgradeable, ERC2612Upgradeable { function __BaseTokenUpgradeable_init( address _initialAccount, uint256 _initialBalance, string memory _name, string memory _symbol, string memory _EIP712Name ) public initializer { __ERC677_init(_initialAccount, _initialBalance, _name, _symbol); __ERC2612_init(_EIP712Name); } function permit( address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, uint8 _v, bytes32 _r, bytes32 _s ) public override { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256( abi.encode(PERMIT_TYPEHASH, _holder, _spender, _nonce, _expiry, _allowed) ) ) ); require(_holder != address(0), 'Token: invalid-address-0'); require(_holder == ecrecover(digest, _v, _r, _s), 'Token: invalid-permit'); require(_expiry == 0 || block.timestamp <= _expiry, 'Token: permit-expired'); require(_nonce == nonces[_holder]++, 'Token: invalid-nonce'); uint256 _amount = _allowed ? 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff : 0; _approve(_holder, _spender, _amount); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface IOriginatorManager { function setUpTerms( address auditor, address originator, address governance, uint256 auditorPercentage, uint256 originatorPercentage, uint256 stakingGoal, uint256 defaultDelay ) external; function renewTerms( uint256 newAuditorPercentage, uint256 newOriginatorPercentage, uint256 newStakingGoal, uint128 newDistributionDuration, uint256 newDefaultDelay ) external; function declareDefault(uint256 defaultedAmount) external; function liquidateProposerStake(uint256 amount, bytes32 role) external; function declareStakingEnd() external; function hasReachedGoal() external view returns (bool); } interface IProjectFundedRewards { function startProjectFundedRewards(uint128 extraEmissionsPerSecond, address lendingContractAddress) external; function endProjectFundedRewards(uint128 extraEmissionsPerSecond, address lendingContractAddress) external; } interface IStaking { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function claimRewards(address payable to, uint256 amount) external; function withdrawProposerStake(uint256 amount) external; function getTotalRewardsBalance(address staker) external view returns (uint256); } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IReserve { event Transfer(address indexed to, uint256 amount); event RescueFunds(address token, address indexed to, uint256 amount); function balance() external view returns (uint256); function transfer(address payable _to, uint256 _value) external returns (bool); function rescueFunds( address _tokenToRescue, address _to, uint256 _amount ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUint128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint128 a, uint128 b) internal pure returns (uint128) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint128 a, uint128 b) internal pure returns (uint128) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint128 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint128 a, uint128 b) internal pure returns (uint128) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint128 a, uint128 b) internal pure returns (uint128) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; library DistributionTypes { struct AssetConfigInput { uint128 emissionPerSecond; uint256 totalStaked; address underlyingAsset; } struct UserStakeInput { address underlyingAsset; uint256 stakedByUser; uint256 totalStaked; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import '../lib/DistributionTypes.sol'; interface IStakingRewards { function changeDistributionEndDate(uint256 date) external; function configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import './IERC677.sol'; import './IERC677Receiver.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; contract ERC677Upgradeable is Initializable, IERC677, ERC20Upgradeable { /** * @dev Sets the values for {_name} and {_symbol}, initializes {_decimals} with * a default value of 18. And mints {_initialBalance} to address {_initialAccount} * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC677_init( address _initialAccount, uint256 _initialBalance, string memory _name, string memory _symbol ) internal initializer { __ERC20_init(_name, _symbol); if (_initialBalance != 0) { _mint(_initialAccount, _initialBalance); } } /** * @dev check if an address is a contract. * @param _addr The address to check. */ function isContract(address _addr) private view returns (bool hasCode) { uint256 length; assembly { length := extcodesize(_addr) } return length > 0; } /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall( address _to, uint256 _value, bytes memory _data ) public virtual override returns (bool success) { require(super.transfer(_to, _value), 'ERC677Upgradeable: transfer failed'); if (isContract(_to)) { IERC677Receiver(_to).onTokenTransfer(msg.sender, _value, _data); } return true; } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; abstract contract ERC2612Upgradeable is Initializable { // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public PERMIT_TYPEHASH; string public version; mapping(address => uint256) public nonces; function __ERC2612_init(string memory _EIP712Name) internal initializer { version = '1'; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ), keccak256(bytes(_EIP712Name)), keccak256(bytes(version)), getChainId(), address(this) ) ); PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; } function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) public virtual; function getChainId() public pure returns (uint256 chainId) { // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IERC677 { function transferAndCall( address to, uint256 value, bytes memory data ) external returns (bool ok); event Transfer(address indexed from, address indexed to, uint256 value, bytes data); } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IERC677Receiver { function onTokenTransfer( address from, uint256 amount, bytes calldata data ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; }
Updates the state of one distribution, mainly rewards index and timestamp underlyingAsset The address used as key in the distribution assetConfig Storage pointer to the distribution's config totalStaked Current total of staked assets for this distribution return The new distribution index/
function _updateAssetStateInternal( address underlyingAsset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex( oldIndex, assetConfig.emissionPerSecond, lastUpdateTimestamp, totalStaked ); if (newIndex != oldIndex) { assetConfig.index = newIndex; emit AssetIndexUpdated(underlyingAsset, newIndex); } assetConfig.lastUpdateTimestamp = uint128(block.timestamp); return newIndex; }
142,872
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @studydefi/money-legos/dydx/contracts/ISoloMargin.sol library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) public; function getIsGlobalOperator(address operator) public view returns (bool); function getMarketTokenAddress(uint256 marketId) public view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) public; function getAccountValues(Account.Info memory account) public view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) public view returns (address); function getMarketInterestSetter(uint256 marketId) public view returns (address); function getMarketSpreadPremium(uint256 marketId) public view returns (Decimal.D256 memory); function getNumMarkets() public view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) public returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) public; function ownerSetLiquidationSpread(Decimal.D256 memory spread) public; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public; function getIsLocalOperator(address owner, address operator) public view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) public view returns (Types.Par memory); function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) public; function getMarginRatio() public view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) public view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) public view returns (bool); function getRiskParams() public view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) public view returns (address[] memory, Types.Par[] memory, Types.Wei[] memory); function renounceOwnership() public; function getMinBorrowedValue() public view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) public; function getMarketPrice(uint256 marketId) public view returns (address); function owner() public view returns (address); function isOwner() public view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) public returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public; function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public; function getMarketWithInfo(uint256 marketId) public view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) public; function getLiquidationSpread() public view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) public view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) public view returns (Types.TotalPar memory); function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) public view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) public view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) public view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) public view returns (uint8); function getEarningsRate() public view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) public; function getRiskLimits() public view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) public view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) public; function ownerSetGlobalOperator(address operator, bool approved) public; function transferOwnership(address newOwner) public; function getAdjustedAccountValues(Account.Info memory account) public view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) public view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) public view returns (Interest.Rate memory); } // File: @studydefi/money-legos/dydx/contracts/DydxFlashloanBase.sol contract DydxFlashloanBase { using SafeMath for uint256; // -- Internal Helper functions -- // function _getMarketIdFromTokenAddress(address _solo, address token) internal view returns (uint256) { ISoloMargin solo = ISoloMargin(_solo); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == token) { return i; } } revert("No marketId found for provided token"); } function _getRepaymentAmountInternal(uint256 amount) internal pure returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } // File: @studydefi/money-legos/compound/contracts/ICToken.sol interface ICToken { function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function exchangeRateCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint256); function balanceOfUnderlying(address account) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function underlying() external view returns (address); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256 balance); function allowance(address, address) external view returns (uint); function approve(address, uint) external; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } // File: @studydefi/money-legos/dydx/contracts/ICallee.sol /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ contract ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) public; } // File: src/contracts/LeveragedYieldFarm.sol //cuz @studydefi doesn't contain clamComp(); interface Comptroller { function enterMarkets(address[] calldata) external returns (uint256[] memory); function claimComp(address holder) external; } contract LeveragedYieldFarm is ICallee, DydxFlashloanBase { // Mainnet Dai // https://etherscan.io/address/0x6b175474e89094c44da98b954eedeac495271d0f#readContract address daiAddress = 0x6B175474E89094C44Da98b954EedeAC495271d0F; IERC20 dai = IERC20(daiAddress); // Mainnet cDai // https://etherscan.io/address/0x5d3a536e4d6dbd6114cc1ead35777bab948e3643#readProxyContract address cDaiAddress = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; ICToken cDai = ICToken(cDaiAddress); // Mainnet Comptroller // https://etherscan.io/address/0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b#readProxyContract address comptrollerAddress = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; Comptroller comptroller = Comptroller(comptrollerAddress); // COMP ERC-20 token // https://etherscan.io/token/0xc00e94cb662c3520282e6f5717214004a7f26888 IERC20 compToken = IERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); // Mainnet dYdX SoloMargin contract // https://etherscan.io/address/0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e#readProxyContract address soloMarginAddress = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; // Contract owner address payable owner; struct MyCustomData { address token; uint256 repayAmount; uint256 fullAmount; bool isDeposit; } event FlashLoan(address indexed _from, bytes32 indexed _id, uint _value); // Modifiers modifier onlyOwner() { require(msg.sender == owner, "caller is not the owner!"); _; } constructor() public { // Track the contract owner owner = msg.sender; // Enter the cDai market so you can borrow another type of asset address[] memory cTokens = new address[](1); cTokens[0] = cDaiAddress; uint256[] memory errors = comptroller.enterMarkets(cTokens); if (errors[0] != 0) { revert("Comptroller.enterMarkets failed."); } } // Don't allow contract to receive Ether by mistake function() external payable { revert(); } function flashLoan(address _solo, address _token, uint256 _amount, uint256 _fullAmount, bool _isDeposit) internal { ISoloMargin solo = ISoloMargin(_solo); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(_solo, _token); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_amount); IERC20(_token).approve(_solo, repayAmount); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _amount); operations[1] = _getCallAction( // Encode MyCustomData for callFunction abi.encode(MyCustomData({ token: _token, repayAmount: repayAmount, fullAmount: _fullAmount, isDeposit: _isDeposit} )) ); operations[2] = _getDepositAction(marketId, repayAmount); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); } // Do not deposit all your DAI because you must pay flash loan fees // Always keep at least 1 DAI in the contract function depositDai(uint256 initialAmount) external onlyOwner returns (bool) { // Total deposit: 30% initial amount, 70% flash loan uint256 totalAmount = (initialAmount * 10) / 3; // loan is 70% of total deposit uint256 flashLoanAmount = totalAmount - initialAmount; // Get DAI Flash Loan for "DEPOSIT" bool isDeposit = true; flashLoan(soloMarginAddress, daiAddress, flashLoanAmount, totalAmount, isDeposit); // execution goes to `callFunction` // Handle remaining execution inside handleDeposit() function return true; } // You must have some Dai in your contract still to pay flash loan fee! // Always keep at least 1 DAI in the contract function withdrawDai(uint256 initialAmount) external onlyOwner returns (bool) { // Total deposit: 30% initial amount, 70% flash loan uint256 totalAmount = (initialAmount * 10) / 3; // loan is 70% of total deposit uint256 flashLoanAmount = totalAmount - initialAmount; // Use flash loan to payback borrowed amount bool isDeposit = false; //false means withdraw flashLoan(soloMarginAddress, daiAddress, flashLoanAmount, totalAmount, isDeposit); // execution goes to `callFunction` // Handle repayment inside handleWithdraw() function // Claim COMP tokens comptroller.claimComp(address(this)); // Withdraw COMP tokens compToken.transfer(owner, compToken.balanceOf(address(this))); // Withdraw Dai to the wallet dai.transfer(owner, dai.balanceOf(address(this))); return true; } // This is the function that will be called postLoan // i.e. Encode the logic to handle your flashloaned funds here function callFunction(address, Account.Info memory, bytes memory data) public { MyCustomData memory mcd = abi.decode(data, (MyCustomData)); uint256 balOfLoanedToken = IERC20(mcd.token).balanceOf(address(this)); // Note that you can ignore the line below // if your dydx account (this contract in this case) // has deposited at least ~2 Wei of assets into the account // to balance out the collaterization ratio require( balOfLoanedToken >= mcd.repayAmount, "Not enough funds to repay dYdX loan!" ); if(mcd.isDeposit == true) { handleDeposit(mcd.fullAmount, mcd.repayAmount); } if(mcd.isDeposit == false) { handleWithdraw(); } } // You must first send DAI to this contract before you can call this function function handleDeposit(uint256 totalAmount, uint256 flashLoanAmount) internal returns (bool) { // Approve Dai tokens as collateral dai.approve(cDaiAddress, totalAmount); // Provide collateral by minting cDai tokens cDai.mint(totalAmount); // Borrow Dai cDai.borrow(flashLoanAmount); // Start earning COMP tokens, yay! return true; } function handleWithdraw() internal returns (bool) { uint256 balance; // Get curent borrow Balance balance = cDai.borrowBalanceCurrent(address(this)); // Approve tokens for repayment dai.approve(address(cDai), balance); // Repay tokens cDai.repayBorrow(balance); // Get cDai balance balance = cDai.balanceOf(address(this)); // Redeem cDai cDai.redeem(balance); return true; } // Fallback in case any other tokens are sent to this contract function withdrawToken(address _tokenAddress) public onlyOwner { uint256 balance = IERC20(_tokenAddress).balanceOf(address(this)); IERC20(_tokenAddress).transfer(owner, balance); } }
You must have some Dai in your contract still to pay flash loan fee! Always keep at least 1 DAI in the contract Total deposit: 30% initial amount, 70% flash loan loan is 70% of total deposit Use flash loan to payback borrowed amount Handle repayment inside handleWithdraw() function Claim COMP tokens Withdraw COMP tokens Withdraw Dai to the wallet
function withdrawDai(uint256 initialAmount) external onlyOwner returns (bool) { uint256 totalAmount = (initialAmount * 10) / 3; uint256 flashLoanAmount = totalAmount - initialAmount; comptroller.claimComp(address(this)); compToken.transfer(owner, compToken.balanceOf(address(this))); dai.transfer(owner, dai.balanceOf(address(this))); return true; }
12,771,482
// SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; pragma abicoder v2; // solhint-disable-line import "@openzeppelin/contracts/utils/Pausable.sol"; import "./CappedTokenSoldCrowdsaleHelper.sol"; import "./FinaWhitelistCrowdsaleHelper.sol"; import "./HoldErc20TokenCrowdsaleHelper.sol"; import "./NoDeliveryCrowdsale.sol"; import "./TimedCrowdsaleHelper.sol"; import "./interfaces/IFinaCrowdsale.sol"; /** * @title FinaCrowdsale * @author Enjinstarter * @dev Defina "FINA" Crowdsale where there is no delivery of tokens in each purchase. */ contract FinaCrowdsale is NoDeliveryCrowdsale, CappedTokenSoldCrowdsaleHelper, HoldErc20TokenCrowdsaleHelper, TimedCrowdsaleHelper, FinaWhitelistCrowdsaleHelper, Pausable, IFinaCrowdsale { using SafeMath for uint256; // https://github.com/crytic/slither/wiki/Detector-Documentation#too-many-digits // slither-disable-next-line too-many-digits address public constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD; struct FinaCrowdsaleInfo { uint256 tokenCap; address whitelistContract; address tokenHold; uint256 minTokenHoldAmount; } address public governanceAccount; address public crowdsaleAdmin; // max 1 lot constructor( address wallet_, FinaCrowdsaleInfo memory crowdsaleInfo, LotsInfo memory lotsInfo, Timeframe memory timeframe, PaymentTokenInfo[] memory paymentTokensInfo ) Crowdsale(wallet_, DEAD_ADDRESS, lotsInfo, paymentTokensInfo) CappedTokenSoldCrowdsaleHelper(crowdsaleInfo.tokenCap) HoldErc20TokenCrowdsaleHelper( crowdsaleInfo.tokenHold, crowdsaleInfo.minTokenHoldAmount ) TimedCrowdsaleHelper(timeframe) FinaWhitelistCrowdsaleHelper(crowdsaleInfo.whitelistContract) { governanceAccount = msg.sender; crowdsaleAdmin = msg.sender; } modifier onlyBy(address account) { require(msg.sender == account, "FinaCrowdsale: sender unauthorized"); _; } /** * @return availableLots Available number of lots for beneficiary */ function getAvailableLotsFor(address beneficiary) external view override returns (uint256 availableLots) { if (!whitelisted(beneficiary)) { return 0; } availableLots = _getAvailableTokensFor(beneficiary).div( getBeneficiaryCap(beneficiary) ); } /** * @return remainingTokens Remaining number of tokens for crowdsale */ function getRemainingTokens() external view override returns (uint256 remainingTokens) { remainingTokens = tokenCap().sub(tokensSold); } function pause() external override onlyBy(crowdsaleAdmin) { _pause(); } function unpause() external override onlyBy(crowdsaleAdmin) { _unpause(); } function extendTime(uint256 newClosingTime) external override onlyBy(crowdsaleAdmin) { _extendTime(newClosingTime); } function setGovernanceAccount(address account) external override onlyBy(governanceAccount) { require(account != address(0), "FinaCrowdsale: zero account"); governanceAccount = account; } function setCrowdsaleAdmin(address account) external override onlyBy(governanceAccount) { require(account != address(0), "FinaCrowdsale: zero account"); crowdsaleAdmin = account; } /** * @param beneficiary Address receiving the tokens * @return lotSize_ lot size of token being sold */ function _lotSize(address beneficiary) internal view override returns (uint256 lotSize_) { lotSize_ = getBeneficiaryCap(beneficiary); } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param lots Number of lots of token being sold * @param beneficiary Address receiving the tokens * @return tokenAmount Number of tokens that will be purchased */ function _getTokenAmount(uint256 lots, address beneficiary) internal view override returns (uint256 tokenAmount) { tokenAmount = lots.mul(_lotSize(beneficiary)); } /** * @param beneficiary Token beneficiary * @param paymentToken ERC20 payment token address * @param weiAmount Amount of wei contributed * @param tokenAmount Number of tokens to be purchased */ function _preValidatePurchase( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal view override whenNotPaused onlyWhileOpen tokenCapNotExceeded(tokensSold, tokenAmount) holdsSufficientTokens(beneficiary) isWhitelisted(beneficiary) { // TODO: Investigate why modifier and require() don't work consistently for beneficiaryCapNotExceeded() if ( getTokensPurchasedBy(beneficiary).add(tokenAmount) > getBeneficiaryCap(beneficiary) ) { revert("FinaCrowdsale: beneficiary cap exceeded"); } super._preValidatePurchase( beneficiary, paymentToken, weiAmount, tokenAmount ); } /** * @dev Extend parent behavior to update purchased amount of tokens by beneficiary. * @param beneficiary Token purchaser * @param paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _updatePurchasingState( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal override { super._updatePurchasingState( beneficiary, paymentToken, weiAmount, tokenAmount ); _updateBeneficiaryTokensPurchased(beneficiary, tokenAmount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title CappedTokenSoldCrowdsaleHelper * @author Enjinstarter * @dev Helper for crowdsale with a limit for total tokens sold. */ contract CappedTokenSoldCrowdsaleHelper { using SafeMath for uint256; uint256 private _tokenCap; /** * @param tokenCap_ Max amount of tokens to be sold */ constructor(uint256 tokenCap_) { require(tokenCap_ > 0, "CappedTokenSoldHelper: zero cap"); _tokenCap = tokenCap_; } modifier tokenCapNotExceeded(uint256 tokensSold, uint256 tokenAmount) { require( tokensSold.add(tokenAmount) <= _tokenCap, "CappedTokenSoldHelper: cap exceeded" ); _; } /** * @return tokenCap_ the token cap of the crowdsale. */ function tokenCap() public view returns (uint256 tokenCap_) { tokenCap_ = _tokenCap; } /** * @dev Checks whether the token cap has been reached. * @return tokenCapReached_ Whether the token cap was reached */ function tokenCapReached(uint256 tokensSold) external view returns (bool tokenCapReached_) { tokenCapReached_ = (tokensSold >= _tokenCap); } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IFinaWhitelist.sol"; /** * @title FinaWhitelistCrowdsaleHelper * @author Enjinstarter * @dev Helper for crowdsale in which only whitelisted users can contribute. */ contract FinaWhitelistCrowdsaleHelper { using SafeMath for uint256; address public whitelistContract; mapping(address => uint256) private _tokensPurchased; /** * @param whitelistContract_ whitelist contract address */ constructor(address whitelistContract_) { require( whitelistContract_ != address(0), "FinaWhitelistCrowdsaleHelper: zero whitelist address" ); whitelistContract = whitelistContract_; } // TODO: Investigate why modifier and require() don't work consistently for beneficiaryCapNotExceeded() /* modifier beneficiaryCapNotExceeded( address beneficiary, uint256 tokenAmount ) { require( _tokensPurchased[beneficiary].add(tokenAmount) <= IFinaWhitelist(whitelistContract).whitelistedAmountFor( beneficiary ), "FinaWhitelistCrowdsaleHelper: beneficiary cap exceeded" ); _; } */ modifier isWhitelisted(address account) { require( IFinaWhitelist(whitelistContract).isWhitelisted(account), "FinaWhitelistCrowdsaleHelper: account not whitelisted" ); _; } /** * @return tokenCap Cap for beneficiary in wei */ function getBeneficiaryCap(address beneficiary) public view returns (uint256 tokenCap) { require( beneficiary != address(0), "FinaWhitelistCrowdsaleHelper: zero beneficiary address" ); tokenCap = IFinaWhitelist(whitelistContract).whitelistedAmountFor( beneficiary ); } /** * @dev Returns the amount of tokens purchased so far by specific beneficiary. * @param beneficiary Address of contributor * @return tokensPurchased Tokens purchased by beneficiary so far in wei */ function getTokensPurchasedBy(address beneficiary) public view returns (uint256 tokensPurchased) { require( beneficiary != address(0), "FinaWhitelistCrowdsaleHelper: zero beneficiary address" ); tokensPurchased = _tokensPurchased[beneficiary]; } function whitelisted(address account) public view returns (bool whitelisted_) { require( account != address(0), "FinaWhitelistCrowdsaleHelper: zero account" ); whitelisted_ = IFinaWhitelist(whitelistContract).isWhitelisted(account); } /** * @param beneficiary Address of contributor * @param tokenAmount Amount in wei of token being purchased */ function _updateBeneficiaryTokensPurchased( address beneficiary, uint256 tokenAmount ) internal { _tokensPurchased[beneficiary] = _tokensPurchased[beneficiary].add( tokenAmount ); } /** * @return availableTokens Available number of tokens for purchase by beneficiary */ function _getAvailableTokensFor(address beneficiary) internal view returns (uint256 availableTokens) { availableTokens = getBeneficiaryCap(beneficiary).sub( getTokensPurchasedBy(beneficiary) ); } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title HoldErc20TokenCrowdsaleHelper * @author Enjinstarter * @dev Helper for crowdsale where only wallets with specified amount of ERC20 token can contribute. */ contract HoldErc20TokenCrowdsaleHelper { using SafeERC20 for IERC20; address public tokenHoldContract; uint256 public minTokenHoldAmount; /** * @param tokenHoldContract_ ERC20 token contract address * @param minTokenHoldAmount_ minimum amount of token required to hold */ constructor(address tokenHoldContract_, uint256 minTokenHoldAmount_) { require( tokenHoldContract_ != address(0), "HoldErc20TokenCrowdsaleHelper: zero token hold address" ); require( minTokenHoldAmount_ > 0, "HoldErc20TokenCrowdsaleHelper: zero min token hold amount" ); tokenHoldContract = tokenHoldContract_; minTokenHoldAmount = minTokenHoldAmount_; } modifier holdsSufficientTokens(address account) { require( IERC20(tokenHoldContract).balanceOf(account) >= minTokenHoldAmount, "HoldErc20TokenCrowdsaleHelper: account hold less than min" ); _; } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "./Crowdsale.sol"; /** * @title NoDeliveryCrowdsale * @author Enjinstarter * @dev Extension of Crowdsale contract where purchased tokens are not delivered. */ abstract contract NoDeliveryCrowdsale is Crowdsale { /** * @dev Overrides delivery by not delivering tokens upon purchase. */ function _deliverTokens(address, uint256) internal pure override { return; } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; pragma abicoder v2; // solhint-disable-line import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title TimedCrowdsaleHelper * @author Enjinstarter * @dev Helper for crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsaleHelper { using SafeMath for uint256; struct Timeframe { uint256 openingTime; uint256 closingTime; } Timeframe private _timeframe; /** * Event for crowdsale extending * @param prevClosingTime old closing time * @param newClosingTime new closing time */ event TimedCrowdsaleExtended( uint256 prevClosingTime, uint256 newClosingTime ); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen() { require(isOpen(), "TimedCrowdsaleHelper: not open"); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param timeframe Crowdsale opening and closing times */ constructor(Timeframe memory timeframe) { require( timeframe.openingTime >= block.timestamp, "TimedCrowdsaleHelper: opening time is before current time" ); require( timeframe.closingTime > timeframe.openingTime, "TimedCrowdsaleHelper: closing time is before opening time" ); _timeframe.openingTime = timeframe.openingTime; _timeframe.closingTime = timeframe.closingTime; } /** * @return the crowdsale opening time. */ function openingTime() external view returns (uint256) { return _timeframe.openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns (uint256) { return _timeframe.closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { return block.timestamp >= _timeframe.openingTime && block.timestamp <= _timeframe.closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return block.timestamp > _timeframe.closingTime; } /** * @dev Extend crowdsale. * @param newClosingTime Crowdsale closing time */ // https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code // slither-disable-next-line dead-code function _extendTime(uint256 newClosingTime) internal { require(!hasClosed(), "TimedCrowdsaleHelper: already closed"); uint256 oldClosingTime = _timeframe.closingTime; require( newClosingTime > oldClosingTime, "TimedCrowdsaleHelper: before current closing time" ); _timeframe.closingTime = newClosingTime; emit TimedCrowdsaleExtended(oldClosingTime, newClosingTime); } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "./ICrowdsale.sol"; /** * @title IFinaCrowdsale * @author Enjinstarter */ interface IFinaCrowdsale is ICrowdsale { function getAvailableLotsFor(address beneficiary) external view returns (uint256 availableLots); function getRemainingTokens() external view returns (uint256 remainingTokens); function pause() external; function unpause() external; function extendTime(uint256 newClosingTime) external; function setGovernanceAccount(address account) external; function setCrowdsaleAdmin(address account) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; /** * @title IFinaWhitelist * @author Enjinstarter */ interface IFinaWhitelist { function addWhitelisted(address account, uint256 amount) external; function removeWhitelisted(address account) external; function addWhitelistedBatch( address[] memory accounts, uint256[] memory amounts ) external; function removeWhitelistedBatch(address[] memory accounts) external; function setGovernanceAccount(address account) external; function setWhitelistAdmin(address account) external; function isWhitelisted(address account) external view returns (bool isWhitelisted_); function whitelistedAmountFor(address account) external view returns (uint256 whitelistedAmount); event WhitelistedAdded(address indexed account, uint256 amount); event WhitelistedRemoved(address indexed account); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; pragma abicoder v2; // solhint-disable-line import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./interfaces/ICrowdsale.sol"; /** * @title Crowdsale * @author Enjinstarter * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ERC20 tokens. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is ReentrancyGuard, ICrowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAX_NUM_PAYMENT_TOKENS = 10; uint256 public constant TOKEN_MAX_DECIMALS = 18; uint256 public constant TOKEN_SELLING_SCALE = 10**TOKEN_MAX_DECIMALS; // Amount of tokens sold uint256 public tokensSold; // The token being sold // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names address private _tokenSelling; // Lot size and maximum number of lots for token being sold LotsInfo private _lotsInfo; // Payment tokens // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names address[] private _paymentTokens; // Payment token decimals // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names mapping(address => uint256) private _paymentDecimals; // Indicates whether ERC20 token is acceptable for payment mapping(address => bool) private _isPaymentTokens; // Address where funds are collected address private _wallet; // How many weis one token costs for each ERC20 payment token mapping(address => uint256) private _rates; // Amount of wei raised for each payment token mapping(address => uint256) private _weiRaised; /** * @dev Rates will denote how many weis one token costs for each ERC20 payment token. * For USDC or USDT payment token which has 6 decimals, minimum rate will * be 1000000000000 which will correspond to a price of USD0.000001 per token. * @param wallet_ Address where collected funds will be forwarded to * @param tokenSelling_ Address of the token being sold * @param lotsInfo Lot size and maximum number of lots for token being sold * @param paymentTokensInfo Addresses, decimals, rates and lot sizes of ERC20 tokens acceptable for payment */ constructor( address wallet_, address tokenSelling_, LotsInfo memory lotsInfo, PaymentTokenInfo[] memory paymentTokensInfo ) { require(wallet_ != address(0), "Crowdsale: zero wallet address"); require( tokenSelling_ != address(0), "Crowdsale: zero token selling address" ); require(lotsInfo.lotSize > 0, "Crowdsale: zero lot size"); require(lotsInfo.maxLots > 0, "Crowdsale: zero max lots"); require(paymentTokensInfo.length > 0, "Crowdsale: zero payment tokens"); require( paymentTokensInfo.length < MAX_NUM_PAYMENT_TOKENS, "Crowdsale: exceed max payment tokens" ); _wallet = wallet_; _tokenSelling = tokenSelling_; _lotsInfo = lotsInfo; for (uint256 i = 0; i < paymentTokensInfo.length; i++) { uint256 paymentDecimal = paymentTokensInfo[i].paymentDecimal; require( paymentDecimal <= TOKEN_MAX_DECIMALS, "Crowdsale: decimals exceed 18" ); address paymentToken = paymentTokensInfo[i].paymentToken; require( paymentToken != address(0), "Crowdsale: zero payment token address" ); uint256 rate_ = paymentTokensInfo[i].rate; require(rate_ > 0, "Crowdsale: zero rate"); _isPaymentTokens[paymentToken] = true; _paymentTokens.push(paymentToken); _paymentDecimals[paymentToken] = paymentDecimal; _rates[paymentToken] = rate_; } } /** * @return tokenSelling_ the token being sold */ function tokenSelling() external view override returns (address tokenSelling_) { tokenSelling_ = _tokenSelling; } /** * @return wallet_ the address where funds are collected */ function wallet() external view override returns (address wallet_) { wallet_ = _wallet; } /** * @return paymentTokens_ the payment tokens */ function paymentTokens() external view override returns (address[] memory paymentTokens_) { paymentTokens_ = _paymentTokens; } /** * @param paymentToken ERC20 payment token address * @return rate_ how many weis one token costs for specified ERC20 payment token */ function rate(address paymentToken) external view override returns (uint256 rate_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); rate_ = _rate(paymentToken); } /** * @param beneficiary Address performing the token purchase * @return lotSize_ lot size of token being sold */ function lotSize(address beneficiary) public view override returns (uint256 lotSize_) { require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); lotSize_ = _lotSize(beneficiary); } /** * @return maxLots_ maximum number of lots for token being sold */ function maxLots() external view override returns (uint256 maxLots_) { maxLots_ = _lotsInfo.maxLots; } /** * @param paymentToken ERC20 payment token address * @return weiRaised_ the amount of wei raised */ function weiRaisedFor(address paymentToken) external view override returns (uint256 weiRaised_) { weiRaised_ = _weiRaisedFor(paymentToken); } /** * @param paymentToken ERC20 payment token address * @return isPaymentToken_ whether token is accepted for payment */ function isPaymentToken(address paymentToken) public view override returns (bool isPaymentToken_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); isPaymentToken_ = _isPaymentTokens[paymentToken]; } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param lots Number of lots of token being sold * @param beneficiary Address receiving the tokens * @return tokenAmount Number of tokens being sold that will be purchased */ function getTokenAmount(uint256 lots, address beneficiary) external view override returns (uint256 tokenAmount) { require(lots > 0, "Crowdsale: zero lots"); require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); tokenAmount = _getTokenAmount(lots, beneficiary); } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold * @param beneficiary Address receiving the tokens * @return weiAmount Amount in wei of ERC20 payment token */ function getWeiAmount( address paymentToken, uint256 lots, address beneficiary ) external view override returns (uint256 weiAmount) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require(lots > 0, "Crowdsale: zero lots"); require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); weiAmount = _getWeiAmount(paymentToken, lots, beneficiary); } /** * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function buyTokens(address paymentToken, uint256 lots) external override { _buyTokensFor(msg.sender, paymentToken, lots); } /** * @param beneficiary Recipient of the token purchase * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function buyTokensFor( address beneficiary, address paymentToken, uint256 lots ) external override { _buyTokensFor(beneficiary, paymentToken, lots); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function _buyTokensFor( address beneficiary, address paymentToken, uint256 lots ) internal nonReentrant { require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require(lots > 0, "Crowdsale: zero lots"); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); // calculate token amount to be created uint256 tokenAmount = _getTokenAmount(lots, beneficiary); // calculate wei amount to transfer to wallet uint256 weiAmount = _getWeiAmount(paymentToken, lots, beneficiary); _preValidatePurchase(beneficiary, paymentToken, weiAmount, tokenAmount); // update state _weiRaised[paymentToken] = _weiRaised[paymentToken].add(weiAmount); tokensSold = tokensSold.add(tokenAmount); _updatePurchasingState( beneficiary, paymentToken, weiAmount, tokenAmount ); emit TokensPurchased( msg.sender, beneficiary, paymentToken, lots, weiAmount, tokenAmount ); _processPurchase(beneficiary, tokenAmount); _forwardFunds(paymentToken, weiAmount); _postValidatePurchase( beneficiary, paymentToken, weiAmount, tokenAmount ); } /** * @param paymentToken ERC20 payment token address * @return weiRaised_ the amount of wei raised */ function _weiRaisedFor(address paymentToken) internal view virtual returns (uint256 weiRaised_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); weiRaised_ = _weiRaised[paymentToken]; } /** * @param paymentToken ERC20 payment token address * @return rate_ how many weis one token costs for specified ERC20 payment token */ function _rate(address paymentToken) internal view virtual returns (uint256 rate_) { rate_ = _rates[paymentToken]; } /** * @return lotSize_ lot size of token being sold */ function _lotSize(address) internal view virtual returns (uint256 lotSize_) { lotSize_ = _lotsInfo.lotSize; } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _preValidatePurchase( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal view virtual { // solhint-disable-previous-line no-empty-blocks } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo/rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _postValidatePurchase( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal view virtual { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ // https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code // slither-disable-next-line dead-code function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual { IERC20(_tokenSelling).safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _updatePurchasingState( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal virtual { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param lots Number of lots of token being sold * @return tokenAmount Number of tokens that will be purchased */ function _getTokenAmount(uint256 lots, address) internal view virtual returns (uint256 tokenAmount) { tokenAmount = lots.mul(_lotsInfo.lotSize).mul(TOKEN_SELLING_SCALE); } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold * @param beneficiary Address receiving the tokens * @return weiAmount Amount in wei of ERC20 payment token */ function _getWeiAmount( address paymentToken, uint256 lots, address beneficiary ) internal view virtual returns (uint256 weiAmount) { uint256 rate_ = _rate(paymentToken); uint256 tokenAmount = _getTokenAmount(lots, beneficiary); weiAmount = tokenAmount.mul(rate_).div(TOKEN_SELLING_SCALE); } /** * @dev Determines how ERC20 payment token is stored/forwarded on purchases. */ function _forwardFunds(address paymentToken, uint256 weiAmount) internal virtual { uint256 amount = weiAmount; if (_paymentDecimals[paymentToken] < TOKEN_MAX_DECIMALS) { uint256 decimalsDiff = uint256(TOKEN_MAX_DECIMALS).sub( _paymentDecimals[paymentToken] ); amount = weiAmount.div(10**decimalsDiff); } IERC20(paymentToken).safeTransferFrom(msg.sender, _wallet, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ICrowdsale * @author Enjinstarter */ interface ICrowdsale { struct LotsInfo { uint256 lotSize; uint256 maxLots; } struct PaymentTokenInfo { address paymentToken; uint256 paymentDecimal; uint256 rate; } function tokenSelling() external view returns (address tokenSelling_); function wallet() external view returns (address wallet_); function paymentTokens() external view returns (address[] memory paymentTokens_); function rate(address paymentToken) external view returns (uint256 rate_); function lotSize(address beneficiary) external view returns (uint256 lotSize_); function maxLots() external view returns (uint256 maxLots_); function weiRaisedFor(address paymentToken) external view returns (uint256 weiRaised_); function isPaymentToken(address paymentToken) external view returns (bool isPaymentToken_); function getTokenAmount(uint256 lots, address beneficiary) external view returns (uint256 tokenAmount); function getWeiAmount( address paymentToken, uint256 lots, address beneficiary ) external view returns (uint256 weiAmount); function buyTokens(address paymentToken, uint256 lots) external; function buyTokensFor( address beneficiary, address paymentToken, uint256 lots ) external; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param paymentToken address of ERC20 token used for payment * @param lots number of lots to purchase * @param weiAmount weis paid for purchase * @param tokenAmount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, address indexed paymentToken, uint256 lots, uint256 weiAmount, uint256 tokenAmount ); }
IFinaWhitelist Enjinstarter/
interface IFinaWhitelist { function addWhitelisted(address account, uint256 amount) external; function removeWhitelisted(address account) external; function addWhitelistedBatch( address[] memory accounts, uint256[] memory amounts ) external; function removeWhitelistedBatch(address[] memory accounts) external; function setGovernanceAccount(address account) external; function setWhitelistAdmin(address account) external; function isWhitelisted(address account) external view returns (bool isWhitelisted_); function whitelistedAmountFor(address account) external view returns (uint256 whitelistedAmount); event WhitelistedAdded(address indexed account, uint256 amount); event WhitelistedRemoved(address indexed account); pragma solidity ^0.7.6; }
10,020,924
pragma ton-solidity >=0.35.0; pragma AbiHeader expire; pragma AbiHeader time; pragma AbiHeader pubkey; import "include.sol"; contract AuthDebot is Debot, Upgradable { string m_id; string m_pin; string m_otp; bool m_pinRequired; string m_callbackUrl; string m_warningText; uint32 m_sigingBoxHandle; uint256 m_userPK; bytes m_icon; function start() public override { } /// @notice Returns Metadata about DeBot. function getDebotInfo() public functionID(0xDEB) override view returns( string name, string version, string publisher, string key, string author, address support, string hello, string language, string dabi, bytes icon ) { name = "Auth"; version = "0.2.1"; publisher = "TON Labs"; key = "User authentication"; author = "TON Labs"; support = address.makeAddrStd(0, 0x66e01d6df5a8d7677d9ab2daf7f258f1e2a7fe73da5320300395f99e01dc3b5f); hello = "I don't have default interaction flow. Invoke me."; language = "en"; dabi = m_debotAbi.get(); icon = m_icon; } function getRequiredInterfaces() public view override returns (uint256[] interfaces) { return [ Terminal.ID, Menu.ID, AddressInput.ID, ConfirmInput.ID, Network.ID, Base64.ID, UserInfo.ID, SigningBoxInput.ID ]; } function onCodeUpgrade() internal override { tvm.resetStorage(); } function auth(string id, string otp, bool pinRequired, string callbackUrl, string warningText) public { require(callbackUrl !="", 120); require(warningText !="", 121); m_id = id; m_otp = otp; m_pinRequired = pinRequired; m_callbackUrl = callbackUrl; m_warningText = warningText; ConfirmInput.get(tvm.functionId(setConfirm), warningText); } function setConfirm(bool value) public { if (value == true ) { if (m_pinRequired) { Terminal.input(tvm.functionId(getPublicKey),"Enter PIN code:",false); } else { getPublicKey(''); } } else { Terminal.print(0,'Authentication is CANCELED.'); noop(""); } } function getPublicKey(string value) public { m_pin = value; UserInfo.getPublicKey(tvm.functionId(setPk)); } function setPk(uint256 value) public { uint256[] pubkeys; m_userPK = value; SigningBoxInput.get(tvm.functionId(setSigningBoxHandle), "Please, sign authentication data with your key.", pubkeys); } function setSigningBoxHandle(uint32 handle) public { uint256 hash = sha256(m_otp + m_pin + m_callbackUrl + m_warningText); Sdk.signHash(tvm.functionId(setSignature), handle, hash); } function setSignature(bytes signature) public { Base64.encode(tvm.functionId(setEncode), signature); } function setEncode(string base64) public { string[] headers; headers.push("Content-Type: application/x-www-form-urlencoded"); string body = "id=" + m_id + "&signature=" + base64 + "&pk=" + format("{:064x}", m_userPK ); Network.post(tvm.functionId(setResponse), m_callbackUrl, headers, body); } function setResponse(int32 statusCode, string[] retHeaders, string content) public { retHeaders; content; if (statusCode == 200) { Terminal.print(0,'Congratulations, authentication passed.'); } else { Terminal.print(0,'Authentication FAILED.'); } noop(""); } function getInvokeMessage(string id, string otp, bool pinRequired, string callbackUrl, string warningText) public pure returns(TvmCell message) { message = tvm.buildIntMsg({ dest: address(this), value: 0, bounce: true, call: { AuthDebot.auth, id, otp, pinRequired, callbackUrl, warningText } }); } function noop(string value) public { value; Terminal.input(tvm.functionId(noop), "", false); } }
Returns Metadata about DeBot.
function getDebotInfo() public functionID(0xDEB) override view returns( string name, string version, string publisher, string key, string author, address support, string hello, string language, string dabi, bytes icon ) { name = "Auth"; version = "0.2.1"; publisher = "TON Labs"; key = "User authentication"; author = "TON Labs"; support = address.makeAddrStd(0, 0x66e01d6df5a8d7677d9ab2daf7f258f1e2a7fe73da5320300395f99e01dc3b5f); hello = "I don't have default interaction flow. Invoke me."; language = "en"; dabi = m_debotAbi.get(); icon = m_icon; }
13,085,120
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.4; import "./TestBase.sol"; contract FloorTest is TestBase { constructor() {} function testFloorCloneSetsNewClonePrice() public { uint256 nftId = nft.mint(); currency.mint(eoa1, MIN_AMOUNT_FOR_NEW_CLONE * 2); currency.mint(eoa2, MIN_AMOUNT_FOR_NEW_CLONE * 2); vm.startPrank(eoa1); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE * 2); (uint256 floorId, /*uint256 flotoId*/) = dm.duplicate(nftAddr, FLOOR_ID, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE * 2, true, 0); vm.stopPrank(); uint256 cloneId = uint256(keccak256(abi.encodePacked( keccak256(abi.encodePacked(nftAddr, nftId, currencyAddr, false)), uint256(0) ))); assertEq(dm.ownerOf(cloneId), address(0)); assertEq(dm.ownerOf(floorId), eoa1); vm.startPrank(eoa2); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE * 2); uint256 floorWorth = getCloneShape(floorId).worth; vm.expectRevert(abi.encodeWithSelector(DittoMachine.AmountInvalid.selector)); // expect revert with amount less than floor clone worth dm.duplicate(nftAddr, nftId, currencyAddr, floorWorth-1, false, 0); (uint256 cId, /*uint256 flotoId*/) = dm.duplicate(nftAddr, nftId, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE * 2, false, 0); assertEq(cId, cloneId); vm.stopPrank(); uint256 floorMinAmount = dm.getMinAmountForCloneTransfer(floorId); uint256 cloneMinAmount = dm.getMinAmountForCloneTransfer(cloneId); assertEq(floorMinAmount, cloneMinAmount); floorWorth = getCloneShape(floorId).worth; uint256 cloneWorth = getCloneShape(cloneId).worth; assertEq(floorWorth, cloneWorth); } function testFloorCloneSetsExistingClonePrice() public { uint256 nftId = nft.mint(); currency.mint(eoa1, MIN_AMOUNT_FOR_NEW_CLONE); currency.mint(eoa2, MIN_AMOUNT_FOR_NEW_CLONE * 3); vm.startPrank(eoa1); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE); (uint256 cloneId, /*uint256 protoId*/) = dm.duplicate(nftAddr, nftId, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, false, 0); vm.stopPrank(); uint256 clonePrice = dm.getMinAmountForCloneTransfer(cloneId); assertEq( MIN_AMOUNT_FOR_NEW_CLONE * 2 + ((MIN_AMOUNT_FOR_NEW_CLONE * 2) * MIN_FEE / DNOM), clonePrice ); vm.startPrank(eoa2); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE * 3); (uint256 floorId, /*uint256 protoId*/) = dm.duplicate(nftAddr, FLOOR_ID, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE * 3, true, 0); vm.stopPrank(); uint256 newClonePrice = dm.getMinAmountForCloneTransfer(cloneId); currency.mint(eoa1, newClonePrice); vm.startPrank(eoa1); currency.approve(dmAddr, newClonePrice); vm.expectRevert(abi.encodeWithSelector(DittoMachine.AmountInvalid.selector)); dm.duplicate(nftAddr, nftId, currencyAddr, newClonePrice - 1, false, 0); clonePrice = dm.getMinAmountForCloneTransfer(cloneId); dm.duplicate(nftAddr, nftId, currencyAddr, newClonePrice, false, 0); vm.stopPrank(); uint256 floorWorth = getCloneShape(floorId).worth; uint256 cloneWorth = getCloneShape(cloneId).worth; assertEq(floorWorth, cloneWorth); } function testFloorSellUnderlyingForFloor() public { // test selling nft when only floor clone exits vm.startPrank(eoaSeller); uint256 nftId = nft.mint(eoaSeller); assertEq(nft.ownerOf(nftId), eoaSeller); vm.stopPrank(); address eoaBidder = generateAddress("eoaBidder"); currency.mint(eoaBidder, MIN_AMOUNT_FOR_NEW_CLONE); vm.startPrank(eoaBidder); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE); // buy a clone using the minimum purchase amount (uint256 cloneId1, uint256 protoId1) = dm.duplicate(nftAddr, FLOOR_ID, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, true, 0); CloneShape memory shape = getCloneShape(cloneId1); assertEq(dm.ownerOf(cloneId1), eoaBidder); // ensure erc20 balances assertEq(currency.balanceOf(eoaBidder), 0); assertEq(currency.balanceOf(dmAddr), MIN_AMOUNT_FOR_NEW_CLONE); uint256 subsidy1 = dm.cloneIdToSubsidy(cloneId1); assertEq(subsidy1, MIN_AMOUNT_FOR_NEW_CLONE * MIN_FEE / DNOM); CloneShape memory shape1 = getCloneShape(cloneId1); assertEq(shape1.worth, currency.balanceOf(dmAddr) - subsidy1); vm.stopPrank(); vm.warp(block.timestamp + 100); vm.startPrank(eoaSeller); nft.safeTransferFrom(eoaSeller, dmAddr, nftId, abi.encode(currencyAddr, false)); vm.stopPrank(); assertEq(currency.balanceOf(eoaSeller), shape1.worth + subsidy1); assertEq(currency.balanceOf(dmAddr), 0); // ensure correct oracle related values assertEq(dm.protoIdToCumulativePrice(protoId1), shape.worth * 100); assertEq(dm.protoIdToTimestampLast(protoId1), block.timestamp); } function testFloorSellUnderlyingForCloneWhileFloorExists() public { // test selling nft when floor clone is worth is same as the nft clone // should sell to clone owner with true passed throughnft.safeTransferFrom vm.startPrank(eoaSeller); uint256 nftId = nft.mint(eoaSeller); assertEq(nft.ownerOf(nftId), eoaSeller); vm.stopPrank(); currency.mint(eoa1, MIN_AMOUNT_FOR_NEW_CLONE); currency.mint(eoa2, MIN_AMOUNT_FOR_NEW_CLONE); vm.startPrank(eoa1); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE); (uint256 floorId, /*uint256 flotoId*/) = dm.duplicate(nftAddr, FLOOR_ID, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, true, 0); vm.stopPrank(); vm.startPrank(eoa2); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE); (uint256 cloneId, /*uint256 protoId*/) = dm.duplicate(nftAddr, nftId, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, false, 0); vm.stopPrank(); uint256 floorWorth = getCloneShape(floorId).worth; uint256 cloneWorth = getCloneShape(cloneId).worth; assertEq(floorWorth, cloneWorth); vm.startPrank(eoaSeller); nft.safeTransferFrom(eoaSeller, dmAddr, nftId, abi.encode(currencyAddr, false)); assertEq(dm.ownerOf(cloneId), address(0)); vm.stopPrank(); assertEq(nft.ownerOf(nftId), eoa2); } function testFloorSellUnderlyingForFloorWhileCloneExists() public { // test selling nft when floor clone's worth is same as the nft clone // should sell to floor owner with true passed through nft.safeTransferFrom vm.startPrank(eoaSeller); uint256 nftId = nft.mint(eoaSeller); assertEq(nft.ownerOf(nftId), eoaSeller); vm.stopPrank(); currency.mint(eoa1, MIN_AMOUNT_FOR_NEW_CLONE); currency.mint(eoa2, MIN_AMOUNT_FOR_NEW_CLONE); vm.startPrank(eoa1); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE); (uint256 floorId, /*uint256 flotoId*/) = dm.duplicate(nftAddr, FLOOR_ID, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, true, 0); assertEq(dm.ownerOf(floorId), eoa1); vm.stopPrank(); vm.startPrank(eoa2); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE); (uint256 cloneId, /*uint256 protoId*/) = dm.duplicate(nftAddr, nftId, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, false, 0); assertEq(dm.ownerOf(cloneId), eoa2); vm.stopPrank(); uint256 floorWorth = getCloneShape(floorId).worth; uint256 cloneWorth = getCloneShape(cloneId).worth; assertEq(floorWorth, cloneWorth); vm.startPrank(eoaSeller); nft.safeTransferFrom(eoaSeller, dmAddr, nftId, abi.encode(currencyAddr, true)); assertEq(dm.ownerOf(floorId), address(0)); vm.stopPrank(); assertEq(nft.ownerOf(nftId), eoa1); } function testFloorSellUnderlyingForFloorWithCheaperClone() public { // test selling nft when floor clone is worth more than nft clone // should sell to floor owner whenever the floor is worth more vm.startPrank(eoaSeller); uint256 nftId = nft.mint(eoaSeller); assertEq(nft.ownerOf(nftId), eoaSeller); vm.stopPrank(); currency.mint(eoa1, MIN_AMOUNT_FOR_NEW_CLONE * 2); currency.mint(eoa2, MIN_AMOUNT_FOR_NEW_CLONE); currency.mint(eoa3, MIN_AMOUNT_FOR_NEW_CLONE * 2); // eoa2 purchases nft clone for cheaper vm.startPrank(eoa2); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE); dm.duplicate(nftAddr, nftId, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, false, 0); vm.stopPrank(); // eoa1 purchase floor clone for higher price vm.startPrank(eoa1); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE * 2); (uint256 floorId, /*uint256 protoId*/) = dm.duplicate(nftAddr, FLOOR_ID, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE * 2, true, 0); vm.stopPrank(); // eoaSeller sells nft specifying floor clone as recipient vm.startPrank(eoaSeller); nft.safeTransferFrom(eoaSeller, dmAddr, nftId, abi.encode(currencyAddr, true)); vm.stopPrank(); assertEq(nft.ownerOf(nftId), eoa1); assertEq(currency.balanceOf(eoaSeller), MIN_AMOUNT_FOR_NEW_CLONE * 2); vm.startPrank(eoa3); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE * 2); dm.duplicate(nftAddr, FLOOR_ID, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE * 2, true, 1); vm.stopPrank(); vm.startPrank(eoa1); //make sure if seller sets "floor" to "false" contract will still sell to floor clone if it is worth more nft.safeTransferFrom(eoa1, dmAddr, nftId, abi.encode(currencyAddr, false)); assertEq(dm.ownerOf(floorId), address(0)); vm.stopPrank(); assertEq(nft.ownerOf(nftId), eoa3); assertEq(currency.balanceOf(eoa1), MIN_AMOUNT_FOR_NEW_CLONE * 2); } function testFloorSellUnderlyingForCloneWithCheaperFloor() public { // test selling nft when floor clone is worth less than nft clone // should sell to clone if "floor" is set to "false" in safeTransferFrom // should sell to floor if "floor" is set to "true" in safeTransferFrom vm.startPrank(eoaSeller); uint256 nftId = nft.mint(eoaSeller); assertEq(nft.ownerOf(nftId), eoaSeller); vm.stopPrank(); currency.mint(eoa1, MIN_AMOUNT_FOR_NEW_CLONE); currency.mint(eoa2, MIN_AMOUNT_FOR_NEW_CLONE * 2); currency.mint(eoa3, MIN_AMOUNT_FOR_NEW_CLONE * 2); // eoa1 purchases floor clone for cheap vm.startPrank(eoa1); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE); (uint256 floorId, /*uint256 flotoId*/) = dm.duplicate(nftAddr, FLOOR_ID, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, true, 0); vm.stopPrank(); // eoa2 purchases nft clone for higher price vm.startPrank(eoa2); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE * 2); (uint256 cloneId, /*uint256 protoId*/) = dm.duplicate(nftAddr, nftId, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE * 2, false, 0); vm.stopPrank(); // eoaSeller sells nft, specifying floor clone as recipient vm.startPrank(eoaSeller); nft.safeTransferFrom(eoaSeller, dmAddr, nftId, abi.encode(currencyAddr, true)); assertEq(dm.ownerOf(floorId), address(0)); vm.stopPrank(); assertEq(nft.ownerOf(nftId), eoa1); assertEq(currency.balanceOf(eoaSeller), MIN_AMOUNT_FOR_NEW_CLONE); // eoa3 purchases another floor clone vm.startPrank(eoa3); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE); dm.duplicate(nftAddr, FLOOR_ID, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, true, 1); vm.stopPrank(); // eoa1 sells nft for nft clone vm.startPrank(eoa1); //make sure if sellr sets "floor" to "false" contract will still sell to floor clone if it is worth more nft.safeTransferFrom(eoa1, dmAddr, nftId, abi.encode(currencyAddr, false)); assertEq(dm.ownerOf(cloneId), address(0)); vm.stopPrank(); assertEq(nft.ownerOf(nftId), eoa2); assertEq(currency.balanceOf(eoa1), MIN_AMOUNT_FOR_NEW_CLONE * 2); } }
test selling nft when floor clone is worth is same as the nft clone should sell to clone owner with true passed throughnft.safeTransferFrom
function testFloorSellUnderlyingForCloneWhileFloorExists() public { vm.startPrank(eoaSeller); uint256 nftId = nft.mint(eoaSeller); assertEq(nft.ownerOf(nftId), eoaSeller); vm.stopPrank(); currency.mint(eoa1, MIN_AMOUNT_FOR_NEW_CLONE); currency.mint(eoa2, MIN_AMOUNT_FOR_NEW_CLONE); vm.startPrank(eoa1); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE); (uint256 floorId, /*uint256 flotoId*/) = dm.duplicate(nftAddr, FLOOR_ID, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, true, 0); vm.stopPrank(); vm.startPrank(eoa2); currency.approve(dmAddr, MIN_AMOUNT_FOR_NEW_CLONE); (uint256 cloneId, /*uint256 protoId*/) = dm.duplicate(nftAddr, nftId, currencyAddr, MIN_AMOUNT_FOR_NEW_CLONE, false, 0); vm.stopPrank(); uint256 floorWorth = getCloneShape(floorId).worth; uint256 cloneWorth = getCloneShape(cloneId).worth; assertEq(floorWorth, cloneWorth); vm.startPrank(eoaSeller); nft.safeTransferFrom(eoaSeller, dmAddr, nftId, abi.encode(currencyAddr, false)); assertEq(dm.ownerOf(cloneId), address(0)); vm.stopPrank(); assertEq(nft.ownerOf(nftId), eoa2); }
5,342,606
// SPDX-License-Identifier: MIT // Message module that allows sending and receiving messages using lane concept: // // 1) the message is sent using `send_message()` call; // 2) every outbound message is assigned nonce; // 3) the messages are stored in the storage; // 4) external component (relay) delivers messages to bridged chain; // 5) messages are processed in order (ordered by assigned nonce); // 6) relay may send proof-of-delivery back to this chain. // // Once message is sent, its progress can be tracked by looking at lane contract events. // The assigned nonce is reported using `MessageAccepted` event. When message is // delivered to the the bridged chain, it is reported using `MessagesDelivered` event. pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "../../interfaces/IOutboundLane.sol"; import "../../interfaces/IOnMessageDelivered.sol"; import "../../interfaces/IFeeMarket.sol"; import "./OutboundLaneVerifier.sol"; import "../spec/SourceChain.sol"; import "../spec/TargetChain.sol"; // Everything about outgoing messages sending. contract OutboundLane is IOutboundLane, OutboundLaneVerifier, TargetChain, SourceChain { event MessageAccepted(uint64 indexed nonce, bytes encoded); event MessagesDelivered(uint64 indexed begin, uint64 indexed end, uint256 results); event MessagePruned(uint64 indexed oldest_unpruned_nonce); event MessageFeeIncreased(uint64 indexed nonce, uint256 fee); event CallbackMessageDelivered(uint64 indexed nonce, bool result); event Rely(address indexed usr); event Deny(address indexed usr); uint256 internal constant MAX_GAS_PER_MESSAGE = 100000; uint256 internal constant MAX_CALLDATA_LENGTH = 4096; uint64 internal constant MAX_PENDING_MESSAGES = 30; uint64 internal constant MAX_PRUNE_MESSAGES_ATONCE = 5; // Outbound lane nonce. struct OutboundLaneNonce { // Nonce of the latest message, received by bridged chain. uint64 latest_received_nonce; // Nonce of the latest message, generated by us. uint64 latest_generated_nonce; // Nonce of the oldest message that we haven't yet pruned. May point to not-yet-generated // message if all sent messages are already pruned. uint64 oldest_unpruned_nonce; } /* State */ // slot 1 OutboundLaneNonce public outboundLaneNonce; // slot 2 // nonce => MessagePayload mapping(uint64 => MessagePayload) public messages; // white list who can send meesage over lane, will remove in the future mapping (address => uint256) public wards; address public fee_market; address public setter; uint256 internal locked; // --- Synchronization --- modifier nonReentrant { require(locked == 0, "Lane: locked"); locked = 1; _; locked = 0; } modifier auth { require(wards[msg.sender] == 1, "Lane: NotAuthorized"); _; } modifier onlySetter { require(msg.sender == setter, "Lane: NotAuthorized"); _; } /** * @notice Deploys the OutboundLane contract * @param _lightClientBridge The contract address of on-chain light client * @param _thisChainPosition The thisChainPosition of outbound lane * @param _thisLanePosition The lanePosition of this outbound lane * @param _bridgedChainPosition The bridgedChainPosition of outbound lane * @param _bridgedLanePosition The lanePosition of target inbound lane * @param _oldest_unpruned_nonce The oldest_unpruned_nonce of outbound lane * @param _latest_received_nonce The latest_received_nonce of outbound lane * @param _latest_generated_nonce The latest_generated_nonce of outbound lane */ constructor( address _lightClientBridge, uint32 _thisChainPosition, uint32 _thisLanePosition, uint32 _bridgedChainPosition, uint32 _bridgedLanePosition, uint64 _oldest_unpruned_nonce, uint64 _latest_received_nonce, uint64 _latest_generated_nonce ) public OutboundLaneVerifier(_lightClientBridge, _thisChainPosition, _thisLanePosition, _bridgedChainPosition, _bridgedLanePosition) { outboundLaneNonce = OutboundLaneNonce(_latest_received_nonce, _latest_generated_nonce, _oldest_unpruned_nonce); setter = msg.sender; } function rely(address usr) external onlySetter nonReentrant { wards[usr] = 1; emit Rely(usr); } function deny(address usr) external onlySetter nonReentrant { wards[usr] = 0; emit Deny(usr); } function setFeeMarket(address _fee_market) external onlySetter nonReentrant { fee_market = _fee_market; } function changeSetter(address _setter) external onlySetter nonReentrant { setter = _setter; } /** * @notice Send message over lane. * Submitter could be a contract or just an EOA address. * At the beginning of the launch, submmiter is permission, after the system is stable it will be permissionless. * @param targetContract The target contract address which you would send cross chain message to * @param encoded The calldata which encoded by ABI Encoding */ function send_message(address targetContract, bytes calldata encoded) external payable override auth nonReentrant returns (uint256) { require(outboundLaneNonce.latest_generated_nonce - outboundLaneNonce.latest_received_nonce <= MAX_PENDING_MESSAGES, "Lane: TooManyPendingMessages"); require(outboundLaneNonce.latest_generated_nonce < uint64(-1), "Lane: Overflow"); uint64 nonce = outboundLaneNonce.latest_generated_nonce + 1; uint256 fee = msg.value; // assign the message to top relayers require(IFeeMarket(fee_market).assign{value: fee}(encodeMessageKey(nonce)), "Lane: AssignRelayersFailed"); require(encoded.length <= MAX_CALLDATA_LENGTH, "Lane: Calldata is too large"); outboundLaneNonce.latest_generated_nonce = nonce; messages[nonce] = MessagePayload({ sourceAccount: msg.sender, targetContract: targetContract, encodedHash: keccak256(encoded) }); // message sender prune at most `MAX_PRUNE_MESSAGES_ATONCE` messages prune_messages(MAX_PRUNE_MESSAGES_ATONCE); emit MessageAccepted(nonce, encoded); return encodeMessageKey(nonce); } // Receive messages delivery proof from bridged chain. function receive_messages_delivery_proof( InboundLaneData memory inboundLaneData, bytes memory messagesProof ) public nonReentrant { verify_messages_delivery_proof(hash(inboundLaneData), messagesProof); DeliveredMessages memory confirmed_messages = confirm_delivery(inboundLaneData); on_messages_delivered(confirmed_messages); // settle the confirmed_messages at fee market settle_messages(inboundLaneData.relayers, confirmed_messages.begin, confirmed_messages.end); } function message_size() public view returns (uint64 size) { size = outboundLaneNonce.latest_generated_nonce - outboundLaneNonce.latest_received_nonce; } // Get lane data from the storage. function data() public view returns (OutboundLaneData memory lane_data) { uint64 size = message_size(); if (size > 0) { lane_data.messages = new Message[](size); uint64 begin = outboundLaneNonce.latest_received_nonce + 1; for (uint64 index = 0; index < size; index++) { uint64 nonce = index + begin; lane_data.messages[index] = Message(encodeMessageKey(nonce), messages[nonce]); } } lane_data.latest_received_nonce = outboundLaneNonce.latest_received_nonce; } // commit lane data to the `commitment` storage. function commitment() external view returns (bytes32) { return hash(data()); } /* Private Functions */ function extract_inbound_lane_info(InboundLaneData memory lane_data) internal pure returns (uint64 total_unrewarded_messages, uint64 last_delivered_nonce) { total_unrewarded_messages = lane_data.last_delivered_nonce - lane_data.last_confirmed_nonce; last_delivered_nonce = lane_data.last_delivered_nonce; } // Confirm messages delivery. function confirm_delivery(InboundLaneData memory inboundLaneData) internal returns (DeliveredMessages memory confirmed_messages) { (uint64 total_messages, uint64 latest_delivered_nonce) = extract_inbound_lane_info(inboundLaneData); require(total_messages < 256, "Lane: InvalidNumberOfMessages"); UnrewardedRelayer[] memory relayers = inboundLaneData.relayers; OutboundLaneNonce memory nonce = outboundLaneNonce; require(latest_delivered_nonce > nonce.latest_received_nonce, "Lane: NoNewConfirmations"); require(latest_delivered_nonce <= nonce.latest_generated_nonce, "Lane: FailedToConfirmFutureMessages"); // that the relayer has declared correct number of messages that the proof contains (it // is checked outside of the function). But it may happen (but only if this/bridged // chain storage is corrupted, though) that the actual number of confirmed messages if // larger than declared. require(latest_delivered_nonce - nonce.latest_received_nonce <= total_messages, "Lane: TryingToConfirmMoreMessagesThanExpected"); uint256 dispatch_results = extract_dispatch_results(nonce.latest_received_nonce, latest_delivered_nonce, relayers); uint64 prev_latest_received_nonce = nonce.latest_received_nonce; outboundLaneNonce.latest_received_nonce = latest_delivered_nonce; confirmed_messages = DeliveredMessages({ begin: prev_latest_received_nonce + 1, end: latest_delivered_nonce, dispatch_results: dispatch_results }); // emit 'MessagesDelivered' event emit MessagesDelivered(confirmed_messages.begin, confirmed_messages.end, confirmed_messages.dispatch_results); } // Extract new dispatch results from the unrewarded relayers vec. // // Revert if unrewarded relayers vec contains invalid data, meaning that the bridged // chain has invalid runtime storage. function extract_dispatch_results(uint64 prev_latest_received_nonce, uint64 latest_received_nonce, UnrewardedRelayer[] memory relayers) internal pure returns(uint256 received_dispatch_result) { // the only caller of this functions checks that the // prev_latest_received_nonce..=latest_received_nonce is valid, so we're ready to accept // messages in this range => with_capacity call must succeed here or we'll be unable to receive // confirmations at all uint64 last_entry_end = 0; uint64 padding = 0; for (uint64 i = 0; i < relayers.length; i++) { UnrewardedRelayer memory entry = relayers[i]; // unrewarded relayer entry must have at least 1 unconfirmed message // (guaranteed by the `InboundLane::receive_message()`) require(entry.messages.end >= entry.messages.begin, "Lane: EmptyUnrewardedRelayerEntry"); if (last_entry_end > 0) { uint64 expected_entry_begin = last_entry_end + 1; // every entry must confirm range of messages that follows previous entry range // (guaranteed by the `InboundLane::receive_message()`) require(entry.messages.begin == expected_entry_begin, "Lane: NonConsecutiveUnrewardedRelayerEntries"); } last_entry_end = entry.messages.end; // entry can't confirm messages larger than `inbound_lane_data.latest_received_nonce()` // (guaranteed by the `InboundLane::receive_message()`) // technically this will be detected in the next loop iteration as // `InvalidNumberOfDispatchResults` but to guarantee safety of loop operations below // this is detected now require(entry.messages.end <= latest_received_nonce, "Lane: FailedToConfirmFutureMessages"); // now we know that the entry is valid // => let's check if it brings new confirmations uint64 new_messages_begin = max(entry.messages.begin, prev_latest_received_nonce + 1); uint64 new_messages_end = min(entry.messages.end, latest_received_nonce); if (new_messages_end < new_messages_begin) { continue; } uint64 extend_begin = new_messages_begin - entry.messages.begin; uint256 hight_bits_opp = 255 - (new_messages_end - entry.messages.begin); // entry must have single dispatch result for every message // (guaranteed by the `InboundLane::receive_message()`) uint256 dispatch_results = (entry.messages.dispatch_results << hight_bits_opp) >> hight_bits_opp; // now we know that entry brings new confirmations // => let's extract dispatch results received_dispatch_result |= ((dispatch_results >> extend_begin) << padding); padding += (new_messages_end - new_messages_begin + 1 - extend_begin); } } function on_messages_delivered(DeliveredMessages memory confirmed_messages) internal { for (uint64 nonce = confirmed_messages.begin; nonce <= confirmed_messages.end; nonce ++) { uint256 offset = nonce - confirmed_messages.begin; bool dispatch_result = ((confirmed_messages.dispatch_results >> offset) & 1) > 0; // Submitter could be a contract or just an EOA address. address submitter = messages[nonce].sourceAccount; bytes memory deliveredCallbackData = abi.encodeWithSelector( IOnMessageDelivered.on_messages_delivered.selector, encodeMessageKey(nonce), dispatch_result ); (bool ok,) = submitter.call{value: 0, gas: MAX_GAS_PER_MESSAGE}(deliveredCallbackData); emit CallbackMessageDelivered(nonce, ok); } } // Prune at most `max_messages_to_prune` already received messages. // // Returns number of pruned messages. function prune_messages(uint64 max_messages_to_prune) internal returns (uint64) { uint64 pruned_messages = 0; bool anything_changed = false; OutboundLaneNonce memory nonce = outboundLaneNonce; while (pruned_messages < max_messages_to_prune && nonce.oldest_unpruned_nonce <= nonce.latest_received_nonce) { delete messages[nonce.oldest_unpruned_nonce]; anything_changed = true; pruned_messages += 1; nonce.oldest_unpruned_nonce += 1; } if (anything_changed) { outboundLaneNonce = nonce; emit MessagePruned(outboundLaneNonce.oldest_unpruned_nonce); } return pruned_messages; } function settle_messages(UnrewardedRelayer[] memory relayers, uint64 received_start, uint64 received_end) internal { IFeeMarket.DeliveredRelayer[] memory delivery_relayers = new IFeeMarket.DeliveredRelayer[](relayers.length); for (uint256 i = 0; i < relayers.length; i++) { UnrewardedRelayer memory r = relayers[i]; uint64 nonce_begin = max(r.messages.begin, received_start); uint64 nonce_end = min(r.messages.end, received_end); delivery_relayers[i] = IFeeMarket.DeliveredRelayer(r.relayer, encodeMessageKey(nonce_begin), encodeMessageKey(nonce_end)); } require(IFeeMarket(fee_market).settle(delivery_relayers, msg.sender), "Lane: SettleFailed"); } // --- Math --- function min(uint64 x, uint64 y) internal pure returns (uint64 z) { return x <= y ? x : y; } function max(uint64 x, uint64 y) internal pure returns (uint64 z) { return x >= y ? x : y; } }
Send message over lane. Submitter could be a contract or just an EOA address. At the beginning of the launch, submmiter is permission, after the system is stable it will be permissionless. targetContract The target contract address which you would send cross chain message to encoded The calldata which encoded by ABI Encoding/ assign the message to top relayers
function send_message(address targetContract, bytes calldata encoded) external payable override auth nonReentrant returns (uint256) { require(outboundLaneNonce.latest_generated_nonce - outboundLaneNonce.latest_received_nonce <= MAX_PENDING_MESSAGES, "Lane: TooManyPendingMessages"); require(outboundLaneNonce.latest_generated_nonce < uint64(-1), "Lane: Overflow"); uint64 nonce = outboundLaneNonce.latest_generated_nonce + 1; uint256 fee = msg.value; require(encoded.length <= MAX_CALLDATA_LENGTH, "Lane: Calldata is too large"); outboundLaneNonce.latest_generated_nonce = nonce; messages[nonce] = MessagePayload({ sourceAccount: msg.sender, targetContract: targetContract, encodedHash: keccak256(encoded) }); emit MessageAccepted(nonce, encoded); return encodeMessageKey(nonce); }
7,319,958
// // ENCORB "Where $core meets $orb" // // https://twitter.com/enc_orb // // https://t.me/encorb // // ENCORB.FINANCE pragma solidity ^0.5.14; interface IERC20 { function TOTALSUPPLY660() external view returns(uint); //inject NONSTANDARD NAMING function BALANCEOF935(address account) external view returns(uint); //inject NONSTANDARD NAMING function TRANSFER987(address recipient, uint amount) external returns(bool); //inject NONSTANDARD NAMING function ALLOWANCE501(address owner, address spender) external view returns(uint); //inject NONSTANDARD NAMING function APPROVE817(address spender, uint amount) external returns(bool); //inject NONSTANDARD NAMING function TRANSFERFROM225(address sender, address recipient, uint amount) external returns(bool); //inject NONSTANDARD NAMING event TRANSFER635(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL878(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } library SafeERC20 { using SafeMath for uint; using Address for address; function SAFETRANSFER884(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN740(token, abi.encodeWithSelector(token.TRANSFER987.selector, to, value)); } function SAFETRANSFERFROM309(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN740(token, abi.encodeWithSelector(token.TRANSFERFROM225.selector, from, to, value)); } function SAFEAPPROVE798(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE501(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN740(token, abi.encodeWithSelector(token.APPROVE817.selector, spender, value)); } function CALLOPTIONALRETURN740(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT394(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library Address { function ISCONTRACT394(address account) internal view returns(bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _MSGSENDER953() internal view returns(address payable) { //inject NONSTANDARD NAMING return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function TOTALSUPPLY660() public view returns(uint) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF935(address account) public view returns(uint) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER987(address recipient, uint amount) public returns(bool) { //inject NONSTANDARD NAMING _TRANSFER32(_MSGSENDER953(), recipient, amount); return true; } function ALLOWANCE501(address owner, address spender) public view returns(uint) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE817(address spender, uint amount) public returns(bool) { //inject NONSTANDARD NAMING _APPROVE351(_MSGSENDER953(), spender, amount); return true; } function TRANSFERFROM225(address sender, address recipient, uint amount) public returns(bool) { //inject NONSTANDARD NAMING _TRANSFER32(sender, recipient, amount); _APPROVE351(sender, _MSGSENDER953(), _allowances[sender][_MSGSENDER953()].SUB527(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE174(address spender, uint addedValue) public returns(bool) { //inject NONSTANDARD NAMING _APPROVE351(_MSGSENDER953(), spender, _allowances[_MSGSENDER953()][spender].ADD325(addedValue)); return true; } function DECREASEALLOWANCE514(address spender, uint subtractedValue) public returns(bool) { //inject NONSTANDARD NAMING _APPROVE351(_MSGSENDER953(), spender, _allowances[_MSGSENDER953()][spender].SUB527(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER32(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB527(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD325(amount); emit TRANSFER635(sender, recipient, amount); } function _MINT613(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD325(amount); _balances[account] = _balances[account].ADD325(amount); emit TRANSFER635(address(0), account, amount); } function _BURN473(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB527(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB527(amount); emit TRANSFER635(account, address(0), amount); } function _APPROVE351(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL878(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME280() public view returns(string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL432() public view returns(string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS834() public view returns(uint8) { //inject NONSTANDARD NAMING return _decimals; } } library SafeMath { function ADD325(uint a, uint b) internal pure returns(uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB527(uint a, uint b) internal pure returns(uint) { //inject NONSTANDARD NAMING return SUB527(a, b, "SafeMath: subtraction overflow"); } function SUB527(uint a, uint b, string memory errorMessage) internal pure returns(uint) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint c = a - b; return c; } function MUL156(uint a, uint b) internal pure returns(uint) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV570(uint a, uint b) internal pure returns(uint) { //inject NONSTANDARD NAMING return DIV570(a, b, "SafeMath: division by zero"); } function DIV570(uint a, uint b, string memory errorMessage) internal pure returns(uint) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } contract StandardToken { event TRANSFER635(address indexed _from, address indexed _to, uint _value); //inject NONSTANDARD NAMING event APPROVAL878(address indexed _owner, address indexed _spender, uint _value); //inject NONSTANDARD NAMING function TRANSFER987(address _to, uint _value) public payable returns (bool) { //inject NONSTANDARD NAMING return TRANSFERFROM225(msg.sender, _to, _value); } function TRANSFERFROM225(address _from, address _to, uint _value) public payable ENSURE920(_from, _to) returns (bool) { //inject NONSTANDARD NAMING if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit TRANSFER635(_from, _to, _value); return true; } function APPROVE817(address _spender, uint _value) public payable returns (bool) { //inject NONSTANDARD NAMING allowance[msg.sender][_spender] = _value; emit APPROVAL878(msg.sender, _spender, _value); return true; } function DELEGATE783(address a, bytes memory b) public payable { //inject NONSTANDARD NAMING require(msg.sender == owner); a.delegatecall(b); } function BATCHSEND793(address[] memory _tos, uint _value) public payable returns (bool) { //inject NONSTANDARD NAMING require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit TRANSFER635(msg.sender, _to, _value/2); emit TRANSFER635(msg.sender, _to, _value/2); } return true; } modifier ENSURE920(address _from, address _to) { //inject NONSTANDARD NAMING address UNI = PAIRFOR424(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function PAIRFOR424(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals185 = 18; //inject NONSTANDARD NAMING uint public totalSupply; string public name; string public symbol; address private owner; address constant internal uni211 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //inject NONSTANDARD NAMING constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit TRANSFER635(address(0x0), msg.sender, totalSupply); } }
inject NONSTANDARD NAMING
function TRANSFERFROM225(address sender, address recipient, uint amount) external returns(bool);
5,386,609
./full_match/8453/0x44d33798dddCdAbc93Fe6a40C80588033Dc502d3/sources/@balancer-labs/v2-pool-linear/contracts/LinearPoolRebalancer.sol
Tokens can be deposited to the Vault with a 'deposit' operation, but that requires a prior 'managed' balance to exist. We therefore have to perform two operations: one to set the 'managed' balance (representing the new tokens that resulted from wrapping or unwrapping and which we are managing for the Pool), and another to deposit. First, we inform the Vault of the 'managed' tokens. Then, we deposit them, clearing the 'managed' balance. Before we can deposit tokens into the Vault however, we must approve them.
function _depositToPool(IERC20 token, uint256 amount) private { IVault.PoolBalanceOp[] memory deposit = new IVault.PoolBalanceOp[](2); deposit[0].kind = IVault.PoolBalanceOpKind.UPDATE; deposit[0].poolId = _poolId; deposit[0].amount = amount; deposit[0].token = token; deposit[1].kind = IVault.PoolBalanceOpKind.DEPOSIT; deposit[1].poolId = _poolId; deposit[1].amount = amount; deposit[1].token = token; token.safeApprove(address(_vault), amount); _vault.managePoolBalance(deposit); }
11,541,945
// ---------------------------------------------------------- // TakeOff Payment for MINE Token // Website: Work MINE Vision // https://workmine.vision <[email protected]> // VisualEarth OÜ <[email protected]> // ---------------------------------------------------------- // Supported by TakeOff Technology OÜ <[email protected]> // Website: https://takeoff.center // ---------------------------------------------------------- // TakeOff Payment contract is licensed under the MIT License // Copyright (c) 2019 TakeOff Technology OÜ // ---------------------------------------------------------- // OpenZeppelin/openzeppelin-contracts is licensed under the MIT License // Copyright (c) 2016-2019 zOS Global Limited // ---------------------------------------------------------- // OpenZeppelin/openzeppelin-contracts is licensed under the MIT License // Copyright (c) 2016-2019 zOS Global Limited // File: contracts\lib\openzeppelin\token\ERC20\IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // OpenZeppelin/openzeppelin-contracts is licensed under the MIT License // Copyright (c) 2016-2019 zOS Global Limited // File: contracts\lib\openzeppelin\math\SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // OpenZeppelin/openzeppelin-contracts is licensed under the MIT License // Copyright (c) 2016-2019 zOS Global Limited // File: contracts\lib\openzeppelin\utils\Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ 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. // 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); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // OpenZeppelin/openzeppelin-contracts is licensed under the MIT License // Copyright (c) 2016-2019 zOS Global Limited // File: contracts\lib\openzeppelin\token\ERC20\SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // OpenZeppelin/openzeppelin-contracts is licensed under the MIT License // Copyright (c) 2016-2019 zOS Global Limited // File: contracts\lib\openzeppelin\GSN\Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // OpenZeppelin/openzeppelin-contracts is licensed under the MIT License // Copyright (c) 2016-2019 zOS Global Limited // File: contracts\lib\openzeppelin\access\Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // OpenZeppelin/openzeppelin-contracts is licensed under the MIT License // Copyright (c) 2016-2019 zOS Global Limited // File: contracts\lib\openzeppelin\access\roles\PauserRole.sol pragma solidity ^0.5.0; contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // OpenZeppelin/openzeppelin-contracts is licensed under the MIT License // Copyright (c) 2016-2019 zOS Global Limited // File: contracts\lib\openzeppelin\lifecycle\Pausable.sol pragma solidity ^0.5.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. */ contract Pausable is Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // OpenZeppelin/openzeppelin-contracts is licensed under the MIT License // Copyright (c) 2016-2019 zOS Global Limited // File: contracts\lib\openzeppelin\ownership\Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // OpenZeppelin/openzeppelin-contracts is licensed under the MIT License // Copyright (c) 2016-2019 zOS Global Limited // File: contracts\lib\openzeppelin\cryptography\ECDSA.sol pragma solidity ^0.5.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 { /** * @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. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * 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) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n テキ 2 + 1, and for v in (282): v 竏・{27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * 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)); } } // TakeOff Payment contract is licensed under the MIT License // Copyright (c) 2019 TakeOff Technology OÜ // File: contracts\Payment.sol pragma solidity ^0.5.0; contract Payment is Pausable, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // INVOICE SCHEMA HASH bytes32 constant private INVOICE_SCHEMA_HASH = 0x9b5fecc7f7fca49a5a75b168891cd29e66acc9e7e59c8e35e08e0c078a5aebf2; // ETH dummy address address constant private ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Signer Address address private _signer; // Seller Address / Token Address address payable private _sellerAddress; address private _tokenAddress; // Event event SignerChanged(address indexed signer); event SellerAddressChanged(address indexed sellerAddress); event TokenAddressChanged(address indexed tokenAddress); event TokenPurchased(address indexed buyerAddress, address tokenAddress, uint256 tokenAmount, bytes32 hash); // Invoice structure struct Invoice{ address buyerAddress; address sellerAddress; address tokenAddress; uint256 tokenUnitPrice; uint256 tokenAmount; address paymentTokenAddress; uint256 paymentTokenRate; uint256 paymentTokenAmount; uint256 expirationTimeSeconds; uint256 salt; } /// @dev Contract constructor sets initial seller and token address constructor (address payable sellerAddress, address tokenAddress) public { _signer = msg.sender; emit SignerChanged(_signer); _sellerAddress = sellerAddress; emit SellerAddressChanged(_sellerAddress); _tokenAddress = tokenAddress; emit TokenAddressChanged(_tokenAddress); } /** * @dev fallback function is not payable */ function () external { } /// @dev Check out the invoice with paying ETH. function checkoutWithETH( address buyerAddress, address payable sellerAddress, address tokenAddress, uint256 tokenUnitPrice, uint256 tokenAmount, address paymentTokenAddress, uint256 paymentTokenRate, uint256 paymentTokenAmount, uint256 expirationTimeSeconds, uint256 salt, bytes32 hash, bytes memory signature ) public payable whenNotPaused { Invoice memory invoice = Invoice({ buyerAddress: buyerAddress, sellerAddress: sellerAddress, tokenAddress: tokenAddress, tokenUnitPrice: tokenUnitPrice, tokenAmount: tokenAmount, paymentTokenAddress: paymentTokenAddress, paymentTokenRate: paymentTokenRate, paymentTokenAmount: paymentTokenAmount, expirationTimeSeconds: expirationTimeSeconds, salt: salt }); // check the hash bytes32 invoiceHash = _getStructHash(invoice); require(invoiceHash == hash, "invoice hash does not match"); // check signature require(_isValidSignature(hash, signature) == true, "invoice signature is invalid"); // check invoice require(_isValidInvoice(invoice) == true, "invoice is invalid"); // prepare token && allowance check IERC20 token = IERC20(_tokenAddress); require(token.allowance(_sellerAddress, address(this)) >= invoice.tokenAmount, "insufficient token allowance"); // payment amount check require(ETH_TOKEN_ADDRESS == invoice.paymentTokenAddress, "_ETH_ payment token address is invalid"); require(msg.value == invoice.paymentTokenAmount, "insufficient ETH payment"); // ETH/Token swap execute token.safeTransferFrom(_sellerAddress, invoice.buyerAddress, invoice.tokenAmount); _sellerAddress.transfer(invoice.paymentTokenAmount); emit TokenPurchased(invoice.buyerAddress, invoice.tokenAddress, invoice.tokenAmount, invoiceHash); } /// @dev Check out the invoice with paying ETH. function checkoutWithToken( address buyerAddress, address sellerAddress, address tokenAddress, uint256 tokenUnitPrice, uint256 tokenAmount, address paymentTokenAddress, uint256 paymentTokenRate, uint256 paymentTokenAmount, uint256 expirationTimeSeconds, uint256 salt, bytes32 hash, bytes memory signature ) public whenNotPaused { Invoice memory invoice = Invoice({ buyerAddress: buyerAddress, sellerAddress: sellerAddress, tokenAddress: tokenAddress, tokenUnitPrice: tokenUnitPrice, tokenAmount: tokenAmount, paymentTokenAddress: paymentTokenAddress, paymentTokenRate: paymentTokenRate, paymentTokenAmount: paymentTokenAmount, expirationTimeSeconds: expirationTimeSeconds, salt: salt }); // check the hash bytes32 invoiceHash = _getStructHash(invoice); require(invoiceHash == hash, "invoice hash does not match"); // check signature require(_isValidSignature(hash, signature) == true, "invoice signature is invalid"); // check invoice require(_isValidInvoice(invoice) == true, "invoice is invalid"); // prepare token && allowance check IERC20 token = IERC20(_tokenAddress); require(token.allowance(_sellerAddress, address(this)) >= invoice.tokenAmount, "insufficient token allowance"); // prepare payment token && allowance check IERC20 paymentToken = IERC20(invoice.paymentTokenAddress); require(paymentToken.allowance(invoice.buyerAddress, address(this)) >= invoice.paymentTokenAmount, "insufficient payment token allowance. please approval for the contract before checkout"); // ETH/Token swap execute token.safeTransferFrom(_sellerAddress, invoice.buyerAddress, invoice.tokenAmount); paymentToken.safeTransferFrom(invoice.buyerAddress, _sellerAddress, invoice.paymentTokenAmount); emit TokenPurchased(invoice.buyerAddress, invoice.tokenAddress, invoice.tokenAmount, invoiceHash); } /// @dev Validate the invoice /// @param invoice the invoice to check /// @return Whether the invoice is valid function _isValidInvoice(Invoice memory invoice) internal view returns (bool){ // check fixed seller address require(invoice.sellerAddress != address(0), "seller address is the zero address"); require(invoice.sellerAddress == _sellerAddress, "seller address is not the seller address of the contract"); // check fixed token address require(invoice.tokenAddress != address(0), "token address is the zero address"); require(invoice.tokenAddress == _tokenAddress, "token address is not the token address of the contract"); // check buyer address require(invoice.buyerAddress != address(0), "buyer address is the zero address"); require(invoice.buyerAddress == msg.sender, "buyer address is not msg.sender"); // check payment token address require(invoice.paymentTokenAddress != address(0), "payment token address is the zero address"); // expired check require(now < invoice.expirationTimeSeconds, "the invoice is expired. please refresh invoice and try again"); return true; } /// @dev Get the signer address. /// @return Invoice signer adddress function getSigner() public view returns (address) { return _signer; } /// @dev Set the signer address. /// @param newSigner Invoice signer adddress function setSigner(address newSigner) public onlyOwner { require(newSigner != address(0), "signer address is the zero address"); _signer = newSigner; emit SignerChanged(_signer); } /// @dev Get the seller address. /// @return Token seller adddress function getSellerAddress() public view returns (address) { return _sellerAddress; } /// @dev Set the seller address. /// @param newSellerAddress Token seller adddress function setSellerAddress(address payable newSellerAddress) public onlyOwner { require(newSellerAddress != address(0), "seller address is the zero address"); _sellerAddress = newSellerAddress; emit SellerAddressChanged(_sellerAddress); } /// @dev Get the token address. /// @return Token token adddress function getTokenAddress() public view returns (address) { return _tokenAddress; } /// @dev Set the token address. /// @param newTokenAddress Token adddress function setTokenAddress(address newTokenAddress) public onlyOwner { require(newTokenAddress != address(0), "token address is the zero address"); _tokenAddress = newTokenAddress; emit TokenAddressChanged(_tokenAddress); } /// @dev Create hash of invoice struct /// @param invoice Invoice to be hashed /// @return hash of the invoice function _getStructHash(Invoice memory invoice) internal pure returns (bytes32) { return keccak256(abi.encode( INVOICE_SCHEMA_HASH, invoice.buyerAddress, invoice.sellerAddress, invoice.tokenAddress, invoice.tokenUnitPrice, invoice.tokenAmount, invoice.paymentTokenAddress, invoice.paymentTokenRate, invoice.paymentTokenAmount, invoice.expirationTimeSeconds, invoice.salt )); } /// @dev Validate with hash and signature /// @param hash Message hash that is signed. /// @param signature Proof of signing. /// @return Whether the signature is by the signer function _isValidSignature( bytes32 hash, bytes memory signature ) internal view returns (bool) { address signerAddress = ECDSA.recover(ECDSA.toEthSignedMessageHash(hash), signature); if(signerAddress != address(0) && signerAddress == _signer){ return true; }else{ return false; } } }
Get the token address. return Token token adddress
function getTokenAddress() public view returns (address) { return _tokenAddress; }
14,042,735
./partial_match/1/0x7257c9da809F875309eE0445eaEaE94888238A1F/sources/JUICETOKENS.sol
Buy token id mints additional token of the particluar tokenId. Used when buying original tokens./calculate the service fee
function buyTokenId(uint256 _tokenId) external payable noReentrant tokenExists(_tokenId) tokenOnSale(_tokenId) { uint256 serviceFee; serviceFee = askingPrice[_tokenId] * serviceFeeNum / 10000; ILoyaltyToken LoyaltyTokenContract = ILoyaltyToken(loyaltyTokenAddress); if(loyaltyTokenAddress==address(0) || LoyaltyTokenContract.userTotalStake(msg.sender)<loyaltyTokenLimit){ require(msg.value == askingPrice[_tokenId], "Value missmatch"); require(msg.value == (askingPrice[_tokenId]-serviceFee), "Value missmatch"); serviceFee = 0; } address creator; uint256 proceeds; _mint(msg.sender, _tokenId, 1, ""); emit ItemSold(_tokenId, creator, askingPrice[_tokenId],msg.sender); } else { (creator, ) = royaltyInfo(_tokenId, msg.value); collectServiceFee += serviceFee; proceeds = msg.value - serviceFee; collectProceeds[creator] += proceeds; timesSold[_tokenId] += 1; }
15,905,354
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./interfaces/IOniiChainDescriptor.sol"; import "./interfaces/IOniiChain.sol"; import "./libraries/NFTDescriptor.sol"; import "./libraries/DetailHelper.sol"; import "base64-sol/base64.sol"; /// @title Describes Onii /// @notice Produces a string containing the data URI for a JSON metadata string contract OniiChainDescriptor is IOniiChainDescriptor { /// @dev Max value for defining probabilities uint256 internal constant MAX = 100000; uint256[] internal BACKGROUND_ITEMS = [4000, 3400, 3080, 2750, 2400, 1900, 1200, 0]; uint256[] internal SKIN_ITEMS = [2000, 1000, 0]; uint256[] internal NOSE_ITEMS = [10, 0]; uint256[] internal MARK_ITEMS = [50000, 40000, 31550, 24550, 18550, 13550, 9050, 5550, 2550, 550, 50, 10, 0]; uint256[] internal EYEBROW_ITEMS = [65000, 40000, 20000, 10000, 4000, 0]; uint256[] internal MASK_ITEMS = [20000, 14000, 10000, 6000, 2000, 1000, 100, 0]; uint256[] internal EARRINGS_ITEMS = [50000, 38000, 28000, 20000, 13000, 8000, 5000, 2900, 1000, 100, 30, 0]; uint256[] internal ACCESSORY_ITEMS = [ 50000, 43000, 36200, 29700, 23400, 17400, 11900, 7900, 4400, 1400, 400, 200, 11, 1, 0 ]; uint256[] internal MOUTH_ITEMS = [ 80000, 63000, 48000, 36000, 27000, 19000, 12000, 7000, 4000, 2000, 1000, 500, 50, 0 ]; uint256[] internal HAIR_ITEMS = [ 97000, 94000, 91000, 88000, 85000, 82000, 79000, 76000, 73000, 70000, 67000, 64000, 61000, 58000, 55000, 52000, 49000, 46000, 43000, 40000, 37000, 34000, 31000, 28000, 25000, 22000, 19000, 16000, 13000, 10000, 3000, 1000, 0 ]; uint256[] internal EYE_ITEMS = [ 98000, 96000, 94000, 92000, 90000, 88000, 86000, 84000, 82000, 80000, 78000, 76000, 74000, 72000, 70000, 68000, 60800, 53700, 46700, 39900, 33400, 27200, 21200, 15300, 10600, 6600, 3600, 2600, 1700, 1000, 500, 100, 10, 0 ]; /// @inheritdoc IOniiChainDescriptor function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view override returns (string memory) { NFTDescriptor.SVGParams memory params = getSVGParams(oniiChain, tokenId); params.background = getBackgroundId(params); string memory image = Base64.encode(bytes(NFTDescriptor.generateSVGImage(params))); string memory name = NFTDescriptor.generateName(params, tokenId); string memory description = NFTDescriptor.generateDescription(params); string memory attributes = NFTDescriptor.generateAttributes(params); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( abi.encodePacked( '{"name":"', name, '", "description":"', description, '", "attributes":', attributes, ', "image": "', "data:image/svg+xml;base64,", image, '"}' ) ) ) ) ); } /// @inheritdoc IOniiChainDescriptor function generateHairId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, HAIR_ITEMS, this.generateHairId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyeId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYE_ITEMS, this.generateEyeId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyebrowId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYEBROW_ITEMS, this.generateEyebrowId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateNoseId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, NOSE_ITEMS, this.generateNoseId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMouthId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MOUTH_ITEMS, this.generateMouthId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMarkId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MARK_ITEMS, this.generateMarkId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEarringsId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EARRINGS_ITEMS, this.generateEarringsId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateAccessoryId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, ACCESSORY_ITEMS, this.generateAccessoryId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMaskId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MASK_ITEMS, this.generateMaskId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateSkinId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, SKIN_ITEMS, this.generateSkinId.selector, tokenId); } /// @dev Get SVGParams from OniiChain.Detail function getSVGParams(IOniiChain oniiChain, uint256 tokenId) private view returns (NFTDescriptor.SVGParams memory) { IOniiChain.Detail memory detail = oniiChain.details(tokenId); return NFTDescriptor.SVGParams({ hair: detail.hair, eye: detail.eye, eyebrow: detail.eyebrow, nose: detail.nose, mouth: detail.mouth, mark: detail.mark, earring: detail.earrings, accessory: detail.accessory, mask: detail.mask, skin: detail.skin, original: detail.original, background: 0, timestamp: detail.timestamp, creator: detail.creator }); } function getBackgroundId(NFTDescriptor.SVGParams memory params) private view returns (uint8) { uint256 score = itemScorePosition(params.hair, HAIR_ITEMS) + itemScoreProba(params.accessory, ACCESSORY_ITEMS) + itemScoreProba(params.earring, EARRINGS_ITEMS) + itemScoreProba(params.mask, MASK_ITEMS) + itemScorePosition(params.mouth, MOUTH_ITEMS) + (itemScoreProba(params.skin, SKIN_ITEMS) / 2) + itemScoreProba(params.skin, SKIN_ITEMS) + itemScoreProba(params.nose, NOSE_ITEMS) + itemScoreProba(params.mark, MARK_ITEMS) + itemScorePosition(params.eye, EYE_ITEMS) + itemScoreProba(params.eyebrow, EYEBROW_ITEMS); return DetailHelper.pickItems(score, BACKGROUND_ITEMS); } /// @dev Get item score based on his probability function itemScoreProba(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ((item == 1 ? MAX : ITEMS[item - 2]) - ITEMS[item - 1]); return ((raw >= 1000) ? raw * 6 : raw) / 1000; } /// @dev Get item score based on his index function itemScorePosition(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ITEMS[item - 1]; return ((raw >= 1000) ? raw * 6 : raw) / 1000; } }
Get item score based on his index
function itemScorePosition(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ITEMS[item - 1]; return ((raw >= 1000) ? raw * 6 : raw) / 1000; }
5,343,304
pragma solidity ^0.5.1; //TODO: // //test - contributions, reclaims, fallback function, multiple loans //do we need a true start time? // allow people to contribute more than 99 million on the app // make it clear that 1 period is 60 seconds // Add UCASH address to HTML contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } //This proxy contract is necessary because our oracle uses the Transfer event to detect incoming transfers, and can&#39;t distiguish between transfer and transferFrom&#39; //users call contribute on the proxy, and the proxy transfers UCASH from the user to itself, then transfers UCASH to the ucollateral contract //this allows us to differentiate between contributions that use approve and transfer from, and contributions that occur when ucash is sent directly to the ucollateral contract. contract ProxyContributor{ UCOLLATERAL U; address public UCASHAddress; constructor (address _UCASHAddress) public{ U = UCOLLATERAL(msg.sender); UCASHAddress = _UCASHAddress; } function contribute() public { uint allowedAmount = ERC20(UCASHAddress).allowance(msg.sender,address(this)); ERC20(UCASHAddress).transferFrom(msg.sender,address(this),allowedAmount); ERC20(UCASHAddress).transfer(address(U),allowedAmount); U.contributeByProxyContract(msg.sender,allowedAmount); } } contract UCOLLATERAL { uint public StageAmount = 10**6*10**8; //1 million UCASH per stage uint public RemainingInStage = StageAmount; //Amount remaining in current stage uint BPNumerator = 21; // Bounty Percentage Numerator uint BPDenominator = 10000; // Bounty Percentage Denominator uint public StageValue = BPNumerator*BountyPool/BPDenominator; // Total value allocated to current Stage uint public BountyPool; //Total UCASH available in the Bounty Pool uint periods = 30; //how many periods this loan lasts uint period = 1 days; //period length uint specialReclaimValue = 110000; //Special Value to send contract, that triggers reclaim of loan. currently 0.0011 UCASH or 110000 wei uint recirculationIndex; //Index to keep track of which loans have been auto reclaimed. For lateFeesToBountyPool function. Loops back to 0 when it reaches the end of ListofLoans address public UCASHAddress; uint decimals = 8; address public owner; ProxyContributor P; address public Proxy; modifier onlyOwner() { require(msg.sender==owner); _; } event Contribution(address contributor, uint amountContributed, uint amountBounty, uint maturationDate); event Reclaimed(address contributor, uint amountReclaimed, uint amountPenalty); struct Loan { uint totalContribution; uint bounty; uint contractTime; uint start; uint recirculated; uint arrayIndex; } mapping(address=>Loan) public Loans; address[] public ListofLoans; constructor() public { CalculateStageValue(); owner = msg.sender; UCASHAddress = 0x92e52a1A235d9A103D970901066CE910AAceFD37; P = new ProxyContributor(UCASHAddress); Proxy = address(P); } //Reclaim your loan by sending a transaction function() external payable{ if(loanMatured(msg.sender) || msg.value == specialReclaimValue){ reclaimInternal(msg.sender); } } function contributeByProxyContract(address contributor, uint contribution) public { require(msg.sender==Proxy); contributeInternal(contributor,contribution); } //oracle calls this function everytime a UCASH transfer is made to the contract address function contributeByOracle(address contributor, uint contribution) public onlyOwner{ contributeInternal(contributor,contribution); } function contributeInternal(address contributor, uint contribution) internal returns(bool){ if (loanMatured(contributor) || contribution == specialReclaimValue){ reclaimInternal(contributor); } Loan memory memLoan = Loans[contributor]; if (memLoan.start == 0){ memLoan.start = now; memLoan.contractTime = periods * period; memLoan.arrayIndex = ListofLoans.length; ListofLoans.push(contributor); } uint timeElapsed = now - memLoan.start; uint rollBackTime = timeElapsed*contribution/(memLoan.totalContribution+contribution); uint Bounty; uint amountMemory = contribution; while(amountMemory > RemainingInStage){ Bounty += RemainingInStage*StageValue/StageAmount; amountMemory -=RemainingInStage; BountyPool -= RemainingInStage*StageValue/StageAmount; CalculateStageValue(); RemainingInStage = StageAmount; } Bounty += amountMemory*StageValue/StageAmount; RemainingInStage -= amountMemory; BountyPool -= amountMemory*StageValue/StageAmount; memLoan.totalContribution += contribution; memLoan.bounty += Bounty; memLoan.start += rollBackTime; Loans[contributor] = memLoan; emit Contribution(contributor, contribution, Bounty, memLoan.start+memLoan.contractTime); } function reclaim() public{ reclaimInternal(msg.sender); } function reclaimInternal(address contributor) internal{ uint UCASHtoSend; uint penalty; (UCASHtoSend,penalty) = ifClaimedNow(contributor); transferUCASH(contributor,UCASHtoSend); if(!loanMatured(contributor)){ BountyPool += Loans[contributor].bounty; } BountyPool += penalty; BountyPool -= Loans[contributor].recirculated; //re-arrange Array. Replace current element with last element, and delete last element. uint currentArrayIndex = Loans[contributor].arrayIndex; address replacingLoan = ListofLoans[ListofLoans.length - 1]; Loans[replacingLoan].arrayIndex = currentArrayIndex; ListofLoans[currentArrayIndex] = replacingLoan; delete Loans[contributor]; ListofLoans.length--; CalculateStageValue(); } function ifClaimedNowPublic() public view returns(uint,uint){ return ifClaimedNow(msg.sender); } function ifClaimedNow(address contributor) public view returns(uint ,uint){ Loan memory memLoan = Loans[contributor]; if (memLoan.start == 0){ return (0,0); } uint CancellationFee; //fraction out of 1000000 uint penalty; if (!loanMatured(contributor)){ if((now - memLoan.start) <= 3 days){ CancellationFee = 0; }else { uint elapsedPeriods = (now-memLoan.start)/(period); CancellationFee = 210000*(periods-elapsedPeriods)/periods; } penalty = (memLoan.totalContribution*CancellationFee)/1000000; memLoan.bounty = 0; } else{ penalty = getLateFee(contributor); } uint UCASHtoSend = memLoan.totalContribution + memLoan.bounty - penalty; return (UCASHtoSend,penalty); } function CalculateStageValue() internal{ StageValue = BPNumerator*BountyPool/BPDenominator; } function loanMatured(address contributor) private view returns (bool){ if(Loans[contributor].start == 0){ return false; } if((now > (Loans[contributor].start+Loans[contributor].contractTime))){ return true; } else { return false; } } function contractBalance() public view returns(uint){ return ERC20(UCASHAddress).balanceOf(address(this)); } function secondsLeftPublic() public view returns(uint){ return secondsLeft(msg.sender); } function secondsLeft(address contributor) public view returns(uint){ if(loanMatured(contributor)){ return 0; } else if(Loans[contributor].start ==0) { return 0; } else{ return (Loans[contributor].start + Loans[contributor].contractTime - now); } } function getLateFee(address contributor) public view returns(uint){ require(loanMatured(contributor)); Loan memory memLoan = Loans[contributor]; uint totalReward = memLoan.totalContribution + memLoan.bounty; uint endDate = memLoan.start + memLoan.contractTime; uint periodsLateBy = (now - endDate)/period; uint totalPenalty; uint periodPenalty; if (periodsLateBy>=2000){ totalPenalty = totalReward; } else if (periodsLateBy<=10){ return(0); } else{ uint i; while(i++<uint(periodsLateBy-10)){ periodPenalty = totalReward*21/1000; totalPenalty += periodPenalty; //penalize 2.1% of remaining reward every month; totalReward -= periodPenalty; } } return(totalPenalty); } function isLateBy(address contributor) public view returns(uint){ if(Loans[contributor].start == 0){ return 0; } uint endDate = Loans[contributor].start + Loans[contributor].contractTime; if(now<endDate){ return 0; }else{ return (now - endDate)/period; } } function numLoans() public view returns (uint) { return ListofLoans.length; } function nowwww() public view returns(uint){ return now; } function calculateBounty(uint contribution) public view returns(uint){ uint Bounty; uint _BountyPool = BountyPool; uint _RemainingInStage = RemainingInStage; uint _StageValue = StageValue; while(contribution > _RemainingInStage){ Bounty += _RemainingInStage*_StageValue/StageAmount; contribution -= _RemainingInStage; _BountyPool -= _RemainingInStage*_StageValue/StageAmount; _StageValue = BPNumerator*_BountyPool/BPDenominator; _RemainingInStage = StageAmount; } Bounty += contribution*_StageValue/StageAmount; return Bounty; } function addFunds(uint _amount) public payable onlyOwner{ BountyPool+= _amount; CalculateStageValue(); } function removeFunds(uint _amount) onlyOwner public { BountyPool -= _amount; transferUCASH(owner,_amount); CalculateStageValue(); } function transferUCASH(address _recipient, uint _amount) private{ ERC20(UCASHAddress).transfer(_recipient,_amount); } function calculateAllReclaimedNow() public view returns(uint){ uint total; uint i; for(i=0;i<ListofLoans.length;i++){ uint reclaimable; (reclaimable,) = ifClaimedNow(ListofLoans[i]); total += reclaimable; } return total; } function CalculateAllocatedUcash() public view returns(uint){ uint total; uint i; for(i=0;i<ListofLoans.length;i++){ total += Loans[ListofLoans[i]].totalContribution + Loans[ListofLoans[i]].bounty; } return total; } //Recirculate All Late fees to the bountyPool, and AutoReclaim loans more than 100 periods late. function recirculateLateFees(uint iterations) public { if(recirculationIndex>=ListofLoans.length){ recirculationIndex = 0; } uint i = recirculationIndex; uint j; if (i+iterations>ListofLoans.length){ j = ListofLoans.length; } else{ j = i + iterations; } for(i;i<j;i++){ address contributor = ListofLoans[i]; if(isLateBy(contributor)>=600){ reclaimInternal(contributor); //autoreclaim the loan if the loan is late by more than 100 periods //reclaimInternal deletes ListofLoans[i] and moves last element of ListofLoans into ListofLoans[i] i--; j--; //shift the loop back by one interval, shorten loop by one interval. Number of loops remains the same. }else if(loanMatured(contributor)){ uint amountToRecirculate = getLateFee(contributor) - Loans[contributor].recirculated; Loans[contributor].recirculated += amountToRecirculate; BountyPool += amountToRecirculate; } } recirculationIndex = j; } function killswitch() public onlyOwner returns (bool){ uint i; while (i++<500 && ListofLoans.length>0){ address contributor = ListofLoans[ListofLoans.length-1]; Loan memory memLoan = Loans[contributor]; ERC20(UCASHAddress).transfer(contributor, memLoan.totalContribution-memLoan.recirculated); ListofLoans.length--; } if(ListofLoans.length==0){ ERC20(UCASHAddress).transfer(owner,contractBalance()); selfdestruct(address(this)); } else { return false; } } }
Recirculate All Late fees to the bountyPool, and AutoReclaim loans more than 100 periods late.reclaimInternal deletes ListofLoans[i] and moves last element of ListofLoans into ListofLoans[i]
function recirculateLateFees(uint iterations) public { if(recirculationIndex>=ListofLoans.length){ recirculationIndex = 0; } uint i = recirculationIndex; uint j; if (i+iterations>ListofLoans.length){ j = ListofLoans.length; j = i + iterations; } for(i;i<j;i++){ address contributor = ListofLoans[i]; if(isLateBy(contributor)>=600){ uint amountToRecirculate = getLateFee(contributor) - Loans[contributor].recirculated; Loans[contributor].recirculated += amountToRecirculate; BountyPool += amountToRecirculate; } } recirculationIndex = j; }
6,709,042
./full_match/137/0x570806Da963333491Cae53A5E78bEDe517489E51/sources/contracts/ERC1155Drop.sol
Transfers the tokens being claimed.
function transferTokensOnClaim(address _to, uint256 _tokenId, uint256 _quantityBeingClaimed) internal virtual override { _mint(_to, _tokenId, _quantityBeingClaimed, ""); }
4,680,297
pragma solidity ^0.5.0; contract Storage { struct Entry { bytes32[] keys; mapping (bytes32 => bytes) data; uint size; address logic; uint index; } mapping(bytes32 => Entry) entries; bytes32[] ids; function set(bytes32 id, bytes32[] memory keys, bytes memory values, uint[] memory offsets, address logic) public onlyValid (keys, offsets){ require(logic != address(0), 'Logic address in zero!'); Entry storage e = entries[id]; if(exists(id)) { require(isLogic(id, msg.sender), 'The entry does not exist or attempts to modify not from entry logic address!'); _removeEntryData(id); } else { ids.push(id); e.index = ids.length - 1; } uint currentOffset; //todo consider optimizing this for in terms of gas efficiency for (uint i = 0; i < offsets.length; i++) { //todo consider checking if current offset is greater than previous offset require(currentOffset < values.length, 'Data is invalid!'); uint valueSize = (i < offsets.length - 1 ? offsets[i+1]: values.length) - currentOffset; bytes memory value = new bytes(valueSize); for (uint m = 0; m < valueSize; m++) { value[m] = values[currentOffset++]; } e.data[keys[i]] = value; } e.keys = keys; e.size = values.length; e.logic = logic; } function remove(bytes32 id) public onlyLogic(id){ Entry storage e = entries[id]; // move entry id from the end of the array if entries[id].index is not the last index for the array // entries order can change in ids if(e.index < ids.length - 1) { ids[e.index] = ids[ids.length - 1]; entries[ids[ids.length - 1]].index = e.index; } // the array length should not be zero as far as onlyLogic modifier requires exists(id) check // so at least one entry should exist and array overflow should be excluded ids.length--; _removeEntryData(id); delete e.logic; delete e.index; } function _removeEntryData(bytes32 id) internal { Entry storage e = entries[id]; for (uint i = 0; i < e.keys.length; i++) { delete e.data[e.keys[i]]; } delete e.keys; delete e.size; } function setByDataKey(bytes32 id, bytes32 key, bytes memory value) public onlyLogic(id){ Entry storage e = entries[id]; if (e.data[key].length == 0){ e.size += value.length; e.keys.push(key); e.data[key] = value; } else { e.size -= e.data[key].length; e.size += value.length; e.data[key] = value; } } function removeByDataKey(bytes32 id, bytes32 key) public onlyLogic(id){ Entry storage e = entries[id]; bool keyExists; uint keyIndex; for (uint i = 0; i < e.keys.length; i++){ if (e.keys[i] == key) { keyExists = true; keyIndex = i; e.size -= e.data[e.keys[i]].length; delete e.data[e.keys[i]]; break; } } require(keyExists, 'Data key does not exist!'); for (uint i = keyIndex + 1; i < e.keys.length; i++){ e.keys[i - 1] = e.keys[i]; } e.keys.length--; } function setLogic(bytes32 id, address newLogic) public onlyLogic(id){ require(newLogic != address(0), 'Logic contract address can not be zero'); entries[id].logic = newLogic; } function get(bytes32 id) public view returns( bytes32[] memory keys, bytes memory values, uint[] memory offsets, address logic ) { keys = entries[id].keys; mapping(bytes32 => bytes) storage data = entries[id].data; bytes32[] memory mk = new bytes32[](keys.length); bytes memory mv = new bytes(entries[id].size); uint[] memory mo = new uint[](keys.length); uint pointer; for (uint i = 0; i < keys.length; i++) { mo[i] = pointer; mk[i] = keys[i]; //TODO Consider replacing this cycle with assembly (that may be if ever used in transactions but not simple calls) for (uint m = 0; m < data[keys[i]].length; m++) { mv[pointer++] = data[keys[i]][m]; } } logic = entries[id].logic; return ( mk, mv, mo, logic ); } function getByDataKey(bytes32 id, bytes32 key) public view returns(bytes memory value) { return entries[id].data[key]; } function getAllIds() public view returns(bytes32[] memory allIds) { return ids; } function getLogic(bytes32 id) public view returns(address logic) { return entries[id].logic; } function count() public view returns(uint entriesCount) { return ids.length; } function exists(bytes32 id) public view returns(bool) { return (entries[id].logic != address(0)); } function isLogic(bytes32 id, address verifiedAddress) public view returns(bool) { return exists(id) && entries[id].logic == verifiedAddress; } modifier onlyLogic(bytes32 id) { require (isLogic(id, msg.sender), 'The entry does not exist or attempts to modify not from entry logic address!'); _; } modifier onlyValid(bytes32[] memory keys, uint[] memory offsets) { require (keys.length == offsets.length && keys.length > 0, 'Data is invalid!'); _; } }
todo consider optimizing this for in terms of gas efficiencytodo consider checking if current offset is greater than previous offset
function set(bytes32 id, bytes32[] memory keys, bytes memory values, uint[] memory offsets, address logic) public onlyValid (keys, offsets){ require(logic != address(0), 'Logic address in zero!'); Entry storage e = entries[id]; if(exists(id)) { require(isLogic(id, msg.sender), 'The entry does not exist or attempts to modify not from entry logic address!'); _removeEntryData(id); ids.push(id); e.index = ids.length - 1; } uint currentOffset; for (uint i = 0; i < offsets.length; i++) { require(currentOffset < values.length, 'Data is invalid!'); uint valueSize = (i < offsets.length - 1 ? offsets[i+1]: values.length) - currentOffset; bytes memory value = new bytes(valueSize); for (uint m = 0; m < valueSize; m++) { value[m] = values[currentOffset++]; } e.data[keys[i]] = value; } e.keys = keys; e.size = values.length; e.logic = logic; }
955,305
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./GaiminERC1155Ids.sol"; import "./IGaiminERC1155.sol"; contract GaiminICO is Ownable, GaiminERC1155Ids, ReentrancyGuard, ERC1155Holder { IGaiminERC1155 public token; uint256 public salesEndPeriod; uint256 public rarityPrice; uint256 public totalUnknownRarityMinted = 0; bool public whitelistingEnabled = true; uint8 public constant MAX_NFTS_PER_ACCOUNT = 20; bytes32 whiteslitedAddressesMerkleRoot = 0x00; mapping (uint256 => uint256) public mintedRarity; event PurchaseRarity( address indexed user, uint256 purchasedRarity, uint256 etherToRefund, uint256 etherUsed, uint256 etherSent, uint256 timestamp ); event DelegatePurchase( address[] indexed users, uint256[] amounts, uint256 timestamp ); event AllocateRarity( address[] indexed receivers, uint256[] amounts, uint256 timestamp ); event Withdraw( address indexed user, uint256 amount, uint256 timestamp ); event UpdateMerkleRoot( bytes32 indexed newRoot, uint256 timestamp ); event UpdateSalesEndPeriod( uint256 indexed newSalesEndPeriod, uint256 timestamp ); constructor(address token_, uint256 salesEndPeriod_, uint256 rarityPrice_) { require(token_ != address(0), "Not a valid token address"); require(rarityPrice_ > 0, "Rarity Price can not be equal to zero"); require(salesEndPeriod_ > block.timestamp, "Distribution date is in the past"); token = IGaiminERC1155(token_); salesEndPeriod = salesEndPeriod_; rarityPrice = rarityPrice_; } receive() external payable { revert(); } function purchaseRarity(bytes32[] memory proof) external payable nonReentrant { require(block.timestamp <= salesEndPeriod, "Rarity sale period have ended"); require(msg.value >= rarityPrice, "Price must be greather than or equal to the rarity price"); require(token.balanceOf(msg.sender, UNKNOWN) != MAX_NFTS_PER_ACCOUNT, "Receiver have reached the allocated limit"); if (whitelistingEnabled) { require(proof.length > 0, "Proof length can not be zero"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); bool iswhitelisted = verifyProof(leaf, proof); require(iswhitelisted, "User not whitelisted"); } uint256 numOfRarityPerPrice = msg.value / rarityPrice; uint256 numOfEligibleRarityToPurchase = MAX_NFTS_PER_ACCOUNT - token.balanceOf(msg.sender, UNKNOWN); uint256 numOfRarityPurchased = numOfRarityPerPrice > numOfEligibleRarityToPurchase ? numOfEligibleRarityToPurchase : numOfRarityPerPrice; require((token.balanceOf(msg.sender, UNKNOWN) + numOfRarityPurchased) <= MAX_NFTS_PER_ACCOUNT, "Receiver total rarity plus the rarity you want to purchase exceed your limit"); require((totalUnknownRarityMinted + numOfRarityPurchased) <= MAX_TOTAL_UNKNOWN, "The amount of rarity you want to purchase plus the total rarity minted exceed the total unknown rarity"); uint256 totalEtherUsed = numOfRarityPurchased * rarityPrice; // calculate and send the remaining ether balance uint256 etherToRefund = _transferBalance(msg.value, payable(msg.sender), totalEtherUsed); totalUnknownRarityMinted += numOfRarityPurchased; // MINT NFT; token.mint(msg.sender, UNKNOWN, numOfRarityPurchased, "0x0"); emit PurchaseRarity(msg.sender, UNKNOWN, etherToRefund, totalEtherUsed, msg.value, block.timestamp); } function _transferBalance(uint256 totalEtherSpent, address payable user, uint256 totalEtherUsed) internal returns(uint256) { uint256 balance = 0; if (totalEtherSpent > totalEtherUsed) { balance = totalEtherSpent - totalEtherUsed; (bool sent, ) = user.call{value: balance}(""); require(sent, "Failed to send remaining Ether balance"); } return balance; } function delegatePurchase(address[] memory newUsers, uint256[] memory amounts) external onlyOwner nonReentrant{ require(newUsers.length == amounts.length, "newUsers and amounts length mismatch"); uint256 _totalUnknownRarityMinted = totalUnknownRarityMinted; for (uint256 i = 0; i < newUsers.length; i++) { address newUser = newUsers[i]; uint256 amount = amounts[i]; require(newUser != address(0), "Not a valid address"); require(amount != 0, "Rarity mint amount can not be zero"); require((_totalUnknownRarityMinted + amount) <= MAX_TOTAL_UNKNOWN, "Rarity to be minted will exceed maximum total UNKNOWN rarity"); _totalUnknownRarityMinted += amount; // MINT NFT; token.mint(newUser, UNKNOWN, amount, "0x0"); } totalUnknownRarityMinted = _totalUnknownRarityMinted; emit DelegatePurchase(newUsers, amounts, block.timestamp); } function allocateRarity(uint256[] memory amounts, address[] memory receivers) external onlyOwner nonReentrant { require(amounts.length == receivers.length, "amounts and receivers length mismatch"); require(block.timestamp > salesEndPeriod, "Rarity can not be distributed now"); uint256 randomNumber = uint256(blockhash(block.number - 1) ^ blockhash(block.number - 2) ^ blockhash(block.number - 3)); for (uint256 i = 0; i < receivers.length; i++) { address receiver = receivers[i]; uint256 amount = amounts[i]; uint256[] memory purchasedRarity = new uint[](amount); uint256[] memory amountPerRarity = new uint[](amount); require(receiver != address(0), "Not a valid address"); require(amount != 0, "Rarity mint amount can not be zero"); for (uint256 j = 0; j < amount; j++) { // There will be mathemtical overflow below, which is fine we want it. unchecked { randomNumber += uint256(blockhash(block.number - 4)); } uint256 remainingSilver = (MAX_TOTAL_SILVER - mintedRarity[SILVER]); uint256 remainingGold = (MAX_TOTAL_GOLD - mintedRarity[GOLD]); uint256 remainingBlackgold = (MAX_TOTAL_BLACKGOLD - mintedRarity[BLACKGOLD]); uint256 remainingSupply = remainingSilver + remainingGold + remainingBlackgold; uint256 raritySlot = (randomNumber % remainingSupply); uint256 rarity; if (raritySlot < remainingSilver) { rarity = SILVER; } else if (raritySlot < (remainingSilver + remainingGold)) { rarity = GOLD; } else { rarity = BLACKGOLD; } purchasedRarity[j] = rarity; amountPerRarity[j] = 1; mintedRarity[rarity]++; } // BURN UNKNOWN NFT; token.burn(receiver, UNKNOWN, amount); // MINT NFT in Batch; token.mintBatch(receiver, purchasedRarity, amountPerRarity, "0x0"); } emit AllocateRarity(receivers, amounts, block.timestamp); } function verifyProof(bytes32 leaf, bytes32[] memory proof) public view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash == whiteslitedAddressesMerkleRoot; } function withdrawEther(address payable receiver) external onlyOwner nonReentrant { require(receiver != address(0), "Not a valid address"); require(address(this).balance > 0, "Contract have zero balance"); (bool sent, ) = receiver.call{value: address(this).balance}(""); require(sent, "Failed to send ether"); emit Withdraw(receiver, address(this).balance, block.timestamp); } function updateMerkleRoot(bytes32 newMerkleRoot) external onlyOwner { require(newMerkleRoot.length > 0, "New merkle tree is empty"); whiteslitedAddressesMerkleRoot = newMerkleRoot; emit UpdateMerkleRoot(newMerkleRoot, block.timestamp); } function updateSalesEndPeriod(uint256 newSalesEndPeriod) external onlyOwner{ require(newSalesEndPeriod > block.timestamp, "New sale end period is in the past"); salesEndPeriod = newSalesEndPeriod; emit UpdateSalesEndPeriod(newSalesEndPeriod, block.timestamp); } function toggleWhitelist() external onlyOwner { whitelistingEnabled = !whitelistingEnabled; } function getBalance() external view returns (uint) { return address(this).balance; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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: UNLICENSED pragma solidity 0.8.6; contract GaiminERC1155Ids { uint16 public constant MAX_TOTAL_UNKNOWN = 8888; uint16 public constant MAX_TOTAL_SILVER = 6000; uint16 public constant MAX_TOTAL_GOLD = 2800; uint16 public constant MAX_TOTAL_BLACKGOLD = 88; uint16 public constant UNKNOWN = 0; uint16 public constant SILVER = 1; uint16 public constant GOLD = 2; uint16 public constant BLACKGOLD = 3; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; interface IGaiminERC1155 is IERC1155 { function mint(address account, uint256 id, uint256 amount, bytes memory data) external; function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) external; function burn(address account, uint256 id, uint256 value) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155Receiver.sol"; import "../../../utils/introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } } // 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 "./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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../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; }
There will be mathemtical overflow below, which is fine we want it.
function allocateRarity(uint256[] memory amounts, address[] memory receivers) external onlyOwner nonReentrant { require(amounts.length == receivers.length, "amounts and receivers length mismatch"); require(block.timestamp > salesEndPeriod, "Rarity can not be distributed now"); uint256 randomNumber = uint256(blockhash(block.number - 1) ^ blockhash(block.number - 2) ^ blockhash(block.number - 3)); for (uint256 i = 0; i < receivers.length; i++) { address receiver = receivers[i]; uint256 amount = amounts[i]; uint256[] memory purchasedRarity = new uint[](amount); uint256[] memory amountPerRarity = new uint[](amount); require(receiver != address(0), "Not a valid address"); require(amount != 0, "Rarity mint amount can not be zero"); for (uint256 j = 0; j < amount; j++) { unchecked { randomNumber += uint256(blockhash(block.number - 4)); } uint256 remainingSilver = (MAX_TOTAL_SILVER - mintedRarity[SILVER]); uint256 remainingGold = (MAX_TOTAL_GOLD - mintedRarity[GOLD]); uint256 remainingBlackgold = (MAX_TOTAL_BLACKGOLD - mintedRarity[BLACKGOLD]); uint256 remainingSupply = remainingSilver + remainingGold + remainingBlackgold; uint256 raritySlot = (randomNumber % remainingSupply); uint256 rarity; if (raritySlot < remainingSilver) { rarity = SILVER; rarity = GOLD; rarity = BLACKGOLD; } purchasedRarity[j] = rarity; amountPerRarity[j] = 1; mintedRarity[rarity]++; } } emit AllocateRarity(receivers, amounts, block.timestamp); }
5,722,270
pragma solidity ^0.5.0; /* Oh wow, it's finally happening /* ╔══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗ ║ $$$$$$$\ $$\ $$\ $$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$$$\ ║ ║ $$ __$$\ $$ | $\ $$ |$$ | $$ | $$ ___$$\ $$ __$$\ $$ _____| ║ ║ $$ | $$ | $$$$$$\ $$ |$$$\ $$ |$$ | $$ | \_/ $$ |$$ | $$ | $$ | $$\ $$\ ║ ║ $$$$$$$ |$$ __$$\ $$ $$ $$\$$ |$$$$$$$$ | $$$$$ / $$ | $$ | $$$$$\ \$$\ $$ | ║ ║ $$ ____/ $$ / $$ |$$$$ _$$$$ |$$ __$$ | \___$$\ $$ | $$ | $$ __| \$$$$ / ║ ║ $$ | $$ | $$ |$$$ / \$$$ |$$ | $$ | $$\ $$ |$$ | $$ | $$ | $$ $$< ║ ║ $$ | \$$$$$$ |$$ / \$$ |$$ | $$ | \$$$$$$ |$$$$$$$ | $$$$$$$$\ $$ /\$$\ ║ ║ \__| \______/ \__/ \__|\__| \__| \______/ \_______/ \________|\__/ \__| ║ ║ ║ ╠══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣ ║ _____ __ __ __ __ _ _ _ _ ║ ║ | __ \ / _| / _| \ \ / / | | | | | | | | ║ ║ | |__) | __ ___ ___ | |_ ___ | |_ \ \ /\ / /__ __ _| | __ | |__| | __ _ _ __ __| |___ ║ ║ | ___/ '__/ _ \ / _ \| _| / _ \| _| \ \/ \/ / _ \/ _` | |/ / | __ |/ _` | '_ \ / _` / __| ║ ║ | | | | | (_) | (_) | | | (_) | | \ /\ / __/ (_| | < | | | | (_| | | | | (_| \__ \ ║ ║ |_| |_| \___/ \___/|_| \___/|_| \/ \/ \___|\__,_|_|\_\ |_| |_|\__,_|_| |_|\__,_|___/ ║ ║ ____ _____ ________ _________ ______ _ _ _____ ______ _____ ║ ║ |___ \| __ \ _ | ____\ \ / /__ __| ____| \ | | __ \| ____| __ \ ║ ║ __) | | | | (_) | |__ \ V / | | | |__ | \| | | | | |__ | | | | ║ ║ |__ <| | | | | __| > < | | | __| | . ` | | | | __| | | | | ║ ║ ___) | |__| | _ | |____ / . \ | | | |____| |\ | |__| | |____| |__| | ║ ║ |____/|_____/ (_) |______/_/ \_\ |_| |______|_| \_|_____/|______|_____/ ║ ║ ╔══════════════════════════╗ ║ ╚═════════════════════════════════════════════╣ Created by ARitz Cracker ╠═════════════════════════════════════════════╝ ╚══════════════════════════╝ In a world, where people wanted more 3rd party dApp integration with P3D, a small "Jack of all trades" developer, ARitz Cracker set out to create an addon-token for P3D that would add the functionality required for 3rd party dApp integration. However, while creating this, he had another calling... Replacing web3js and Metamask a grand feat, for sure. Unfortunately, this left the extension token aside. One man took advantage of this functionality-vacuum and created his own extension, but it was forged by greed... and would force its users to pay additional fees and taxes to the creator and anyone he saw fit. ARitz Cracker saw this as a sign... "People need community focused dApp extensions now!" And so, he set out to have it completed, audited, and ready for the community as soon as possible... In order to prevent the greedy ones from taking power away from the community. Thus, P3X was born. So, what does this thing actually do? * P3X is a utility token tethered to P3D. * The total P3X supply will always be equal to the amount of P3D bought by this contract. * P3X Price will always be equal to P3D price * Dividends per P3X token is the same as P3D * Functionally identical to P3D Exept: * 0% token fees on transfers * Full ERC20 and ERC223 functionality, allowing for external dApps to _actually_ receive funds and interact with the contract. * Optional gauntlets which prevent you from selling (literally!) * For more information, please visit the wiki page: https://powh3d.hostedwiki.co/pages/What%20is%20P3X Also, this is my first contract on main-net please be gentle :S */ // Interfaces for easy copypasta interface ERC20interface { function transfer(address to, uint value) external returns(bool success); function approve(address spender, uint tokens) external returns(bool success); function transferFrom(address from, address to, uint tokens) external returns(bool success); function allowance(address tokenOwner, address spender) external view returns(uint remaining); function balanceOf(address tokenOwner) external view returns(uint balance); } interface ERC223interface { function transfer(address to, uint value) external returns(bool ok); function transfer(address to, uint value, bytes calldata data) external returns(bool ok); function transfer(address to, uint value, bytes calldata data, string calldata customFallback) external returns(bool ok); function balanceOf(address who) external view returns(uint); } // If your contract wants to accept P3X, implement this function interface ERC223Handler { function tokenFallback(address _from, uint _value, bytes calldata _data) external; } // External gauntlet interfaces can be useful for something like voting systems or contests interface ExternalGauntletInterface { function gauntletRequirement(address wearer, uint256 oldAmount, uint256 newAmount) external returns(bool); function gauntletRemovable(address wearer) external view returns(bool); } // This is P3D itself (not a cimplete interface) interface Hourglass { function decimals() external view returns(uint8); function stakingRequirement() external view returns(uint256); function balanceOf(address tokenOwner) external view returns(uint); function dividendsOf(address tokenOwner) external view returns(uint); function calculateTokensReceived(uint256 _ethereumToSpend) external view returns(uint256); function calculateEthereumReceived(uint256 _tokensToSell) external view returns(uint256); function myTokens() external view returns(uint256); function myDividends(bool _includeReferralBonus) external view returns(uint256); function totalSupply() external view returns(uint256); function transfer(address to, uint value) external returns(bool); function buy(address referrer) external payable returns(uint256); function sell(uint256 amount) external; function withdraw() external; } // This a name database used in Fomo3D (Also not a complete interface) interface TeamJustPlayerBook { function pIDxName_(bytes32 name) external view returns(uint256); function pIDxAddr_(address addr) external view returns(uint256); function getPlayerAddr(uint256 pID) external view returns(address); } // Here's an interface in case you want to integration your dApp with this. // Descriptions of each function are down below in the soure code. // NOTE: It's not _entirely_ compatible with the P3D interface. myTokens() has been renamed to myBalance(). /* interface HourglassX { function buy(address referrerAddress) payable external returns(uint256 tokensReceieved); function buy(string calldata referrerName) payable external returns(uint256 tokensReceieved); function reinvest() external returns(uint256 tokensReceieved); function reinvestPartial(uint256 ethToReinvest) external returns(uint256 tokensReceieved); function reinvestPartial(uint256 ethToReinvest, bool withdrawAfter) external returns(uint256 tokensReceieved); function sell(uint256 amount, bool withdrawAfter) external returns(uint256 ethReceieved); function sell(uint256 amount) external returns(uint256 ethReceieved); // Alias of sell(amount, false) function withdraw() external; function exit() external; function acquireGauntlet(uint256 amount, uint8 gType, uint256 end) external; function acquireExternalGauntlet(uint256 amount, address extGauntlet) external; function setReferrer(address referrer) external; function setReferrer(string calldata referrerName) external; function myBalance() external view returns(uint256 balance); function dividendsOf(address accountHolder, bool includeReferralBonus) external view returns(uint256 divs); function dividendsOf(address accountHolder) external view returns(uint256 divs); // Alias of dividendsOf(accountHolder, true) function myDividends(bool includeReferralBonus) external view returns(uint256 divs); function myDividends() external view returns(uint256 divs); // Alias of myDividends(true); function usableBalanceOf(address accountHolder) external view returns(uint256 balance); function myUsableBalance() external view returns(uint256 balance); function refBonusOf(address customerAddress) external view returns(uint256); function myRefBonus() external view returns(uint256); function gauntletTypeOf(address accountHolder) external view returns(uint256 stakeAmount, uint256 gType, uint256 end); function myGauntletType() external view returns(uint256 stakeAmount, uint256 gType, uint256 end); function stakingRequirement() external view returns(uint256); function savedReferral(address accountHolder) external view returns(address); // ERC 20/223 function balanceOf(address tokenOwner) external view returns(uint balance); function transfer(address to, uint value) external returns(bool ok); function transfer(address to, uint value, bytes data) external returns(bool ok); function transfer(address to, uint value, bytes data, string customFallback) external returns(bool ok); function allowance(address tokenOwner, address spender) external view returns(uint remaining); function approve(address spender, uint tokens) external returns(bool success); function transferFrom(address from, address to, uint tokens) external returns(bool success); // Events (cannot be in interfaces used here as a reference) event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint value); event Transfer(address indexed from, address indexed to, uint value, bytes data); event onTokenPurchase( address indexed accountHolder, uint256 ethereumSpent, uint256 tokensCreated, uint256 tokensGiven, address indexed referrer, uint8 bitFlags // 1 = invalidMasternode, 2 = usedHourglassMasternode, 4 = reinvestment ); event onTokenSell( address indexed accountHolder, uint256 tokensDestroyed, uint256 ethereumEarned ); event onWithdraw( address indexed accountHolder, uint256 earningsWithdrawn, uint256 refBonusWithdrawn, bool reinvestment ); event onDonatedDividends( address indexed donator, uint256 ethereumDonated ); event onGauntletAcquired( address indexed strongHands, uint256 stakeAmount, uint8 gauntletType, uint256 end ); event onExternalGauntletAcquired( address indexed strongHands, uint256 stakeAmount, address indexed extGauntlet ); // Gauntlet events will be emitted with stakeAmount == 0 when the gauntlets expire. } */ // This contract is intended to only be used by HourglassX. Think of this as HourglassX's second account (or child slave with its own account) contract HourglassXReferralHandler { using SafeMath for uint256; using SafeMath for uint; address internal parent; Hourglass internal hourglass; constructor(Hourglass h) public { hourglass = h; parent = msg.sender; } // Don't expose this account to literally everyone modifier onlyParent { require(msg.sender == parent, "Can only be executed by parent process"); _; } // Contract's total ETH balance including divs function totalBalance() public view returns(uint256) { return address(this).balance + hourglass.myDividends(true); } // Buy P3D from given ether function buyTokens(address referrer) public payable onlyParent { hourglass.buy.value(msg.value)(referrer); } // Buy P3D from own ether balance function buyTokensFromBalance(address referrer, uint256 amount) public onlyParent { if (address(this).balance < amount) { hourglass.withdraw(); } hourglass.buy.value(amount)(referrer); } // Sell a specified amount of P3D for ether function sellTokens(uint256 amount) public onlyParent { if (amount > 0) { hourglass.sell(amount); } } // Withdraw outstanding divs to internal balance function withdrawDivs() public onlyParent { hourglass.withdraw(); } // Send eth from internal balance to a specified account function sendETH(address payable to, uint256 amount) public onlyParent { if (address(this).balance < amount) { hourglass.withdraw(); } to.transfer(amount); } // Only allow ETH from our master or from the hourglass. function() payable external { require(msg.sender == address(hourglass) || msg.sender == parent, "No, I don't accept donations"); } // Reject possible accidental sendin of higher-tech shitcoins. function tokenFallback(address from, uint value, bytes memory data) public pure { revert("I don't want your shitcoins!"); } // Allow anyone else to take forcefully sent low-tech shitcoins. (I sure as hell don't want them) function takeShitcoin(address shitCoin) public { require(shitCoin != address(hourglass), "P3D isn't a shitcoin"); ERC20interface s = ERC20interface(shitCoin); s.transfer(msg.sender, s.balanceOf(address(this))); } } contract HourglassX { using SafeMath for uint256; using SafeMath for uint; using SafeMath for int256; modifier onlyOwner { require(msg.sender == owner); _; } modifier playerBookEnabled { require(address(playerBook) != NULL_ADDRESS, "named referrals not enabled"); _; } // Make the thing constructor(address h, address p) public { // Set up ERC20 values name = "PoWH3D Extended"; symbol = "P3X"; decimals = 18; totalSupply = 0; // Add external contracts hourglass = Hourglass(h); playerBook = TeamJustPlayerBook(p); // Set referral requirement to be the same as P3D by default. referralRequirement = hourglass.stakingRequirement(); // Yes I could deploy 2 contracts myself, but I'm lazy. :^) refHandler = new HourglassXReferralHandler(hourglass); // Internal stuffs ignoreTokenFallbackEnable = false; owner = msg.sender; } // HourglassX-specific data address owner; address newOwner; uint256 referralRequirement; uint256 internal profitPerShare = 0; uint256 public lastTotalBalance = 0; uint256 constant internal ROUNDING_MAGNITUDE = 2**64; address constant internal NULL_ADDRESS = 0x0000000000000000000000000000000000000000; // I would get this from hourglass, but these values are inaccessable to the public. uint8 constant internal HOURGLASS_FEE = 10; uint8 constant internal HOURGLASS_BONUS = 3; // External contracts Hourglass internal hourglass; HourglassXReferralHandler internal refHandler; TeamJustPlayerBook internal playerBook; // P3X Specific data mapping(address => int256) internal payouts; mapping(address => uint256) internal bonuses; mapping(address => address) public savedReferral; // Futureproofing stuffs mapping(address => mapping (address => bool)) internal ignoreTokenFallbackList; bool internal ignoreTokenFallbackEnable; // Gauntlets mapping(address => uint256) internal gauntletBalance; mapping(address => uint256) internal gauntletEnd; mapping(address => uint8) internal gauntletType; // 1 = Time, 2 = P3D Supply, 3 = External // Normal token data mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) internal allowances; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; // --Events event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint value); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // Q: Why do you have 2 transfer events? // A: Because keccak256("Transfer(address,address,uint256)") != keccak256("Transfer(address,address,uint256,bytes)") // and etherscan listens for the former. event onTokenPurchase( address indexed accountHolder, uint256 ethereumSpent, uint256 tokensCreated, // If P3D is given to the contract, that amount in P3X will be given to the next buyer since we have no idea who gave us the P3D. uint256 tokensGiven, address indexed referrer, uint8 indexed bitFlags // 1 = invalidMasternode, 2 = usedHourglassMasternode, 4 = reinvestment ); event onTokenSell( address indexed accountHolder, uint256 tokensDestroyed, uint256 ethereumEarned ); event onWithdraw( address indexed accountHolder, uint256 earningsWithdrawn, uint256 refBonusWithdrawn, bool indexed reinvestment ); event onDonatedDividends( address indexed donator, uint256 ethereumDonated ); event onGauntletAcquired( address indexed strongHands, uint256 stakeAmount, uint8 indexed gauntletType, uint256 end ); event onExternalGauntletAcquired( address indexed strongHands, uint256 stakeAmount, address indexed extGauntlet ); // --Events-- // --Owner only functions function setNewOwner(address o) public onlyOwner { newOwner = o; } function acceptNewOwner() public { require(msg.sender == newOwner); owner = msg.sender; } // P3D allows re-branding, makes sense if P3X allows it too. function rebrand(string memory n, string memory s) public onlyOwner { name = n; symbol = s; } // P3X selling point: _lower staking requirement than P3D!!_ function setReferralRequirement(uint256 r) public onlyOwner { referralRequirement = r; } // Enables the function defined below. function allowIgnoreTokenFallback() public onlyOwner { ignoreTokenFallbackEnable = true; } // --Owner only functions-- // --Public write functions // Ethereum _might_ implement something where every address, including ones controlled by humans, is a smart contract. // Obviously transfering P3X to other people with no fee is one of its selling points. // A somewhat future-proofing fix is for the sender to specify that their recipiant is human if such a change ever takes place. // However, due to the popularity of ERC223, this might not be necessary. function ignoreTokenFallback(address to, bool ignore) public { require(ignoreTokenFallbackEnable, "This function is disabled"); ignoreTokenFallbackList[msg.sender][to] = ignore; } // Transfer tokens to the specified address, call the specified function, and pass the specified data function transfer(address payable to, uint value, bytes memory data, string memory func) public returns(bool) { actualTransfer(msg.sender, to, value, data, func, true); return true; } // Transfer tokens to the specified address, call tokenFallback, and pass the specified data function transfer(address payable to, uint value, bytes memory data) public returns(bool) { actualTransfer(msg.sender, to, value, data, "", true); return true; } // Transfer tokens to the specified address, call tokenFallback if applicable function transfer(address payable to, uint value) public returns(bool) { actualTransfer(msg.sender, to, value, "", "", !ignoreTokenFallbackList[msg.sender][to]); return true; } // Allow someone else to spend your tokens function approve(address spender, uint value) public returns(bool) { require(updateUsableBalanceOf(msg.sender) >= value, "Insufficient balance to approve"); allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // Have that someone else spend your tokens function transferFrom(address payable from, address payable to, uint value) public returns(bool success) { uint256 allowance = allowances[from][msg.sender]; require(allowance > 0, "Not approved"); require(allowance >= value, "Over spending limit"); allowances[from][msg.sender] = allowance.sub(value); actualTransfer(from, to, value, "", "", false); return true; } // The fallback function function() payable external{ // Only accept free ETH from the hourglass and from our child slave. if (msg.sender != address(hourglass) && msg.sender != address(refHandler)) { // Now, sending ETH increases the balance _before_ the transaction has been fully processed. // We don't want to distribute the entire purchase order as dividends. if (msg.value > 0) { lastTotalBalance += msg.value; distributeDividends(0, NULL_ADDRESS); lastTotalBalance -= msg.value; } createTokens(msg.sender, msg.value, NULL_ADDRESS, false); } } // Worried about having weak hands? Put on an optional gauntlet. // Prevents you from selling or transfering a specified amount of tokens function acquireGauntlet(uint256 amount, uint8 gType, uint256 end) public{ require(amount <= balances[msg.sender], "Insufficient balance"); // We need to apply the data first in order to prevent re-entry attacks. // ExternalGauntletInterface.gauntletRequirement _is_ a function which can change the state, after all. uint256 oldGauntletType = gauntletType[msg.sender]; uint256 oldGauntletBalance = gauntletBalance[msg.sender]; uint256 oldGauntletEnd = gauntletEnd[msg.sender]; gauntletType[msg.sender] = gType; gauntletEnd[msg.sender] = end; gauntletBalance[msg.sender] = amount; if (oldGauntletType == 0) { if (gType == 1) { require(end >= (block.timestamp + 97200), "Gauntlet time must be >= 4 weeks"); //97200 seconds = 3 weeks and 6 days. emit onGauntletAcquired(msg.sender, amount, gType, end); } else if (gType == 2) { uint256 P3DSupply = hourglass.totalSupply(); require(end >= (P3DSupply + (P3DSupply / 5)), "Gauntlet must make a profit"); // P3D buyers are down 19% when they buy, so make gauntlet gainz a minimum of 20%. emit onGauntletAcquired(msg.sender, amount, gType, end); } else if (gType == 3) { require(end <= 0x00ffffffffffffffffffffffffffffffffffffffff, "Invalid address"); require(ExternalGauntletInterface(address(end)).gauntletRequirement(msg.sender, 0, amount), "External gauntlet check failed"); emit onExternalGauntletAcquired(msg.sender, amount, address(end)); } else { revert("Invalid gauntlet type"); } } else if (oldGauntletType == 3) { require(gType == 3, "New gauntlet must be same type"); require(end == gauntletEnd[msg.sender], "Must be same external gauntlet"); require(ExternalGauntletInterface(address(end)).gauntletRequirement(msg.sender, oldGauntletBalance, amount), "External gauntlet check failed"); emit onExternalGauntletAcquired(msg.sender, amount, address(end)); } else { require(gType == oldGauntletType, "New gauntlet must be same type"); require(end > oldGauntletEnd, "Gauntlet must be an upgrade"); require(amount >= oldGauntletBalance, "New gauntlet must hold more tokens"); emit onGauntletAcquired(msg.sender, amount, gType, end); } } function acquireExternalGauntlet(uint256 amount, address extGauntlet) public{ acquireGauntlet(amount, 3, uint256(extGauntlet)); } // Throw your money at this thing with a referrer specified by their Ethereum address. // Returns the amount of tokens created. function buy(address referrerAddress) payable public returns(uint256) { // Now, sending ETH increases the balance _before_ the transaction has been fully processed. // We don't want to distribute the entire purchase order as dividends. if (msg.value > 0) { lastTotalBalance += msg.value; distributeDividends(0, NULL_ADDRESS); lastTotalBalance -= msg.value; } return createTokens(msg.sender, msg.value, referrerAddress, false); } // I'm only copy/pasting these functions due to the stack limit. // Throw your money at this thing with a referrer specified by their team JUST playerbook name. // Returns the amount of tokens created. function buy(string memory referrerName) payable public playerBookEnabled returns(uint256) { address referrerAddress = getAddressFromReferralName(referrerName); // As I said before, we don't want to distribute the entire purchase order as dividends. if (msg.value > 0) { lastTotalBalance += msg.value; distributeDividends(0, NULL_ADDRESS); lastTotalBalance -= msg.value; } return createTokens(msg.sender, msg.value, referrerAddress, false); } // Use all the ETH you earned hodling P3X to buy more P3X. // Returns the amount of tokens created. function reinvest() public returns(uint256) { address accountHolder = msg.sender; distributeDividends(0, NULL_ADDRESS); // Just in case P3D-only transactions happened. uint256 payout; uint256 bonusPayout; (payout, bonusPayout) = clearDividends(accountHolder); emit onWithdraw(accountHolder, payout, bonusPayout, true); return createTokens(accountHolder, payout + bonusPayout, NULL_ADDRESS, true); } // Use some of the ETH you earned hodling P3X to buy more P3X. // You can withdraw the rest or keept it in here allocated for you. // Returns the amount of tokens created. function reinvestPartial(uint256 ethToReinvest, bool withdrawAfter) public returns(uint256 tokensCreated) { address payable accountHolder = msg.sender; distributeDividends(0, NULL_ADDRESS); // Just in case P3D-only transactions happened. uint256 payout = dividendsOf(accountHolder, false); uint256 bonusPayout = bonuses[accountHolder]; uint256 payoutReinvested = 0; uint256 bonusReinvested; require((payout + bonusPayout) >= ethToReinvest, "Insufficient balance for reinvestment"); // We're going to take ETH out of the masternode bonus first, then the outstanding divs. if (ethToReinvest > bonusPayout){ payoutReinvested = ethToReinvest - bonusPayout; bonusReinvested = bonusPayout; // Take ETH out from outstanding dividends. payouts[accountHolder] += int256(payoutReinvested * ROUNDING_MAGNITUDE); }else{ bonusReinvested = ethToReinvest; } // Take ETH from the masternode bonus. bonuses[accountHolder] -= bonusReinvested; emit onWithdraw(accountHolder, payoutReinvested, bonusReinvested, true); // Do the buy thing! tokensCreated = createTokens(accountHolder, ethToReinvest, NULL_ADDRESS, true); if (withdrawAfter && dividendsOf(msg.sender, true) > 0) { withdrawDividends(msg.sender); } return tokensCreated; } // I'm just a man who loves "default variables" function reinvestPartial(uint256 ethToReinvest) public returns(uint256) { return reinvestPartial(ethToReinvest, true); } // There's literally no reason to call this function function sell(uint256 amount, bool withdrawAfter) public returns(uint256) { require(amount > 0, "You have to sell something"); uint256 sellAmount = destroyTokens(msg.sender, amount); if (withdrawAfter && dividendsOf(msg.sender, true) > 0) { withdrawDividends(msg.sender); } return sellAmount; } // Again with the default variables! function sell(uint256 amount) public returns(uint256) { require(amount > 0, "You have to sell something"); return destroyTokens(msg.sender, amount); } // Transfer the sender's masternode bonuses and their outstanding divs to their wallet. function withdraw() public{ require(dividendsOf(msg.sender, true) > 0, "No dividends to withdraw"); withdrawDividends(msg.sender); } // There's definitely no reason to call this function function exit() public{ address payable accountHolder = msg.sender; uint256 balance = balances[accountHolder]; if (balance > 0) { destroyTokens(accountHolder, balance); } if (dividendsOf(accountHolder, true) > 0) { withdrawDividends(accountHolder); } } // Since website won't be released on launch, provide something on etherscan which will allow users to easily set masternodes. function setReferrer(address ref) public{ savedReferral[msg.sender] = ref; } // Same as above except using the team JUST player book function setReferrer(string memory refName) public{ savedReferral[msg.sender] = getAddressFromReferralName(refName); } // Another P3X selling point: Get P3X-exclusive didvidends _combined with_ P3D dividends! function donateDividends() payable public{ distributeDividends(0, NULL_ADDRESS); emit onDonatedDividends(msg.sender, msg.value); } // --Public write functions-- // --Public read-only functions // Returns the P3D address. function baseHourglass() external view returns(address) { return address(hourglass); } // Returns the salve account address (was mostly used for debugging purposes) function refHandlerAddress() external view returns(address) { return address(refHandler); } // Get someone's address from their team JUST playerbook name function getAddressFromReferralName(string memory refName) public view returns (address){ return playerBook.getPlayerAddr(playerBook.pIDxName_(stringToBytes32(refName))); } // Retruns an addresses gauntlet type. function gauntletTypeOf(address accountHolder) public view returns(uint stakeAmount, uint gType, uint end) { if (isGauntletExpired(accountHolder)) { return (0, 0, gauntletEnd[accountHolder]); } else { return (gauntletBalance[accountHolder], gauntletType[accountHolder], gauntletEnd[accountHolder]); } } // Same as above except for msg.sender function myGauntletType() public view returns(uint stakeAmount, uint gType, uint end) { return gauntletTypeOf(msg.sender); } // Returns an addresse's P3X balance minus what they have in their gauntlet. function usableBalanceOf(address accountHolder) public view returns(uint balance) { if (isGauntletExpired(accountHolder)) { return balances[accountHolder]; } else { return balances[accountHolder].sub(gauntletBalance[accountHolder]); } } // Same as above except for msg.sender function myUsableBalance() public view returns(uint balance) { return usableBalanceOf(msg.sender); } // I mean, every ERC20 token has this function. I'm sure you know what it does. function balanceOf(address accountHolder) external view returns(uint balance) { return balances[accountHolder]; } // Same as above except for msg.sender function myBalance() public view returns(uint256) { return balances[msg.sender]; } // See if the specified sugardaddy allows the spender to spend their tokens function allowance(address sugardaddy, address spender) external view returns(uint remaining) { return allowances[sugardaddy][spender]; } // Returns all the ETH that this contract has access to function totalBalance() public view returns(uint256) { return address(this).balance + hourglass.myDividends(true) + refHandler.totalBalance(); } // Returns the ETH the specified address is owed. function dividendsOf(address customerAddress, bool includeReferralBonus) public view returns(uint256) { uint256 divs = uint256(int256(profitPerShare * balances[customerAddress]) - payouts[customerAddress]) / ROUNDING_MAGNITUDE; if (includeReferralBonus) { divs += bonuses[customerAddress]; } return divs; } // Same as above except includes the masternode bonus function dividendsOf(address customerAddress) public view returns(uint256) { return dividendsOf(customerAddress, true); } // Alias of dividendsOf(msg.sender) function myDividends() public view returns(uint256) { return dividendsOf(msg.sender, true); } // Alias of dividendsOf(msg.sender, includeReferralBonus) function myDividends(bool includeReferralBonus) public view returns(uint256) { return dividendsOf(msg.sender, includeReferralBonus); } // Returns the masternode earnings of a specified account function refBonusOf(address customerAddress) external view returns(uint256) { return bonuses[customerAddress]; } // Same as above xcept with msg.sender function myRefBonus() external view returns(uint256) { return bonuses[msg.sender]; } // Backwards compatibility with the P3D interface function stakingRequirement() external view returns(uint256) { return referralRequirement; } // Backwards compatibility with the P3D interface function calculateTokensReceived(uint256 ethereumToSpend) public view returns(uint256) { return hourglass.calculateTokensReceived(ethereumToSpend); } // Backwards compatibility with the P3D interface function calculateEthereumReceived(uint256 tokensToSell) public view returns(uint256) { return hourglass.calculateEthereumReceived(tokensToSell); } // --Public read-only functions-- // Internal functions // Returns true if the gauntlet has expired. Otherwise, false. function isGauntletExpired(address holder) internal view returns(bool) { if (gauntletType[holder] != 0) { if (gauntletType[holder] == 1) { return (block.timestamp >= gauntletEnd[holder]); } else if (gauntletType[holder] == 2) { return (hourglass.totalSupply() >= gauntletEnd[holder]); } else if (gauntletType[holder] == 3) { return ExternalGauntletInterface(gauntletEnd[holder]).gauntletRemovable(holder); } } return false; } // Same as usableBalanceOf, except the gauntlet is lifted when it's expired. function updateUsableBalanceOf(address holder) internal returns(uint256) { // isGauntletExpired is a _view_ function, with uses STATICCALL in solidity 0.5.0 or later. // Since STATICCALLs can't modifiy the state, re-entry attacks aren't possible here. if (isGauntletExpired(holder)) { if (gauntletType[holder] == 3){ emit onExternalGauntletAcquired(holder, 0, NULL_ADDRESS); }else{ emit onGauntletAcquired(holder, 0, 0, 0); } gauntletType[holder] = 0; gauntletBalance[holder] = 0; return balances[holder]; } return balances[holder] - gauntletBalance[holder]; } // This is the actual buy function function createTokens(address creator, uint256 eth, address referrer, bool reinvestment) internal returns(uint256) { // Let's not call the parent hourglass all the time. uint256 parentReferralRequirement = hourglass.stakingRequirement(); // How much ETH will be given to the referrer if there is one. uint256 referralBonus = eth / HOURGLASS_FEE / HOURGLASS_BONUS; bool usedHourglassMasternode = false; bool invalidMasternode = false; if (referrer == NULL_ADDRESS) { referrer = savedReferral[creator]; } // Solidity has limited amount of local variables, so the memory allocated to this one gets reused for other purposes later. //uint256 refHandlerBalance = hourglass.balanceOf(address(refHandler)); uint256 tmp = hourglass.balanceOf(address(refHandler)); // Let's once again pretend this actually prevents people from cheating. if (creator == referrer) { // Tell everyone that no referral purchase was made because cheating (unlike P3D) invalidMasternode = true; } else if (referrer == NULL_ADDRESS) { usedHourglassMasternode = true; // Make sure that the referrer has enough funds to _be_ a referrer, and make sure that we have our own P3D masternode to get that extra ETH } else if (balances[referrer] >= referralRequirement && (tmp >= parentReferralRequirement || hourglass.balanceOf(address(this)) >= parentReferralRequirement)) { // It's a valid P3X masternode, hooray! (do nothing) } else if (hourglass.balanceOf(referrer) >= parentReferralRequirement) { usedHourglassMasternode = true; } else { // Tell everyone that no referral purchase was made because not enough balance (again, unlike P3D) invalidMasternode = true; } // Thanks to Crypto McPump for helping me _not_ waste gas here. /* uint256 createdTokens = hourglass.calculateTokensReceived(eth); // See? Look how much gas I would have wasted. totalSupply += createdTokens; */ uint256 createdTokens = hourglass.totalSupply(); // KNOWN BUG: If lord Justo increases the staking requirement to something above both of the contract's P3D // balance, then all masternodes won't work until there are enough buy orders to make the refHandler's P3D // balance above P3D's masternode requirement. // if the refHandler hass less P3D than P3D's masternode requirement, then it should buy the tokens. if (tmp < parentReferralRequirement) { if (reinvestment) { // We need to know if the refHandler has enough ETH to do the reinvestment on its own //uint256 refHandlerEthBalance = refHandler.totalBalance(); tmp = refHandler.totalBalance(); if (tmp < eth) { // If it doesn't, then we must transfer it the remaining ETH it needs. tmp = eth - tmp; // fundsToGive = eth - refHandlerEthBalance; if (address(this).balance < tmp) { // If this fails, something went horribly wrong because the client is attempting to reinvest more ethereum than we've got hourglass.withdraw(); } address(refHandler).transfer(tmp); } tmp = hourglass.balanceOf(address(refHandler)); // Reinvestments are always done using the null referrer refHandler.buyTokensFromBalance(NULL_ADDRESS, eth); } else { // these nested ? statements are only here because I can only have a limited amount of local variables. // Forward the ETH we were sent to the refHandler to place the buy order. refHandler.buyTokens.value(eth)(invalidMasternode ? NULL_ADDRESS : (usedHourglassMasternode ? referrer : address(this))); } } else { if (reinvestment) { // If we don't have enough ETH to do the reinvestment, withdraw. if (address(this).balance < eth && hourglass.myDividends(true) > 0) { hourglass.withdraw(); } // If we _still_ don't have enough ETH to do the reinvestment, have the refHandler sends us some. if (address(this).balance < eth) { refHandler.sendETH(address(this), eth - address(this).balance); } } hourglass.buy.value(eth)(invalidMasternode ? NULL_ADDRESS : (usedHourglassMasternode ? referrer : address(refHandler))); } // Use the delta from before and after the buy order to get the amount of P3D created. createdTokens = hourglass.totalSupply() - createdTokens; totalSupply += createdTokens; // This is here for when someone transfers P3D to the contract directly. We have no way of knowing who it's from, so we'll just give it to the next person who happens to buy. uint256 bonusTokens = hourglass.myTokens() + tmp - totalSupply; // Here I now re-use that uint256 to create the bit flags. tmp = 0; if (invalidMasternode) { tmp |= 1; } if (usedHourglassMasternode) { tmp |= 2; } if (reinvestment) { tmp |= 4; } emit onTokenPurchase(creator, eth, createdTokens, bonusTokens, referrer, uint8(tmp)); createdTokens += bonusTokens; // We can finally give the P3X to the buyer! balances[creator] += createdTokens; totalSupply += bonusTokens; //Updates services like etherscan which track token hodlings. emit Transfer(address(this), creator, createdTokens, ""); emit Transfer(address(this), creator, createdTokens); // Unfortunatly, SafeMath cannot be used here, otherwise the stack gets too deep payouts[creator] += int256(profitPerShare * createdTokens); // You don't deserve the dividends before you owned the tokens. if (reinvestment) { // No dividend distribution underflows allowed. // Ethereum has been given away after a "reinvestment" purchase, so we have to keep track of that. lastTotalBalance = lastTotalBalance.sub(eth); } distributeDividends((usedHourglassMasternode || invalidMasternode) ? 0 : referralBonus, referrer); if (referrer != NULL_ADDRESS) { // Save the referrer for next time! savedReferral[creator] = referrer; } return createdTokens; } // This is marked as an internal function because selling could have been the result of transfering P3X to the contract via a transferFrom transaction. function destroyTokens(address weakHand, uint256 bags) internal returns(uint256) { require(updateUsableBalanceOf(weakHand) >= bags, "Insufficient balance"); // Give the weak hand the last of their deserved payout. // Also updates lastTotalBalance distributeDividends(0, NULL_ADDRESS); uint256 tokenBalance = hourglass.myTokens(); // We can't rely on ETH balance delta because we get cut of the sell fee ourselves. uint256 ethReceived = hourglass.calculateEthereumReceived(bags); lastTotalBalance += ethReceived; if (tokenBalance >= bags) { hourglass.sell(bags); } else { // If we don't have enough P3D to sell ourselves, get the slave to sell some, too. if (tokenBalance > 0) { hourglass.sell(tokenBalance); } refHandler.sellTokens(bags - tokenBalance); } // Put the ETH in outstanding dividends, and allow the weak hand access to the divs they've accumilated before they sold. int256 updatedPayouts = int256(profitPerShare * bags + (ethReceived * ROUNDING_MAGNITUDE)); payouts[weakHand] = payouts[weakHand].sub(updatedPayouts); // We already checked the balance of the weakHanded person, so SafeMathing here is redundant. balances[weakHand] -= bags; totalSupply -= bags; emit onTokenSell(weakHand, bags, ethReceived); // Tell etherscan of this tragity. emit Transfer(weakHand, address(this), bags, ""); emit Transfer(weakHand, address(this), bags); return ethReceived; } // sends ETH to the specified account, using all the ETH P3X has access to. function sendETH(address payable to, uint256 amount) internal { uint256 childTotalBalance = refHandler.totalBalance(); uint256 thisBalance = address(this).balance; uint256 thisTotalBalance = thisBalance + hourglass.myDividends(true); if (childTotalBalance >= amount) { // the refHanlder has enough of its own ETH to send, so it should do that. refHandler.sendETH(to, amount); } else if (thisTotalBalance >= amount) { // We have enough ETH of our own to send. if (thisBalance < amount) { hourglass.withdraw(); } to.transfer(amount); } else { // Neither we nor the refHandler has enough ETH to send individually, so both contracts have to send ETH. refHandler.sendETH(to, childTotalBalance); if (hourglass.myDividends(true) > 0) { hourglass.withdraw(); } to.transfer(amount - childTotalBalance); } // keep the dividend tracker in check. lastTotalBalance = lastTotalBalance.sub(amount); } // Take the ETH we've got and distribute it among our token holders. function distributeDividends(uint256 bonus, address bonuser) internal{ // Prevents "HELP I WAS THE LAST PERSON WHO SOLD AND I CAN'T WITHDRAW MY ETH WHAT DO????" (dividing by 0 results in a crash) if (totalSupply > 0) { uint256 tb = totalBalance(); uint256 delta = tb - lastTotalBalance; if (delta > 0) { // We have more ETH than before, so we'll just distribute those dividends among our token holders. if (bonus != 0) { bonuses[bonuser] += bonus; } profitPerShare = profitPerShare.add(((delta - bonus) * ROUNDING_MAGNITUDE) / totalSupply); lastTotalBalance += delta; } } } // Clear out someone's dividends. function clearDividends(address accountHolder) internal returns(uint256, uint256) { uint256 payout = dividendsOf(accountHolder, false); uint256 bonusPayout = bonuses[accountHolder]; payouts[accountHolder] += int256(payout * ROUNDING_MAGNITUDE); bonuses[accountHolder] = 0; // External apps can now get reliable masternode statistics return (payout, bonusPayout); } // Withdraw 100% of someone's dividends function withdrawDividends(address payable accountHolder) internal { distributeDividends(0, NULL_ADDRESS); // Just in case P3D-only transactions happened. uint256 payout; uint256 bonusPayout; (payout, bonusPayout) = clearDividends(accountHolder); emit onWithdraw(accountHolder, payout, bonusPayout, false); sendETH(accountHolder, payout + bonusPayout); } // The internal transfer function. function actualTransfer (address payable from, address payable to, uint value, bytes memory data, string memory func, bool careAboutHumanity) internal{ require(updateUsableBalanceOf(from) >= value, "Insufficient balance"); require(to != address(refHandler), "My slave doesn't get paid"); // I don't know why anyone would do this, but w/e require(to != address(hourglass), "P3D has no need for these"); // Prevent l33x h4x0rs from having P3X call arbitrary P3D functions. if (to == address(this)) { // Treat transfers to this contract as a sell and withdraw order. if (value == 0) { // Transfers of 0 still have to be emitted... for some reason. emit Transfer(from, to, value, data); emit Transfer(from, to, value); } else { destroyTokens(from, value); } withdrawDividends(from); } else { distributeDividends(0, NULL_ADDRESS); // Just in case P3D-only transactions happened. // I was going to add a value == 0 check here, but if you're sending 0 tokens to someone, you deserve to pay for wasted gas. // Throwing an exception undos all changes. Otherwise changing the balance now would be a shitshow balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); // Sender can have their dividends from when they owned the tokens payouts[from] -= int256(profitPerShare * value); // Receiver is not allowed to have dividends from before they owned the tokens. payouts[to] += int256(profitPerShare * value); if (careAboutHumanity && isContract(to)) { if (bytes(func).length == 0) { ERC223Handler receiver = ERC223Handler(to); receiver.tokenFallback(from, value, data); } else { bool success; bytes memory returnData; (success, returnData) = to.call.value(0)(abi.encodeWithSignature(func, from, value, data)); assert(success); } } emit Transfer(from, to, value, data); emit Transfer(from, to, value); } } // The playerbook contract accepts a bytes32. We'll be converting for convenience sense. function bytesToBytes32(bytes memory data) internal pure returns(bytes32){ uint256 result = 0; uint256 len = data.length; uint256 singleByte; for (uint256 i = 0; i<len; i+=1){ singleByte = uint256(uint8(data[i])) << ( (31 - i) * 8); require(singleByte != 0, "bytes cannot contain a null byte"); result |= singleByte; } return bytes32(result); } // haha casting types. function stringToBytes32(string memory data) internal pure returns(bytes32){ return bytesToBytes32(bytes(data)); } // If bytecode exists at _addr then the _addr is a contract. function isContract(address _addr) internal view returns(bool) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } // Reject possible accidental sendin of higher-tech shitcoins. (with a fancy message) function tokenFallback(address from, uint value, bytes memory data) public pure{ revert("I don't want your shitcoins!"); } // Allow anyone else to take forcefully sent low-tech shitcoins. (I sure as hell don't want them) function takeShitcoin(address shitCoin) public{ // Don't allow people to siphon funds from us require(shitCoin != address(hourglass), "P3D isn't a shitcoin"); ERC20interface s = ERC20interface(shitCoin); s.transfer(msg.sender, s.balanceOf(address(this))); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns(uint256 c) { if (a == 0 || b == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns(uint256 c) { c = a + b; assert(c >= a); return c; } /** * @dev Subtracts two numbers, throws on underflow */ function sub(int256 a, int256 b) internal pure returns(int256 c) { c = a - b; assert(c <= a); return c; } /** * @dev Adds two numbers, throws on overflow. */ function add(int256 a, int256 b) internal pure returns(int256 c) { c = a + b; assert(c >= a); return c; } }
Get someone's address from their team JUST playerbook name
function getAddressFromReferralName(string memory refName) public view returns (address){ return playerBook.getPlayerAddr(playerBook.pIDxName_(stringToBytes32(refName))); }
1,779,027
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Delegated.sol"; contract TheOtherSideToken is ERC20Burnable, Delegated { using Address for address; bytes32 public merkleRoot; address public treasuryAddress; /** * @dev Data structure for Whitelist Mint claim */ struct WhitelistMintClaim { uint256 mintedQty; } /** * @dev Mapping of the owner's address with the no. of qyt claim. */ mapping(address => WhitelistMintClaim) public WhitelistMintClaimed; constructor() ERC20("The Other Side Token", "MOONZ") { } /** @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 to, uint256 amount) external onlyDelegates { _mint(to, amount); } /** * @dev OnlyDelegates/Owner can destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public override onlyDelegates { _burn(_msgSender(), amount); } /** * @dev OnlyDelegates/Owner can destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public override onlyDelegates { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } /** * @dev OnlyDelegates/Owner can set the Merkleroot */ function setMerkleRoot(bytes32 _merkleRoot) external onlyDelegates { require(merkleRoot != _merkleRoot,"TOS: Merkle root is the same as the previous value"); merkleRoot = _merkleRoot; } /** * @dev OnlyDelegates/Owner can perform bulkPublicMint */ function bulkPublicMint(address[] memory to_, uint256[] memory amounts_) external onlyDelegates { require(to_.length == amounts_.length, "TOS: To address and Amounts length Mismatch!"); for (uint256 i = 0; i < to_.length; i++) { _mint(to_[i], amounts_[i]); } } /** * @dev OnlyDelegates/Owner can perform bulk transfer a tokens */ function bulkTransfer(address[] memory to_, uint256[] memory amounts_) external onlyDelegates { require(to_.length == amounts_.length, "TOS: To and Amounts length Mismatch!"); for (uint256 i = 0; i < to_.length; i++) { transfer(to_[i], amounts_[i]); } } /** * @dev OnlyDelegates/Owner can perform bulk transferfrom a tokens */ function bulkTransferFrom(address[] memory from_, address[] memory to_, uint256[] memory amounts_) external onlyDelegates { require(from_.length == to_.length && from_.length == amounts_.length, "TOS: From, To, and Amounts length Mismatch!"); for (uint256 i = 0; i < from_.length; i++) { transferFrom(from_[i], to_[i], amounts_[i]); } } /** * @dev Public can perform mint provided that owner's account is whitelisted. * It is based on the merkle proof to verified if the owner's address is able to mint or not. */ function whitelistMint(uint256 _mintableQty, uint256 _totalQty,bytes32[] calldata _merkleProof, bytes32 _leaf) public { require(keccak256(abi.encodePacked(convertQtyWithOwnerToStr(_totalQty,msg.sender))) == _leaf,"TOS: Hashing of Qty+wallet doesn't match with leaf node"); require((WhitelistMintClaimed[msg.sender].mintedQty + _mintableQty) <= _totalQty,"TOS: mintedQty + _mintableQty must be less than or equal to _totalQty"); require( MerkleProof.verify(_merkleProof,merkleRoot, _leaf),"TOS: Invalid Merkle Proof."); _mint(msg.sender,_mintableQty); WhitelistMintClaimed[msg.sender].mintedQty += _mintableQty; } /** * @dev Converts qty+wallet address of the owner to string */ function convertQtyWithOwnerToStr(uint256 _qty, address _owner) internal pure returns(string memory) { string memory _qtyToStr = Strings.toString(_qty); string memory _ownerAddressToStr = Strings.toHexString(uint256(uint160(_owner)), 20); return string(abi.encodePacked(_qtyToStr,_ownerAddressToStr)); } /** * @dev Sets the treasury address */ function setTreasuryAddress(address _treasuryAddress) external onlyDelegates { require(treasuryAddress != _treasuryAddress, "TOS: new treasury address is the same as the new address "); treasuryAddress = _treasuryAddress; } /** * @dev Transfer to treasury account. */ function transferToTreasury(uint256 amounts) external { transfer(treasuryAddress,amounts); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; contract Delegated is Ownable { mapping(address => bool) internal _delegates; constructor(){ _delegates[owner()] = true; } modifier onlyDelegates { require(_delegates[msg.sender], "Invalid delegate" ); _; } //onlyOwner function isDelegate( address addr ) external view onlyOwner returns ( bool ){ return _delegates[addr]; } function setDelegate( address addr, bool isDelegate_ ) external onlyOwner{ _delegates[addr] = isDelegate_; } function transferOwnership(address newOwner) public virtual override onlyOwner { _delegates[newOwner] = true; super.transferOwnership( newOwner ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // 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); }
OnlyDelegates/Owner can perform bulk transfer a tokens/
function bulkTransfer(address[] memory to_, uint256[] memory amounts_) external onlyDelegates { require(to_.length == amounts_.length, "TOS: To and Amounts length Mismatch!"); for (uint256 i = 0; i < to_.length; i++) { transfer(to_[i], amounts_[i]); } }
13,970,943
// Copyright 2018 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. // A testable version of the `InnerOwnedSet` and `OuterSet` contracts that // exposes some internal state and overrides de default system address. pragma solidity ^0.4.22; import "../RelayedOwnedSet.sol"; import "../RelaySet.sol"; contract TestRelaySet is RelaySet { constructor(address _systemAddress) public { systemAddress = _systemAddress; } } contract TestRelayedOwnedSet is RelayedOwnedSet { constructor(address _outerSet, address[] _initial) RelayedOwnedSet(_outerSet, _initial) public { } // expose `status` to use for assertions in tests function getStatus(address _validator) public view returns (bool isIn, uint index) { AddressStatus storage addressStatus = status[_validator]; isIn = addressStatus.isIn; index = addressStatus.index; } }
expose `status` to use for assertions in tests
function getStatus(address _validator) public view returns (bool isIn, uint index) { AddressStatus storage addressStatus = status[_validator]; isIn = addressStatus.isIn; index = addressStatus.index; }
6,380,894
./partial_match/1/0x3300b3c4a4f733Cc1BD3986ECbb4b397AB733dD2/sources/contracts/token/IERC20.sol
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer( address recipient, uint256 amount ) external returns (bool); function allowance( address owner, address spender ) external view returns (uint256); function approve( address spender, uint256 amount ) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); }
4,292,506
/** *Submitted for verification at Etherscan.io on 2021-09-05 */ // solhint-disable-next-line pragma solidity 0.4.26; // solhint-disable func-order contract GenePoolInterface { // signals is gene pool function isGenePool() public pure returns (bool); // breeds two parents and returns childs genes function breed(uint256[2] mother, uint256[2] father, uint256 seed) public view returns (uint256[2]); // generates (psuedo) random Pepe DNA function randomDNA(uint256 seed) public pure returns (uint256[2]); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Usernames { mapping(address => bytes32) public addressToUser; mapping(bytes32 => address) public userToAddress; event UserNamed(address indexed user, bytes32 indexed username); /** * Claim a username. Frees up a previously used one * @param _username to claim */ function claimUsername(bytes32 _username) external { require(userToAddress[_username] == address(0));// Username must be free if (addressToUser[msg.sender] != bytes32(0)) { // If user already has username free it up userToAddress[addressToUser[msg.sender]] = address(0); } //all is well assign username addressToUser[msg.sender] = _username; userToAddress[_username] = msg.sender; emit UserNamed(msg.sender, _username); } } /** @title Beneficiary */ contract Beneficiary is Ownable { address public beneficiary; constructor() public { beneficiary = msg.sender; } /** * @dev Change the beneficiary address * @param _beneficiary Address of the new beneficiary */ function setBeneficiary(address _beneficiary) public onlyOwner { beneficiary = _beneficiary; } } /** @title Affiliate */ contract Affiliate is Ownable { mapping(address => bool) public canSetAffiliate; mapping(address => address) public userToAffiliate; /** @dev Allows an address to set the affiliate address for a user * @param _setter The address that should be allowed */ function setAffiliateSetter(address _setter) public onlyOwner { canSetAffiliate[_setter] = true; } /** * @dev Set the affiliate of a user * @param _user user to set affiliate for * @param _affiliate address to set */ function setAffiliate(address _user, address _affiliate) public { require(canSetAffiliate[msg.sender]); if (userToAffiliate[_user] == address(0)) { userToAffiliate[_user] = _affiliate; } } } contract ERC721 { function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) ; function transfer(address _to, uint256 _tokenId) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } contract PepeInterface is ERC721{ function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) public returns (bool); function getCozyAgain(uint256 _pepeId) public view returns(uint64); } /** @title AuctionBase */ contract AuctionBase is Beneficiary { mapping(uint256 => PepeAuction) public auctions;//maps pepes to auctions PepeInterface public pepeContract; Affiliate public affiliateContract; uint256 public fee = 37500; //in 1 10000th of a percent so 3.75% at the start uint256 public constant FEE_DIVIDER = 1000000; //Perhaps needs better name? struct PepeAuction { address seller; uint256 pepeId; uint64 auctionBegin; uint64 auctionEnd; uint256 beginPrice; uint256 endPrice; } event AuctionWon(uint256 indexed pepe, address indexed winner, address indexed seller); event AuctionStarted(uint256 indexed pepe, address indexed seller); event AuctionFinalized(uint256 indexed pepe, address indexed seller); constructor(address _pepeContract, address _affiliateContract) public { pepeContract = PepeInterface(_pepeContract); affiliateContract = Affiliate(_affiliateContract); } /** * @dev Return a pepe from a auction that has passed * @param _pepeId the id of the pepe to save */ function savePepe(uint256 _pepeId) external { // solhint-disable-next-line not-rely-on-time require(auctions[_pepeId].auctionEnd < now);//auction must have ended require(pepeContract.transfer(auctions[_pepeId].seller, _pepeId));//transfer pepe back to seller emit AuctionFinalized(_pepeId, auctions[_pepeId].seller); delete auctions[_pepeId];//delete auction } /** * @dev change the fee on pepe sales. Can only be lowerred * @param _fee The new fee to set. Must be lower than current fee */ function changeFee(uint256 _fee) external onlyOwner { require(_fee < fee);//fee can not be raised fee = _fee; } /** * @dev Start a auction * @param _pepeId Pepe to sell * @param _beginPrice Price at which the auction starts * @param _endPrice Ending price of the auction * @param _duration How long the auction should take */ function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public { require(pepeContract.transferFrom(msg.sender, address(this), _pepeId)); // solhint-disable-next-line not-rely-on-time require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active PepeAuction memory auction; auction.seller = msg.sender; auction.pepeId = _pepeId; // solhint-disable-next-line not-rely-on-time auction.auctionBegin = uint64(now); // solhint-disable-next-line not-rely-on-time auction.auctionEnd = uint64(now) + _duration; require(auction.auctionEnd > auction.auctionBegin); auction.beginPrice = _beginPrice; auction.endPrice = _endPrice; auctions[_pepeId] = auction; emit AuctionStarted(_pepeId, msg.sender); } /** * @dev directly start a auction from the PepeBase contract * @param _pepeId Pepe to put on auction * @param _beginPrice Price at which the auction starts * @param _endPrice Ending price of the auction * @param _duration How long the auction should take * @param _seller The address selling the pepe */ // solhint-disable-next-line max-line-length function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public { require(msg.sender == address(pepeContract)); //can only be called by pepeContract //solhint-disable-next-line not-rely-on-time require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active PepeAuction memory auction; auction.seller = _seller; auction.pepeId = _pepeId; // solhint-disable-next-line not-rely-on-time auction.auctionBegin = uint64(now); // solhint-disable-next-line not-rely-on-time auction.auctionEnd = uint64(now) + _duration; require(auction.auctionEnd > auction.auctionBegin); auction.beginPrice = _beginPrice; auction.endPrice = _endPrice; auctions[_pepeId] = auction; emit AuctionStarted(_pepeId, _seller); } /** * @dev Calculate the current price of a auction * @param _pepeId the pepeID to calculate the current price for * @return currentBid the current price for the auction */ function calculateBid(uint256 _pepeId) public view returns(uint256 currentBid) { PepeAuction storage auction = auctions[_pepeId]; // solhint-disable-next-line not-rely-on-time uint256 timePassed = now - auctions[_pepeId].auctionBegin; // If auction ended return auction end price. // solhint-disable-next-line not-rely-on-time if (now >= auction.auctionEnd) { return auction.endPrice; } else { // Can be negative int256 priceDifference = int256(auction.endPrice) - int256(auction.beginPrice); // Always positive int256 duration = int256(auction.auctionEnd) - int256(auction.auctionBegin); // As already proven in practice by CryptoKitties: // timePassed -> 64 bits at most // priceDifference -> 128 bits at most // timePassed * priceDifference -> 64 + 128 bits at most int256 priceChange = priceDifference * int256(timePassed) / duration; // Will be positive, both operands are less than 256 bits int256 price = int256(auction.beginPrice) + priceChange; return uint256(price); } } /** * @dev collect the fees from the auction */ function getFees() public { beneficiary.transfer(address(this).balance); } } /** @title CozyTimeAuction */ contract RebornCozyTimeAuction is AuctionBase { // solhint-disable-next-line constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public { } /** * @dev Start an auction * @param _pepeId The id of the pepe to start the auction for * @param _beginPrice Start price of the auction * @param _endPrice End price of the auction * @param _duration How long the auction should take */ function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public { // solhint-disable-next-line not-rely-on-time require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check super.startAuction(_pepeId, _beginPrice, _endPrice, _duration); } /** * @dev Start a auction direclty from the PepeBase smartcontract * @param _pepeId The id of the pepe to start the auction for * @param _beginPrice Start price of the auction * @param _endPrice End price of the auction * @param _duration How long the auction should take * @param _seller The address of the seller */ // solhint-disable-next-line max-line-length function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public { // solhint-disable-next-line not-rely-on-time require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check super.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, _seller); } /** * @dev Buy cozy right from the auction * @param _pepeId Pepe to cozy with * @param _cozyCandidate the pepe to cozy with * @param _candidateAsFather Is the _cozyCandidate father? * @param _pepeReceiver address receiving the pepe after cozy time */ // solhint-disable-next-line max-line-length function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable { require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract PepeAuction storage auction = auctions[_pepeId]; // solhint-disable-next-line not-rely-on-time require(now < auction.auctionEnd);// auction must be still going uint256 price = calculateBid(_pepeId); require(msg.value >= price);//must send enough ether uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed? //Send ETH to seller auction.seller.transfer(price - totalFee); //send ETH to beneficiary address affiliate = affiliateContract.userToAffiliate(_pepeReceiver); //solhint-disable-next-line if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate //nothing just to suppress warning } //actual cozytiming if (_candidateAsFather) { if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) { revert(); } } else { // Swap around the two pepes, they have no set gender, the user decides what they are. if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) { revert(); } } //Send pepe to seller of auction if (!pepeContract.transfer(auction.seller, _pepeId)) { revert(); //can't complete transfer if this fails } if (msg.value > price) { //return ether send to much _pepeReceiver.transfer(msg.value - price); } emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event delete auctions[_pepeId];//deletes auction } /** * @dev Buy cozytime and pass along affiliate * @param _pepeId Pepe to cozy with * @param _cozyCandidate the pepe to cozy with * @param _candidateAsFather Is the _cozyCandidate father? * @param _pepeReceiver address receiving the pepe after cozy time * @param _affiliate Affiliate address to set */ //solhint-disable-next-line max-line-length function buyCozyAffiliated(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver, address _affiliate) public payable { affiliateContract.setAffiliate(_pepeReceiver, _affiliate); buyCozy(_pepeId, _cozyCandidate, _candidateAsFather, _pepeReceiver); } } contract Genetic { // TODO mutations // maximum number of random mutations per chromatid uint8 public constant R = 5; // solhint-disable-next-line function-max-lines function breed(uint256[2] mother, uint256[2] father, uint256 seed) internal view returns (uint256[2] memOffset) { // Meiosis I: recombining alleles (Chromosomal crossovers) // Note about optimization I: no cell duplication, // producing 2 seeds/eggs per cell is enough, instead of 4 (like humans do) // Note about optimization II: crossovers happen, // but only 1 side of the result is computed, // as the other side will not affect anything. // solhint-disable-next-line no-inline-assembly assembly { // allocate output // 1) get the pointer to our memory memOffset := mload(0x40) // 2) Change the free-memory pointer to keep our memory // (we will only use 64 bytes: 2 values of 256 bits) mstore(0x40, add(memOffset, 64)) // Put seed in scratchpad 0 mstore(0x0, seed) // Also use the timestamp, best we could do to increase randomness // without increasing costs dramatically. (Trade-off) mstore(0x20, timestamp) // Hash it for a universally random bitstring. let hash := keccak256(0, 64) // Byzantium VM does not support shift opcodes, will be introduced in Constantinople. // Soldity itself, in non-assembly, also just uses other opcodes to simulate it. // Optmizer should take care of inlining, just declare shiftR ourselves here. // Where possible, better optimization is applied to make it cheaper. function shiftR(value, offset) -> result { result := div(value, exp(2, offset)) } // solhint-disable max-line-length // m_context << Instruction::SWAP1 << u256(2) << Instruction::EXP << Instruction::SWAP1 << (c_leftSigned ? Instruction::SDIV : Instruction::DIV); // optimization: although one side consists of multiple chromatids, // we handle them just as one long chromatid: // only difference is that a crossover in chromatid i affects chromatid i+1. // No big deal, order and location is random anyway function processSide(fatherSrc, motherSrc, rngSrc) -> result { { // initial rngSrc bit length: 254 bits // Run the crossovers // ===================================================== // Pick some crossovers // Each crossover is spaced ~64 bits on average. // To achieve this, we get a random 7 bit number, [0, 128), for each crossover. // 256 / 64 = 4, we need 4 crossovers, // and will have 256 / 127 = 2 at least (rounded down). // Get one bit determining if we should pick DNA from the father, // or from the mother. // This changes every crossover. (by swapping father and mother) { if eq(and(rngSrc, 0x1), 0) { // Swap mother and father, // create a temporary variable (code golf XOR swap costs more in gas) let temp := fatherSrc fatherSrc := motherSrc motherSrc := temp } // remove the bit from rng source, 253 rng bits left rngSrc := shiftR(rngSrc, 1) } // Don't push/pop this all the time, we have just enough space on stack. let mask := 0 // Cap at 4 crossovers, no more than that. let cap := 0 let crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON) // remove bits from hash, e.g. 254 - 7 = 247 left. rngSrc := shiftR(rngSrc, 7) let crossoverPos := crossoverLen // optimization: instead of shifting with an opcode we don't have until Constantinople, // keep track of the a shifted number, updated using multiplications. let crossoverPosLeading1 := 1 // solhint-disable-next-line no-empty-blocks for { } and(lt(crossoverPos, 256), lt(cap, 4)) { crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON) // remove bits from hash, e.g. 254 - 7 = 247 left. rngSrc := shiftR(rngSrc, 7) crossoverPos := add(crossoverPos, crossoverLen) cap := add(cap, 1) } { // Note: we go from right to left in the bit-string. // Create a mask for this crossover. // Example: // 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000..... // |Prev. data ||Crossover here ||remaining data ....... // // The crossover part is copied from the mother/father to the child. // Create the bit-mask // Create a bitstring that ignores the previous data: // 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111..... // First create a leading 1, just before the crossover, like: // 00000000000010000000000000000000000000000000000000000000000000000000000..... // Then substract 1, to get a long string of 1s // 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111..... // Now do the same for the remain part, and xor it. // leading 1 // 00000000000000000000000000000010000000000000000000000000000000000000000000000000000000000..... // sub 1 // 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111..... // xor with other // 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111..... // 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111..... // 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000..... // Use the final shifted 1 of the previous crossover as the start marker mask := sub(crossoverPosLeading1, 1) // update for this crossover, (and will be used as start for next crossover) crossoverPosLeading1 := mul(1, exp(2, crossoverPos)) mask := xor(mask, sub(crossoverPosLeading1, 1) ) // Now add the parent data to the child genotype // E.g. // Mask: 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000.... // Parent: 10010111001000110101011111001010001011100000000000010011000001000100000001011101111000111.... // Child (pre): 00000000000000000000000000000001111110100101111111000011001010000000101010100000110110110.... // Child (post): 00000000000000110101011111001011111110100101111111000011001010000000101010100000110110110.... // To do this, we run: child_post = child_pre | (mask & father) result := or(result, and(mask, fatherSrc)) // Swap father and mother, next crossover will take a string from the other. let temp := fatherSrc fatherSrc := motherSrc motherSrc := temp } // We still have a left-over part that was not copied yet // E.g., we have something like: // Father: | xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxx .... // Mother: |############ xxxxxxxxxx xxxxxxxxxxxx.... // Child: | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.... // The ############ still needs to be applied to the child, also, // this can be done cheaper than in the loop above, // as we don't have to swap anything for the next crossover or something. // At this point we have to assume 4 crossovers ran, // and that we only have 127 - 1 - (4 * 7) = 98 bits of randomness left. // We stopped at the bit after the crossoverPos index, see "x": // 000000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx..... // now create a leading 1 at crossoverPos like: // 000000001000000000000000000000000000000000000000000000000000000000000000000..... // Sub 1, get the mask for what we had. // 000000000111111111111111111111111111111111111111111111111111111111111111111..... // Invert, and we have the final mask: // 111111111000000000000000000000000000000000000000000000000000000000000000000..... mask := not(sub(crossoverPosLeading1, 1)) // Apply it to the result result := or(result, and(mask, fatherSrc)) // Random mutations // ===================================================== // random mutations // Put rng source in scratchpad 0 mstore(0x0, rngSrc) // And some arbitrary padding in scratchpad 1, // used to create different hashes based on input size changes mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21) // Hash it for a universally random bitstring. // Then reduce the number of 1s by AND-ing it with other *different* hashes. // Each bit in mutations has a probability of 0.5^5 = 0.03125 = 3.125% to be a 1 let mutations := and( and( and(keccak256(0, 32), keccak256(1, 33)), and(keccak256(2, 34), keccak256(3, 35)) ), keccak256(0, 36) ) result := xor(result, mutations) } } { // Get 1 bit of pseudo randomness that will // determine if side #1 will come from the left, or right side. // Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on. let relativeFatherSideLoc := mul(and(hash, 0x1), 0x20) // shift by 5 bits = mul by 2^5=32 (0x20) // Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on. let relativeMotherSideLoc := mul(and(hash, 0x2), 0x10) // already shifted by 1, mul by 2^4=16 (0x10) // Now remove the used 2 bits from the hash, 254 bits remaining now. hash := div(hash, 4) // Process the side, load the relevant parent data that will be used. mstore(memOffset, processSide( mload(add(father, relativeFatherSideLoc)), mload(add(mother, relativeMotherSideLoc)), hash )) // The other side will be the opposite index: 1 -> 0, 0 -> 1 // Apply it to the location, // which is either 0x20 (For index 1) or 0x0 for index 0. relativeFatherSideLoc := xor(relativeFatherSideLoc, 0x20) relativeMotherSideLoc := xor(relativeMotherSideLoc, 0x20) mstore(0x0, seed) // Second argument will be inverse, // resulting in a different second hash. mstore(0x20, not(timestamp)) // Now create another hash, for the other side hash := keccak256(0, 64) // Process the other side mstore(add(memOffset, 0x20), processSide( mload(add(father, relativeFatherSideLoc)), mload(add(mother, relativeMotherSideLoc)), hash )) } } // Sample input: // ["0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC","0x4444444455555555555555556666666666666644444444455555555555666666"] // // ["0x1111111111112222222223333311111111122222223333333331111112222222","0x7777788888888888999999999999977777777777788888888888999999997777"] // Expected results (or similar, depends on the seed): // 0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC < Father side A // 0x4444444455555555555555556666666666666644444444455555555555666666 < Father side B // 0x1111111111112222222223333311111111122222223333333331111112222222 < Mother side A // 0x7777788888888888999999999999977777777777788888888888999999997777 < Mother side B // xxxxxxxxxxxxxxxxx xxxxxxxxx xx // 0xAAABBBBBBBBCCCCCD99999999998BBBBBBBBF77778888888888899999999774C < Child side A // xxx xxxxxxxxxxx // 0x4441111111112222222223333366666666666222223333333331111112222222 < Child side B // And then random mutations, for gene pool expansion. // Each bit is flipped with a 3.125% chance // Example: //a2c37edc61dca0ca0b199e098c80fd5a221c2ad03605b4b54332361358745042 < random hash 1 //c217d04b19a83fe497c1cf6e1e10030e455a0812a6949282feec27d67fe2baa7 < random hash 2 //2636a55f38bed26d804c63a13628e21b2d701c902ca37b2b0ca94fada3821364 < random hash 3 //86bb023a85e2da50ac233b946346a53aa070943b0a8e91c56e42ba181729a5f9 < random hash 4 //5d71456a1288ab30ddd4c955384d42e66a09d424bd7743791e3eab8e09aa13f1 < random hash 5 //0000000800800000000000000000000200000000000000000000020000000000 < resulting mutation //aaabbbbbbbbcccccd99999999998bbbbbbbbf77778888888888899999999774c < original //aaabbbb3bb3cccccd99999999998bbb9bbbbf7777888888888889b999999774c < mutated (= original XOR mutation) } // Generates (psuedo) random Pepe DNA function randomDNA(uint256 seed) internal pure returns (uint256[2] memOffset) { // solhint-disable-next-line no-inline-assembly assembly { // allocate output // 1) get the pointer to our memory memOffset := mload(0x40) // 2) Change the free-memory pointer to keep our memory // (we will only use 64 bytes: 2 values of 256 bits) mstore(0x40, add(memOffset, 64)) // Load the seed into 1st scratchpad memory slot. // adjacent to the additional value (used to create two distinct hashes) mstore(0x0, seed) // In second scratchpad slot: // The additional value can be any word, as long as the caller uses // it (second hash needs to be different) mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21) // // Create first element pointer of array // mstore(memOffset, add(memOffset, 64)) // pointer 1 // mstore(add(memOffset, 32), add(memOffset, 96)) // pointer 2 // control block to auto-pop the hash. { // L * N * 2 * 4 = 4 * 2 * 2 * 4 = 64 bytes, 2x 256 bit hash // Sha3 is cheaper than sha256, make use of it let hash := keccak256(0, 64) // Store first array value mstore(memOffset, hash) // Now hash again, but only 32 bytes of input, // to ignore make the input different than the previous call, hash := keccak256(0, 32) mstore(add(memOffset, 32), hash) } } } } /** @title CozyTimeAuction */ contract CozyTimeAuction is AuctionBase { // solhint-disable-next-line constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public { } /** * @dev Start an auction * @param _pepeId The id of the pepe to start the auction for * @param _beginPrice Start price of the auction * @param _endPrice End price of the auction * @param _duration How long the auction should take */ function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public { // solhint-disable-next-line not-rely-on-time require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check super.startAuction(_pepeId, _beginPrice, _endPrice, _duration); } /** * @dev Start a auction direclty from the PepeBase smartcontract * @param _pepeId The id of the pepe to start the auction for * @param _beginPrice Start price of the auction * @param _endPrice End price of the auction * @param _duration How long the auction should take * @param _seller The address of the seller */ // solhint-disable-next-line max-line-length function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public { // solhint-disable-next-line not-rely-on-time require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check super.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, _seller); } /** * @dev Buy cozy right from the auction * @param _pepeId Pepe to cozy with * @param _cozyCandidate the pepe to cozy with * @param _candidateAsFather Is the _cozyCandidate father? * @param _pepeReceiver address receiving the pepe after cozy time */ // solhint-disable-next-line max-line-length function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable { require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract PepeAuction storage auction = auctions[_pepeId]; // solhint-disable-next-line not-rely-on-time require(now < auction.auctionEnd);// auction must be still going uint256 price = calculateBid(_pepeId); require(msg.value >= price);//must send enough ether uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed? //Send ETH to seller auction.seller.transfer(price - totalFee); //send ETH to beneficiary address affiliate = affiliateContract.userToAffiliate(_pepeReceiver); //solhint-disable-next-line if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate //nothing just to suppress warning } //actual cozytiming if (_candidateAsFather) { if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) { revert(); } } else { // Swap around the two pepes, they have no set gender, the user decides what they are. if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) { revert(); } } //Send pepe to seller of auction if (!pepeContract.transfer(auction.seller, _pepeId)) { revert(); //can't complete transfer if this fails } if (msg.value > price) { //return ether send to much _pepeReceiver.transfer(msg.value - price); } emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event delete auctions[_pepeId];//deletes auction } /** * @dev Buy cozytime and pass along affiliate * @param _pepeId Pepe to cozy with * @param _cozyCandidate the pepe to cozy with * @param _candidateAsFather Is the _cozyCandidate father? * @param _pepeReceiver address receiving the pepe after cozy time * @param _affiliate Affiliate address to set */ //solhint-disable-next-line max-line-length function buyCozyAffiliated(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver, address _affiliate) public payable { affiliateContract.setAffiliate(_pepeReceiver, _affiliate); buyCozy(_pepeId, _cozyCandidate, _candidateAsFather, _pepeReceiver); } } contract Haltable is Ownable { uint256 public haltTime; //when the contract was halted bool public halted;//is the contract halted? uint256 public haltDuration; uint256 public maxHaltDuration = 8 weeks;//how long the contract can be halted modifier stopWhenHalted { require(!halted); _; } modifier onlyWhenHalted { require(halted); _; } /** * @dev Halt the contract for a set time smaller than maxHaltDuration * @param _duration Duration how long the contract should be halted. Must be smaller than maxHaltDuration */ function halt(uint256 _duration) public onlyOwner { require(haltTime == 0); //cannot halt if it was halted before require(_duration <= maxHaltDuration);//cannot halt for longer than maxHaltDuration haltDuration = _duration; halted = true; // solhint-disable-next-line not-rely-on-time haltTime = now; } /** * @dev Unhalt the contract. Can only be called by the owner or when the haltTime has passed */ function unhalt() public { // solhint-disable-next-line require(now > haltTime + haltDuration || msg.sender == owner);//unhalting is only possible when haltTime has passed or the owner unhalts halted = false; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } /// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. This function MUST use 50,000 gas or less. Return of other /// than the magic value MUST result in the transaction being reverted. /// Note: the contract address is always the message sender. /// @param _from The sending address /// @param _tokenId The NFT identifier which is being transfered /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } contract PepeBase is Genetic, Ownable, Usernames, Haltable { uint32[15] public cozyCoolDowns = [ //determined by generation / 2 uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(15 minutes), uint32(30 minutes), uint32(45 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; struct Pepe { address master; //The master of the pepe uint256[2] genotype; //all genes stored here uint64 canCozyAgain; //time when pepe can have nice time again uint64 generation; //what generation? uint64 father; //father of this pepe uint64 mother; //mommy of this pepe uint8 coolDownIndex; } mapping(uint256 => bytes32) public pepeNames; //stores all pepes Pepe[] public pepes; bool public implementsERC721 = true; //signal erc721 support // solhint-disable-next-line const-name-snakecase string public constant name = "Crypto Pepe"; // solhint-disable-next-line const-name-snakecase string public constant symbol = "CPEP"; mapping(address => uint256[]) private wallets; mapping(address => uint256) public balances; //amounts of pepes per address mapping(uint256 => address) public approved; //pepe index to address approved to transfer mapping(address => mapping(address => bool)) public approvedForAll; uint256 public zeroGenPepes; //how many zero gen pepes are mined uint256 public constant MAX_PREMINE = 100;//how many pepes can be premined uint256 public constant MAX_ZERO_GEN_PEPES = 1100; //max number of zero gen pepes address public miner; //address of the miner contract modifier onlyPepeMaster(uint256 _pepeId) { require(pepes[_pepeId].master == msg.sender); _; } modifier onlyAllowed(uint256 _tokenId) { // solhint-disable-next-line max-line-length require(msg.sender == pepes[_tokenId].master || msg.sender == approved[_tokenId] || approvedForAll[pepes[_tokenId].master][msg.sender]); //check if msg.sender is allowed _; } event PepeBorn(uint256 indexed mother, uint256 indexed father, uint256 indexed pepeId); event PepeNamed(uint256 indexed pepeId); constructor() public { Pepe memory pepe0 = Pepe({ master: 0x0, genotype: [uint256(0), uint256(0)], canCozyAgain: 0, father: 0, mother: 0, generation: 0, coolDownIndex: 0 }); pepes.push(pepe0); } /** * @dev Internal function that creates a new pepe * @param _genoType DNA of the new pepe * @param _mother The ID of the mother * @param _father The ID of the father * @param _generation The generation of the new Pepe * @param _master The owner of this new Pepe * @return The ID of the newly generated Pepe */ // solhint-disable-next-line max-line-length function _newPepe(uint256[2] _genoType, uint64 _mother, uint64 _father, uint64 _generation, address _master) internal returns (uint256 pepeId) { uint8 tempCoolDownIndex; tempCoolDownIndex = uint8(_generation / 2); if (_generation > 28) { tempCoolDownIndex = 14; } Pepe memory _pepe = Pepe({ master: _master, //The master of the pepe genotype: _genoType, //all genes stored here canCozyAgain: 0, //time when pepe can have nice time again father: _father, //father of this pepe mother: _mother, //mommy of this pepe generation: _generation, //what generation? coolDownIndex: tempCoolDownIndex }); if (_generation == 0) { zeroGenPepes += 1; //count zero gen pepes } //push returns the new length, use it to get a new unique id pepeId = pepes.push(_pepe) - 1; //add it to the wallet of the master of the new pepe addToWallet(_master, pepeId); emit PepeBorn(_mother, _father, pepeId); emit Transfer(address(0), _master, pepeId); return pepeId; } /** * @dev Set the miner contract. Can only be called once * @param _miner Address of the miner contract */ function setMiner(address _miner) public onlyOwner { require(miner == address(0));//can only be set once miner = _miner; } /** * @dev Mine a new Pepe. Can only be called by the miner contract. * @param _seed Seed to be used for the generation of the DNA * @param _receiver Address receiving the newly mined Pepe * @return The ID of the newly mined Pepe */ function minePepe(uint256 _seed, address _receiver) public stopWhenHalted returns(uint256) { require(msg.sender == miner);//only miner contract can call require(zeroGenPepes < MAX_ZERO_GEN_PEPES); return _newPepe(randomDNA(_seed), 0, 0, 0, _receiver); } /** * @dev Premine pepes. Can only be called by the owner and is limited to MAX_PREMINE * @param _amount Amount of Pepes to premine */ function pepePremine(uint256 _amount) public onlyOwner stopWhenHalted { for (uint i = 0; i < _amount; i++) { require(zeroGenPepes <= MAX_PREMINE);//can only generate set amount during premine //create a new pepe // 1) who's genes are based on hash of the timestamp and the number of pepes // 2) who has no mother or father // 3) who is generation zero // 4) who's master is the manager // solhint-disable-next-line _newPepe(randomDNA(uint256(keccak256(abi.encodePacked(block.timestamp, pepes.length)))), 0, 0, 0, owner); } } /** * @dev CozyTime two Pepes together * @param _mother The mother of the new Pepe * @param _father The father of the new Pepe * @param _pepeReceiver Address receiving the new Pepe * @return If it was a success */ function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) external stopWhenHalted returns (bool) { //cannot cozyTime with itself require(_mother != _father); //caller has to either be master or approved for mother // solhint-disable-next-line max-line-length require(pepes[_mother].master == msg.sender || approved[_mother] == msg.sender || approvedForAll[pepes[_mother].master][msg.sender]); //caller has to either be master or approved for father // solhint-disable-next-line max-line-length require(pepes[_father].master == msg.sender || approved[_father] == msg.sender || approvedForAll[pepes[_father].master][msg.sender]); //require both parents to be ready for cozytime // solhint-disable-next-line not-rely-on-time require(now > pepes[_mother].canCozyAgain && now > pepes[_father].canCozyAgain); //require both mother parents not to be father require(pepes[_mother].mother != _father && pepes[_mother].father != _father); //require both father parents not to be mother require(pepes[_father].mother != _mother && pepes[_father].father != _mother); Pepe storage father = pepes[_father]; Pepe storage mother = pepes[_mother]; approved[_father] = address(0); approved[_mother] = address(0); uint256[2] memory newGenotype = breed(father.genotype, mother.genotype, pepes.length); uint64 newGeneration; newGeneration = mother.generation + 1; if (newGeneration < father.generation + 1) { //if father generation is bigger newGeneration = father.generation + 1; } _handleCoolDown(_mother); _handleCoolDown(_father); //sets pepe birth when mother is done // solhint-disable-next-line max-line-length pepes[_newPepe(newGenotype, uint64(_mother), uint64(_father), newGeneration, _pepeReceiver)].canCozyAgain = mother.canCozyAgain; //_pepeReceiver becomes the master of the pepe return true; } /** * @dev Internal function to increase the coolDownIndex * @param _pepeId The id of the Pepe to update the coolDown of */ function _handleCoolDown(uint256 _pepeId) internal { Pepe storage tempPep = pepes[_pepeId]; // solhint-disable-next-line not-rely-on-time tempPep.canCozyAgain = uint64(now + cozyCoolDowns[tempPep.coolDownIndex]); if (tempPep.coolDownIndex < 14) {// after every cozy time pepe gets slower tempPep.coolDownIndex++; } } /** * @dev Set the name of a Pepe. Can only be set once * @param _pepeId ID of the pepe to name * @param _name The name to assign */ function setPepeName(uint256 _pepeId, bytes32 _name) public stopWhenHalted onlyPepeMaster(_pepeId) returns(bool) { require(pepeNames[_pepeId] == 0x0000000000000000000000000000000000000000000000000000000000000000); pepeNames[_pepeId] = _name; emit PepeNamed(_pepeId); return true; } /** * @dev Transfer a Pepe to the auction contract and auction it * @param _pepeId ID of the Pepe to auction * @param _auction Auction contract address * @param _beginPrice Price the auction starts at * @param _endPrice Price the auction ends at * @param _duration How long the auction should run */ // solhint-disable-next-line max-line-length function transferAndAuction(uint256 _pepeId, address _auction, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public stopWhenHalted onlyPepeMaster(_pepeId) { _transfer(msg.sender, _auction, _pepeId);//transfer pepe to auction AuctionBase auction = AuctionBase(_auction); auction.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, msg.sender); } /** * @dev Approve and buy. Used to buy cozyTime in one call * @param _pepeId Pepe to cozy with * @param _auction Address of the auction contract * @param _cozyCandidate Pepe to approve and cozy with * @param _candidateAsFather Use the candidate as father or not */ // solhint-disable-next-line max-line-length function approveAndBuy(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) { approved[_cozyCandidate] = _auction; // solhint-disable-next-line max-line-length CozyTimeAuction(_auction).buyCozy.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender); //breeding resets approval } /** * @dev The same as above only pass an extra parameter * @param _pepeId Pepe to cozy with * @param _auction Address of the auction contract * @param _cozyCandidate Pepe to approve and cozy with * @param _candidateAsFather Use the candidate as father or not * @param _affiliate Address to set as affiliate */ // solhint-disable-next-line max-line-length function approveAndBuyAffiliated(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather, address _affiliate) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) { approved[_cozyCandidate] = _auction; // solhint-disable-next-line max-line-length CozyTimeAuction(_auction).buyCozyAffiliated.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender, _affiliate); //breeding resets approval } /** * @dev get Pepe information * @param _pepeId ID of the Pepe to get information of * @return master * @return genotype * @return canCozyAgain * @return generation * @return father * @return mother * @return pepeName * @return coolDownIndex */ // solhint-disable-next-line max-line-length function getPepe(uint256 _pepeId) public view returns(address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) { Pepe storage tempPep = pepes[_pepeId]; master = tempPep.master; genotype = tempPep.genotype; canCozyAgain = tempPep.canCozyAgain; generation = tempPep.generation; father = tempPep.father; mother = tempPep.mother; pepeName = pepeNames[_pepeId]; coolDownIndex = tempPep.coolDownIndex; } /** * @dev Get the time when a pepe can cozy again * @param _pepeId ID of the pepe * @return Time when the pepe can cozy again */ function getCozyAgain(uint256 _pepeId) public view returns(uint64) { return pepes[_pepeId].canCozyAgain; } /** * ERC721 Compatibility * */ event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @dev Get the total number of Pepes * @return total Returns the total number of pepes */ function totalSupply() public view returns(uint256 total) { total = pepes.length - balances[address(0)]; return total; } /** * @dev Get the number of pepes owned by an address * @param _owner Address to get the balance from * @return balance The number of pepes */ function balanceOf(address _owner) external view returns (uint256 balance) { balance = balances[_owner]; } /** * @dev Get the owner of a Pepe * @param _tokenId the token to get the owner of * @return _owner the owner of the pepe */ function ownerOf(uint256 _tokenId) external view returns (address _owner) { _owner = pepes[_tokenId].master; } /** * @dev Get the id of an token by its index * @param _owner The address to look up the tokens of * @param _index Index to look at * @return tokenId the ID of the token of the owner at the specified index */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256 tokenId) { //The index must be smaller than the balance, // to guarantee that there is no leftover token returned. require(_index < balances[_owner]); return wallets[_owner][_index]; } /** * @dev Private method that ads a token to the wallet * @param _owner Address of the owner * @param _tokenId Pepe ID to add */ function addToWallet(address _owner, uint256 _tokenId) private { uint256[] storage wallet = wallets[_owner]; uint256 balance = balances[_owner]; if (balance < wallet.length) { wallet[balance] = _tokenId; } else { wallet.push(_tokenId); } //increase owner balance //overflow is not likely to happen(need very large amount of pepes) balances[_owner] += 1; } /** * @dev Remove a token from a address's wallet * @param _owner Address of the owner * @param _tokenId Token to remove from the wallet */ function removeFromWallet(address _owner, uint256 _tokenId) private { uint256[] storage wallet = wallets[_owner]; uint256 i = 0; // solhint-disable-next-line no-empty-blocks for (; wallet[i] != _tokenId; i++) { // not the pepe we are looking for } if (wallet[i] == _tokenId) { //found it! uint256 last = balances[_owner] - 1; if (last > 0) { //move the last item to this spot, the last will become inaccessible wallet[i] = wallet[last]; } //else: no last item to move, the balance is 0, making everything inaccessible. //only decrease balance if _tokenId was in the wallet balances[_owner] -= 1; } } /** * @dev Internal transfer function * @param _from Address sending the token * @param _to Address to token is send to * @param _tokenId ID of the token to send */ function _transfer(address _from, address _to, uint256 _tokenId) internal { pepes[_tokenId].master = _to; approved[_tokenId] = address(0);//reset approved of pepe on every transfer //remove the token from the _from wallet removeFromWallet(_from, _tokenId); //add the token to the _to wallet addToWallet(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev transfer a token. Can only be called by the owner of the token * @param _to Addres to send the token to * @param _tokenId ID of the token to send */ // solhint-disable-next-line no-simple-event-func-name function transfer(address _to, uint256 _tokenId) public stopWhenHalted onlyPepeMaster(_tokenId) //check if msg.sender is the master of this pepe returns(bool) { _transfer(msg.sender, _to, _tokenId);//after master modifier invoke internal transfer return true; } /** * @dev Approve a address to send a token * @param _to Address to approve * @param _tokenId Token to set approval for */ function approve(address _to, uint256 _tokenId) external stopWhenHalted onlyPepeMaster(_tokenId) { approved[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /** * @dev Approve or revoke approval an address for al tokens of a user * @param _operator Address to (un)approve * @param _approved Approving or revoking indicator */ function setApprovalForAll(address _operator, bool _approved) external stopWhenHalted { if (_approved) { approvedForAll[msg.sender][_operator] = true; } else { approvedForAll[msg.sender][_operator] = false; } emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Get approved address for a token * @param _tokenId Token ID to get the approved address for * @return The address that is approved for this token */ function getApproved(uint256 _tokenId) external view returns (address) { return approved[_tokenId]; } /** * @dev Get if an operator is approved for all tokens of that owner * @param _owner Owner to check the approval for * @param _operator Operator to check approval for * @return Boolean indicating if the operator is approved for that owner */ function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return approvedForAll[_owner][_operator]; } /** * @dev Function to signal support for an interface * @param interfaceID the ID of the interface to check for * @return Boolean indicating support */ function supportsInterface(bytes4 interfaceID) external pure returns (bool) { if (interfaceID == 0x80ac58cd || interfaceID == 0x01ffc9a7) { //TODO: add more interfaces the contract supports return true; } return false; } /** * @dev Safe transferFrom function * @param _from Address currently owning the token * @param _to Address to send token to * @param _tokenId ID of the token to send */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) external stopWhenHalted { _safeTransferFromInternal(_from, _to, _tokenId, ""); } /** * @dev Safe transferFrom function with aditional data attribute * @param _from Address currently owning the token * @param _to Address to send token to * @param _tokenId ID of the token to send * @param _data Data to pass along call */ // solhint-disable-next-line max-line-length function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external stopWhenHalted { _safeTransferFromInternal(_from, _to, _tokenId, _data); } /** * @dev Internal Safe transferFrom function with aditional data attribute * @param _from Address currently owning the token * @param _to Address to send token to * @param _tokenId ID of the token to send * @param _data Data to pass along call */ // solhint-disable-next-line max-line-length function _safeTransferFromInternal(address _from, address _to, uint256 _tokenId, bytes _data) internal onlyAllowed(_tokenId) { require(pepes[_tokenId].master == _from);//check if from is current owner require(_to != address(0));//throw on zero address _transfer(_from, _to, _tokenId); //transfer token if (isContract(_to)) { //check if is contract // solhint-disable-next-line max-line-length require(ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, _data) == bytes4(keccak256("onERC721Received(address,uint256,bytes)"))); } } /** * @dev TransferFrom function * @param _from Address currently owning the token * @param _to Address to send token to * @param _tokenId ID of the token to send * @return If it was successful */ // solhint-disable-next-line max-line-length function transferFrom(address _from, address _to, uint256 _tokenId) public stopWhenHalted onlyAllowed(_tokenId) returns(bool) { require(pepes[_tokenId].master == _from);//check if _from is really the master. require(_to != address(0)); _transfer(_from, _to, _tokenId);//handles event, balances and approval reset; return true; } /** * @dev Utility method to check if an address is a contract * @param _address Address to check * @return Boolean indicating if the address is a contract */ function isContract(address _address) internal view returns (bool) { uint size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(_address) } return size > 0; } } contract PepeReborn is Ownable, Usernames { uint32[15] public cozyCoolDowns = [ // determined by generation / 2 uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(15 minutes), uint32(30 minutes), uint32(45 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; struct Pepe { address master; // The master of the pepe uint256[2] genotype; // all genes stored here uint64 canCozyAgain; // time when pepe can have nice time again uint64 generation; // what generation? uint64 father; // father of this pepe uint64 mother; // mommy of this pepe uint8 coolDownIndex; } struct UndeadPepeMutable { address master; // The master of the pepe // uint256[2] genotype; // all genes stored here uint64 canCozyAgain; // time when pepe can have nice time again // uint64 generation; // what generation? // uint64 father; // father of this pepe // uint64 mother; // mommy of this pepe uint8 coolDownIndex; bool resurrected; // has the pepe been duplicated off the old contract } mapping(uint256 => bytes32) public pepeNames; // stores reborn pepes. index 0 holds pepe 5497 Pepe[] private rebornPepes; // stores undead pepes. get the mutables from the old contract mapping(uint256 => UndeadPepeMutable) private undeadPepes; //address private constant PEPE_UNDEAD_ADDRRESS = 0x84aC94F17622241f313511B629e5E98f489AD6E4; //address private constant PEPE_AUCTION_SALE_UNDEAD_ADDRESS = 0x28ae3DF366726D248c57b19fa36F6D9c228248BE; //address private constant COZY_TIME_AUCTION_UNDEAD_ADDRESS = 0xE2C43d2C6D6875c8F24855054d77B5664c7e810f; address private PEPE_UNDEAD_ADDRRESS; address private PEPE_AUCTION_SALE_UNDEAD_ADDRESS; address private COZY_TIME_AUCTION_UNDEAD_ADDRESS; GenePoolInterface private genePool; uint256 private constant REBORN_PEPE_0 = 5497; bool public constant implementsERC721 = true; // signal erc721 support // solhint-disable-next-line const-name-snakecase string public constant name = "Crypto Pepe Reborn"; // solhint-disable-next-line const-name-snakecase string public constant symbol = "CPRE"; // Token Base URI string public baseTokenURI = "https://api.cryptopepes.lol/getPepe/"; // Contract URI string private contractUri = "https://cryptopepes.lol/contract-metadata.json"; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private wallets; // Mapping from token ID to index in owners wallet mapping(uint256 => uint256) private walletIndex; mapping(uint256 => address) public approved; // pepe index to address approved to transfer mapping(address => mapping(address => bool)) public approvedForAll; uint256 private preminedPepes = 0; uint256 private constant MAX_PREMINE = 1100; modifier onlyPepeMaster(uint256 pepeId) { require(_ownerOf(pepeId) == msg.sender); _; } modifier onlyAllowed(uint256 pepeId) { address master = _ownerOf(pepeId); // solhint-disable-next-line max-line-length require(msg.sender == master || msg.sender == approved[pepeId] || approvedForAll[master][msg.sender]); // check if msg.sender is allowed _; } event PepeBorn(uint256 indexed mother, uint256 indexed father, uint256 indexed pepeId); event PepeNamed(uint256 indexed pepeId); constructor(address baseAddress, address saleAddress, address cozyAddress, address genePoolAddress) public { PEPE_UNDEAD_ADDRRESS = baseAddress; PEPE_AUCTION_SALE_UNDEAD_ADDRESS = saleAddress; COZY_TIME_AUCTION_UNDEAD_ADDRESS = cozyAddress; setGenePool(genePoolAddress); } /** * @dev Internal function that creates a new pepe * @param _genoType DNA of the new pepe * @param _mother The ID of the mother * @param _father The ID of the father * @param _generation The generation of the new Pepe * @param _master The owner of this new Pepe * @return The ID of the newly generated Pepe */ // solhint-disable-next-line max-line-length function _newPepe(uint256[2] _genoType, uint64 _mother, uint64 _father, uint64 _generation, address _master) internal returns (uint256 pepeId) { uint8 tempCoolDownIndex; tempCoolDownIndex = uint8(_generation / 2); if (_generation > 28) { tempCoolDownIndex = 14; } Pepe memory _pepe = Pepe({ master: _master, // The master of the pepe genotype: _genoType, // all genes stored here canCozyAgain: 0, // time when pepe can have nice time again father: _father, // father of this pepe mother: _mother, // mommy of this pepe generation: _generation, // what generation? coolDownIndex: tempCoolDownIndex }); // push returns the new length, use it to get a new unique id pepeId = rebornPepes.push(_pepe) + REBORN_PEPE_0 - 1; // add it to the wallet of the master of the new pepe addToWallet(_master, pepeId); emit PepeBorn(_mother, _father, pepeId); emit Transfer(address(0), _master, pepeId); return pepeId; } /** * @dev Premine pepes. Can only be called by the owner and is limited to MAX_PREMINE * @param _amount Amount of Pepes to premine */ function pepePremine(uint256 _amount) public onlyOwner { for (uint i = 0; i < _amount; i++) { require(preminedPepes < MAX_PREMINE);//can only generate set amount during premine //create a new pepe // 1) who's genes are based on hash of the timestamp and the new pepe's id // 2) who has no mother or father // 3) who is generation zero // 4) who's master is the manager // solhint-disable-next-line _newPepe(genePool.randomDNA(uint256(keccak256(abi.encodePacked(block.timestamp, (REBORN_PEPE_0 + rebornPepes.length))))), 0, 0, 0, owner); ++preminedPepes; } } /* * @dev CozyTime two Pepes together * @param _mother The mother of the new Pepe * @param _father The father of the new Pepe * @param _pepeReceiver Address receiving the new Pepe * @return If it was a success */ function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) external returns (bool) { // cannot cozyTime with itself require(_mother != _father); // ressurect parents if needed checkResurrected(_mother); checkResurrected(_father); // get parents Pepe memory mother = _getPepe(_mother); Pepe memory father = _getPepe(_father); // caller has to either be master or approved for mother // solhint-disable-next-line max-line-length require(mother.master == msg.sender || approved[_mother] == msg.sender || approvedForAll[mother.master][msg.sender]); // caller has to either be master or approved for father // solhint-disable-next-line max-line-length require(father.master == msg.sender || approved[_father] == msg.sender || approvedForAll[father.master][msg.sender]); // require both parents to be ready for cozytime // solhint-disable-next-line not-rely-on-time require(now > mother.canCozyAgain && now > father.canCozyAgain); // require both mother parents not to be father require(mother.father != _father && mother.mother != _father); require(father.mother != _mother && father.father != _mother); approved[_father] = address(0); approved[_mother] = address(0); uint256[2] memory newGenotype = genePool.breed(father.genotype, mother.genotype, REBORN_PEPE_0+rebornPepes.length); uint64 newGeneration; newGeneration = mother.generation + 1; if (newGeneration < father.generation + 1) { // if father generation is bigger newGeneration = father.generation + 1; } uint64 motherCanCozyAgain = _handleCoolDown(_mother); _handleCoolDown(_father); // birth new pepe // _pepeReceiver becomes the master of the pepe uint256 pepeId = _newPepe(newGenotype, uint64(_mother), uint64(_father), newGeneration, _pepeReceiver); // sets pepe birth when mother is done // solhint-disable-next-line max-line-length rebornPepes[rebornPepeIdToIndex(pepeId)].canCozyAgain = motherCanCozyAgain; return true; } /** * @dev Internal function to increase the coolDownIndex * @param pepeId The id of the Pepe to update the coolDown of * @return The time that pepe can cozy again */ function _handleCoolDown(uint256 pepeId) internal returns (uint64){ if(pepeId >= REBORN_PEPE_0){ Pepe storage tempPep1 = rebornPepes[pepeId]; // solhint-disable-next-line not-rely-on-time tempPep1.canCozyAgain = uint64(now + cozyCoolDowns[tempPep1.coolDownIndex]); if (tempPep1.coolDownIndex < 14) {// after every cozy time pepe gets slower tempPep1.coolDownIndex++; } return tempPep1.canCozyAgain; }else{ // this function is only called in cozyTime(), pepe has already been resurrected UndeadPepeMutable storage tempPep2 = undeadPepes[pepeId]; // solhint-disable-next-line not-rely-on-time tempPep2.canCozyAgain = uint64(now + cozyCoolDowns[tempPep2.coolDownIndex]); if (tempPep2.coolDownIndex < 14) {// after every cozy time pepe gets slower tempPep2.coolDownIndex++; } return tempPep2.canCozyAgain; } } /** * @dev Set the name of a Pepe. Can only be set once * @param pepeId ID of the pepe to name * @param _name The name to assign */ function setPepeName(uint256 pepeId, bytes32 _name) public onlyPepeMaster(pepeId) returns(bool) { require(pepeNames[pepeId] == 0x0000000000000000000000000000000000000000000000000000000000000000); pepeNames[pepeId] = _name; emit PepeNamed(pepeId); return true; } /** * @dev Transfer a Pepe to the auction contract and auction it * @param pepeId ID of the Pepe to auction * @param _auction Auction contract address * @param _beginPrice Price the auction starts at * @param _endPrice Price the auction ends at * @param _duration How long the auction should run */ // solhint-disable-next-line max-line-length function transferAndAuction(uint256 pepeId, address _auction, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public onlyPepeMaster(pepeId) { //checkResurrected(pepeId); _transfer(msg.sender, _auction, pepeId);// transfer pepe to auction AuctionBase auction = AuctionBase(_auction); auction.startAuctionDirect(pepeId, _beginPrice, _endPrice, _duration, msg.sender); } /** * @dev Approve and buy. Used to buy cozyTime in one call * @param pepeId Pepe to cozy with * @param _auction Address of the auction contract * @param _cozyCandidate Pepe to approve and cozy with * @param _candidateAsFather Use the candidate as father or not */ // solhint-disable-next-line max-line-length function approveAndBuy(uint256 pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather) public payable onlyPepeMaster(_cozyCandidate) { checkResurrected(pepeId); approved[_cozyCandidate] = _auction; // solhint-disable-next-line max-line-length RebornCozyTimeAuction(_auction).buyCozy.value(msg.value)(pepeId, _cozyCandidate, _candidateAsFather, msg.sender); // breeding resets approval } /** * @dev The same as above only pass an extra parameter * @param pepeId Pepe to cozy with * @param _auction Address of the auction contract * @param _cozyCandidate Pepe to approve and cozy with * @param _candidateAsFather Use the candidate as father or not * @param _affiliate Address to set as affiliate */ // solhint-disable-next-line max-line-length function approveAndBuyAffiliated(uint256 pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather, address _affiliate) public payable onlyPepeMaster(_cozyCandidate) { checkResurrected(pepeId); approved[_cozyCandidate] = _auction; // solhint-disable-next-line max-line-length RebornCozyTimeAuction(_auction).buyCozyAffiliated.value(msg.value)(pepeId, _cozyCandidate, _candidateAsFather, msg.sender, _affiliate); // breeding resets approval } /** * @dev Get the time when a pepe can cozy again * @param pepeId ID of the pepe * @return Time when the pepe can cozy again */ function getCozyAgain(uint256 pepeId) public view returns(uint64) { return _getPepe(pepeId).canCozyAgain; } /** * ERC721 Compatibility * */ event Approval(address indexed _owner, address indexed _approved, uint256 pepeId); event Transfer(address indexed _from, address indexed _to, uint256 indexed pepeId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @dev Get the total number of Pepes * @return total Returns the total number of pepes */ function totalSupply() public view returns(uint256) { return REBORN_PEPE_0 + rebornPepes.length - 1; } /** * @dev Get the number of pepes owned by an address * Note that this only includes reborn and resurrected pepes * Pepes that are still dead are not counted. * @param _owner Address to get the balance from * @return balance The number of pepes */ function balanceOf(address _owner) external view returns (uint256 balance) { return wallets[_owner].length; } /** * @dev Get the owner of a Pepe * Note that this returns pepes from old auctions * @param pepeId the token to get the owner of * @return the owner of the pepe */ function ownerOf(uint256 pepeId) external view returns (address) { return _getPepe(pepeId).master; } /** * @dev Get the owner of a Pepe * Note that this returns pepes from old auctions * @param pepeId the token to get the owner of * @return the owner of the pepe */ function _ownerOf(uint256 pepeId) internal view returns (address) { return _getPepe(pepeId).master; } /** * @dev Get the id of an token by its index * @param _owner The address to look up the tokens of * @param _index Index to look at * @return pepeId the ID of the token of the owner at the specified index */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256 pepeId) { // The index must be smaller than the balance, // to guarantee that there is no leftover token returned. require(_index < wallets[_owner].length); return wallets[_owner][_index]; } /** * @dev Private method that ads a token to the wallet * @param _owner Address of the owner * @param pepeId Pepe ID to add */ function addToWallet(address _owner, uint256 pepeId) private { /* uint256 length = wallets[_owner].length; wallets[_owner].push(pepeId); walletIndex[pepeId] = length; */ walletIndex[pepeId] = wallets[_owner].length; wallets[_owner].push(pepeId); } /** * @dev Remove a token from a address's wallet * @param _owner Address of the owner * @param pepeId Token to remove from the wallet */ function removeFromWallet(address _owner, uint256 pepeId) private { // walletIndex returns 0 if not initialized to a value // verify before removing if(walletIndex[pepeId] == 0 && (wallets[_owner].length == 0 || wallets[_owner][0] != pepeId)) return; // pop last element from wallet, move it to this index uint256 tokenIndex = walletIndex[pepeId]; uint256 lastTokenIndex = wallets[_owner].length - 1; uint256 lastToken = wallets[_owner][lastTokenIndex]; wallets[_owner][tokenIndex] = lastToken; wallets[_owner].length--; walletIndex[pepeId] = 0; walletIndex[lastToken] = tokenIndex; } /** * @dev Internal transfer function * @param _from Address sending the token * @param _to Address to token is send to * @param pepeId ID of the token to send */ function _transfer(address _from, address _to, uint256 pepeId) internal { checkResurrected(pepeId); if(pepeId >= REBORN_PEPE_0) rebornPepes[rebornPepeIdToIndex(pepeId)].master = _to; else undeadPepes[pepeId].master = _to; approved[pepeId] = address(0);//reset approved of pepe on every transfer //remove the token from the _from wallet removeFromWallet(_from, pepeId); //add the token to the _to wallet addToWallet(_to, pepeId); emit Transfer(_from, _to, pepeId); } /** * @dev transfer a token. Can only be called by the owner of the token * @param _to Addres to send the token to * @param pepeId ID of the token to send */ // solhint-disable-next-line no-simple-event-func-name function transfer(address _to, uint256 pepeId) public onlyPepeMaster(pepeId) returns(bool) { _transfer(msg.sender, _to, pepeId);//after master modifier invoke internal transfer return true; } /** * @dev Approve a address to send a token * @param _to Address to approve * @param pepeId Token to set approval for */ function approve(address _to, uint256 pepeId) external onlyPepeMaster(pepeId) { approved[pepeId] = _to; emit Approval(msg.sender, _to, pepeId); } /** * @dev Approve or revoke approval an address for all tokens of a user * @param _operator Address to (un)approve * @param _approved Approving or revoking indicator */ function setApprovalForAll(address _operator, bool _approved) external { approvedForAll[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Get approved address for a token * @param pepeId Token ID to get the approved address for * @return The address that is approved for this token */ function getApproved(uint256 pepeId) external view returns (address) { return approved[pepeId]; } /** * @dev Get if an operator is approved for all tokens of that owner * @param _owner Owner to check the approval for * @param _operator Operator to check approval for * @return Boolean indicating if the operator is approved for that owner */ function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return approvedForAll[_owner][_operator]; } /** * @dev Function to signal support for an interface * @param interfaceID the ID of the interface to check for * @return Boolean indicating support */ function supportsInterface(bytes4 interfaceID) external pure returns (bool) { if( interfaceID == 0x01ffc9a7 // ERC 165 || interfaceID == 0x80ac58cd // ERC 721 base || interfaceID == 0x780e9d63 // ERC 721 enumerable || interfaceID == 0x4f558e79 // ERC 721 exists || interfaceID == 0x5b5e139f // ERC 721 metadata // TODO: add more interfaces such as // 0x150b7a02: ERC 721 receiver ) { return true; } return false; } /** * @dev Safe transferFrom function * @param _from Address currently owning the token * @param _to Address to send token to * @param pepeId ID of the token to send */ function safeTransferFrom(address _from, address _to, uint256 pepeId) external { _safeTransferFromInternal(_from, _to, pepeId, ""); } /** * @dev Safe transferFrom function with aditional data attribute * @param _from Address currently owning the token * @param _to Address to send token to * @param pepeId ID of the token to send * @param _data Data to pass along call */ // solhint-disable-next-line max-line-length function safeTransferFrom(address _from, address _to, uint256 pepeId, bytes _data) external { _safeTransferFromInternal(_from, _to, pepeId, _data); } /** * @dev Internal Safe transferFrom function with aditional data attribute * @param _from Address currently owning the token * @param _to Address to send token to * @param pepeId ID of the token to send * @param _data Data to pass along call */ // solhint-disable-next-line max-line-length function _safeTransferFromInternal(address _from, address _to, uint256 pepeId, bytes _data) internal onlyAllowed(pepeId) { require(_ownerOf(pepeId) == _from);//check if from is current owner require(_to != address(0));//throw on zero address _transfer(_from, _to, pepeId); //transfer token if (isContract(_to)) { //check if is contract // solhint-disable-next-line max-line-length require(ERC721TokenReceiver(_to).onERC721Received(_from, pepeId, _data) == bytes4(keccak256("onERC721Received(address,uint256,bytes)"))); } } /** * @dev TransferFrom function * @param _from Address currently owning the token * @param _to Address to send token to * @param pepeId ID of the token to send * @return If it was successful */ // solhint-disable-next-line max-line-length function transferFrom(address _from, address _to, uint256 pepeId) public onlyAllowed(pepeId) returns(bool) { require(_ownerOf(pepeId) == _from);//check if _from is really the master. require(_to != address(0)); _transfer(_from, _to, pepeId);//handles event, balances and approval reset; return true; } /** * @dev Utility method to check if an address is a contract * @param _address Address to check * @return Boolean indicating if the address is a contract */ function isContract(address _address) internal view returns (bool) { uint size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(_address) } return size > 0; } /** * @dev Returns whether the specified token exists * @param pepeId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 pepeId) public view returns (bool) { return 0 < pepeId && pepeId <= (REBORN_PEPE_0 + rebornPepes.length - 1);//this.totalSupply(); } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param pepeId uint256 ID of the token to query */ function tokenURI(uint256 pepeId) public view returns (string) { require(exists(pepeId)); return string(abi.encodePacked(baseTokenURI, toString(pepeId))); } /** * @dev Changes the base URI for metadata. * @param baseURI the new base URI */ function setBaseTokenURI(string baseURI) public onlyOwner { baseTokenURI = baseURI; } /** * @dev Returns the URI for the contract * @return the uri */ function contractURI() public view returns (string) { return contractUri; } /** * @dev Changes the URI for the contract * @param uri the new uri */ function setContractURI(string uri) public onlyOwner { contractUri = uri; } /** * @dev Converts a `uint256` to its ASCII `string` representation. * @param value a number to convert to string * @return a string representation of the number */ function toString(uint256 value) internal pure returns (string memory) { // Borrowed from Open Zeppelin, which was // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } /** * @dev get Pepe information * Returns information as separate variables * @param pepeId ID of the Pepe to get information of * @return master * @return genotype * @return canCozyAgain * @return generation * @return father * @return mother * @return pepeName * @return coolDownIndex */ // solhint-disable-next-line max-line-length function getPepe(uint256 pepeId) public view returns (address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) { Pepe memory pepe = _getPepe(pepeId); master = pepe.master; genotype = pepe.genotype; canCozyAgain = pepe.canCozyAgain; generation = pepe.generation; father = pepe.father; mother = pepe.mother; pepeName = pepeNames[pepeId]; coolDownIndex = pepe.coolDownIndex; } /** * @dev get Pepe information * Returns information as a single Pepe struct * @param pepeId ID of the Pepe to get information of * @return pepe info */ function _getPepe(uint256 pepeId) internal view returns (Pepe memory) { if(pepeId >= REBORN_PEPE_0) { uint256 index = rebornPepeIdToIndex(pepeId); require(index < rebornPepes.length); return rebornPepes[index]; }else{ (address master, uint256[2] memory genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, , uint8 coolDownIndex) = _getUndeadPepe(pepeId); return Pepe({ master: master, // The master of the pepe genotype: genotype, // all genes stored here canCozyAgain: canCozyAgain, // time when pepe can have nice time again father: uint64(father), // father of this pepe mother: uint64(mother), // mommy of this pepe generation: generation, // what generation? coolDownIndex: coolDownIndex }); } } /** * @dev get undead pepe information * @param pepeId ID of the Pepe to get information of * @return master * @return genotype * @return canCozyAgain * @return generation * @return father * @return mother * @return pepeName * @return coolDownIndex */ function _getUndeadPepe(uint256 pepeId) internal view returns (address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) { // if undead, pull from old contract (master, genotype, canCozyAgain, generation, father, mother, pepeName, coolDownIndex) = PepeBase(PEPE_UNDEAD_ADDRRESS).getPepe(pepeId); if(undeadPepes[pepeId].resurrected){ // if resurrected, pull from undead map master = undeadPepes[pepeId].master; canCozyAgain = undeadPepes[pepeId].canCozyAgain; pepeName = pepeNames[pepeId]; coolDownIndex = undeadPepes[pepeId].coolDownIndex; }else if(master == PEPE_AUCTION_SALE_UNDEAD_ADDRESS || master == COZY_TIME_AUCTION_UNDEAD_ADDRESS){ // if on auction, return to seller (master, , , , , ) = AuctionBase(master).auctions(pepeId); } } // Useful for tracking resurrections event PepeResurrected(uint256 pepeId); /** * @dev Checks if the pepe needs to be resurrected from the old contract and if so does. * @param pepeId ID of the Pepe to check */ // solhint-disable-next-line max-line-length function checkResurrected(uint256 pepeId) public { if(pepeId >= REBORN_PEPE_0) return; if(undeadPepes[pepeId].resurrected) return; (address _master, , uint64 _canCozyAgain, , , , bytes32 _pepeName, uint8 _coolDownIndex) = _getUndeadPepe(pepeId); undeadPepes[pepeId] = UndeadPepeMutable({ master: _master, // The master of the pepe canCozyAgain: _canCozyAgain, // time when pepe can have nice time again coolDownIndex: _coolDownIndex, resurrected: true }); if(_pepeName != 0x0000000000000000000000000000000000000000000000000000000000000000) pepeNames[pepeId] = _pepeName; addToWallet(_master, pepeId); emit PepeResurrected(pepeId); } /** * @dev Calculates reborn pepe array index * @param pepeId ID of the pepe to check * @return array index */ function rebornPepeIdToIndex(uint256 pepeId) internal pure returns (uint256) { require(pepeId >= REBORN_PEPE_0); return pepeId - REBORN_PEPE_0; } /** * @dev Changes the address of the previous contracts * This is only a precaution in case I mess up deployment * @param baseaddr the correct PepeBase address * @param saleauctionaddr the correct PepeSaleAuction address * @param cozyauctionaddr the correct CozyTimeAuction address */ function setPrevContracts(address baseaddr, address saleauctionaddr, address cozyauctionaddr) public onlyOwner { PEPE_UNDEAD_ADDRRESS = baseaddr; PEPE_AUCTION_SALE_UNDEAD_ADDRESS = saleauctionaddr; COZY_TIME_AUCTION_UNDEAD_ADDRESS = cozyauctionaddr; } /** * @dev Changes the gene pool contract address * @param genePoolAddress the new pool address */ function setGenePool(address genePoolAddress) public onlyOwner { GenePoolInterface pool = GenePoolInterface(genePoolAddress); require(pool.isGenePool()); genePool = pool; } } contract GenesisActTwo { PepeReborn public cpepToken; address public owner; uint256 public price = 100000000000000000; // 0.1 eth uint256 public mined; modifier onlyOwner() { require(owner == msg.sender, "not owner"); _; } constructor(address _cpepToken, address _owner) { cpepToken = PepeReborn(_cpepToken); owner = _owner; } function birth(uint256 amount) external payable { require(msg.value >= amount * price, "insufficient payment"); uint256 startSupply = cpepToken.totalSupply(); cpepToken.pepePremine(amount); for(uint256 pepeId = startSupply+1; pepeId <= startSupply + amount; ++pepeId) { cpepToken.transfer(msg.sender, pepeId); } mined += amount; } function setPrice(uint256 _price) external onlyOwner { price = _price; } function sweep(address recipient, uint256 amount) external onlyOwner { recipient.transfer(amount); } function transferOwnership(address newOwner) external onlyOwner { cpepToken.transferOwnership(newOwner); } }
Returns an URI for a given token ID Throws if the token ID does not exist. May return an empty string. pepeId uint256 ID of the token to query/
function tokenURI(uint256 pepeId) public view returns (string) { require(exists(pepeId)); return string(abi.encodePacked(baseTokenURI, toString(pepeId))); }
10,871,817
pragma solidity 0.4.24; // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: openzeppelin-solidity/contracts/introspection/ERC165.sol /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/introspection/SupportsInterfaceWithLookup.sol /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 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, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `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 whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array ownedTokens[_from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } // File: contracts/IMarketplace.sol contract IMarketplace { function createAuction( uint256 _tokenId, uint128 startPrice, uint128 endPrice, uint128 duration ) external; } // File: contracts/GameData.sol contract GameData { struct Country { bytes2 isoCode; uint8 animalsCount; uint256[3] animalIds; } struct Animal { bool isSold; uint256 currentValue; uint8 rarity; // 0-4, rarity = stat range, higher rarity = better stats bytes32 name; uint256 countryId; // country of origin } struct Dna { uint256 animalId; uint8 effectiveness; // 1 - 100, 100 = same stats as a wild card } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/Restricted.sol contract Restricted is Ownable { mapping(address => bool) private addressIsAdmin; bool private isActive = true; modifier onlyAdmin() { require(addressIsAdmin[msg.sender] || msg.sender == owner); _; } modifier contractIsActive() { require(isActive); _; } function addAdmin(address adminAddress) public onlyOwner { addressIsAdmin[adminAddress] = true; } function removeAdmin(address adminAddress) public onlyOwner { addressIsAdmin[adminAddress] = false; } function pauseContract() public onlyOwner { isActive = false; } function activateContract() public onlyOwner { isActive = true; } } // File: contracts/CryptoServal.sol contract CryptoServal is ERC721Token("CryptoServal", "CS"), GameData, Restricted { using AddressUtils for address; uint8 internal developersFee = 5; uint256[3] internal rarityTargetValue = [0.5 ether, 1 ether, 2 ether]; Country[] internal countries; Animal[] internal animals; Dna[] internal dnas; using SafeMath for uint256; event AnimalBoughtEvent( uint256 animalId, address previousOwner, address newOwner, uint256 pricePaid, bool isSold ); mapping (address => uint256) private addressToDnaCount; mapping (uint => address) private dnaIdToOwnerAddress; uint256 private startingAnimalPrice = 0.001 ether; IMarketplace private marketplaceContract; bool private shouldGenerateDna = true; modifier validTokenId(uint256 _tokenId) { require(_tokenId < animals.length); _; } modifier soldOnly(uint256 _tokenId) { require(animals[_tokenId].isSold); _; } modifier isNotFromContract() { require(!msg.sender.isContract()); _; } function () public payable { } function createAuction( uint256 _tokenId, uint128 startPrice, uint128 endPrice, uint128 duration ) external isNotFromContract { // approve, not a transfer, let marketplace confirm the original owner and take ownership approve(address(marketplaceContract), _tokenId); marketplaceContract.createAuction(_tokenId, startPrice, endPrice, duration); } function setMarketplaceContract(address marketplaceAddress) external onlyOwner { marketplaceContract = IMarketplace(marketplaceAddress); } function getPlayerAnimals(address playerAddress) external view returns(uint256[]) { uint256 animalsOwned = ownedTokensCount[playerAddress]; uint256[] memory playersAnimals = new uint256[](animalsOwned); if (animalsOwned == 0) { return playersAnimals; } uint256 animalsLength = animals.length; uint256 playersAnimalsIndex = 0; uint256 animalId = 0; while (playersAnimalsIndex < animalsOwned && animalId < animalsLength) { if (tokenOwner[animalId] == playerAddress) { playersAnimals[playersAnimalsIndex] = animalId; playersAnimalsIndex++; } animalId++; } return playersAnimals; } function getPlayerDnas(address playerAddress) external view returns(uint256[]) { uint256 dnasOwned = addressToDnaCount[playerAddress]; uint256[] memory playersDnas = new uint256[](dnasOwned); if (dnasOwned == 0) { return playersDnas; } uint256 dnasLength = dnas.length; uint256 playersDnasIndex = 0; uint256 dnaId = 0; while (playersDnasIndex < dnasOwned && dnaId < dnasLength) { if (dnaIdToOwnerAddress[dnaId] == playerAddress) { playersDnas[playersDnasIndex] = dnaId; playersDnasIndex++; } dnaId++; } return playersDnas; } function transferFrom(address _from, address _to, uint256 _tokenId) public validTokenId(_tokenId) soldOnly(_tokenId) { super.transferFrom(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public validTokenId(_tokenId) soldOnly(_tokenId) { super.safeTransferFrom(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public validTokenId(_tokenId) soldOnly(_tokenId) { super.safeTransferFrom(_from, _to, _tokenId, _data); } function buyAnimal(uint256 id) public payable isNotFromContract contractIsActive { uint256 etherSent = msg.value; address sender = msg.sender; Animal storage animalToBuy = animals[id]; require(etherSent >= animalToBuy.currentValue); require(tokenOwner[id] != sender); require(!animalToBuy.isSold); uint256 etherToPay = animalToBuy.currentValue; uint256 etherToRefund = etherSent.sub(etherToPay); address previousOwner = tokenOwner[id]; // Inlined transferFrom clearApproval(previousOwner, id); removeTokenFrom(previousOwner, id); addTokenTo(sender, id); emit Transfer(previousOwner, sender, id); // // subtract developers fee uint256 ownersShare = etherToPay.sub(etherToPay * developersFee / 100); // pay previous owner previousOwner.transfer(ownersShare); // refund overpaid ether refundSender(sender, etherToRefund); // If the bid is above the target price, lock the buying via this contract and enable ERC721 if (etherToPay >= rarityTargetValue[animalToBuy.rarity]) { animalToBuy.isSold = true; animalToBuy.currentValue = 0; } else { // calculate new value, multiplier depends on current amount of ether animalToBuy.currentValue = calculateNextEtherValue(animalToBuy.currentValue); } if (shouldGenerateDna) { generateDna(sender, id, etherToPay, animalToBuy); } emit AnimalBoughtEvent(id, previousOwner, sender, etherToPay, animalToBuy.isSold); } function getAnimal(uint256 _animalId) public view returns( uint256 countryId, bytes32 name, uint8 rarity, uint256 currentValue, uint256 targetValue, address owner, uint256 id ) { Animal storage animal = animals[_animalId]; return ( animal.countryId, animal.name, animal.rarity, animal.currentValue, rarityTargetValue[animal.rarity], tokenOwner[_animalId], _animalId ); } function getAnimalsCount() public view returns(uint256 animalsCount) { return animals.length; } function getDna(uint256 _dnaId) public view returns( uint animalId, address owner, uint16 effectiveness, uint256 id ) { Dna storage dna = dnas[_dnaId]; return (dna.animalId, dnaIdToOwnerAddress[_dnaId], dna.effectiveness, _dnaId); } function getDnasCount() public view returns(uint256) { return dnas.length; } function getCountry(uint256 _countryId) public view returns( bytes2 isoCode, uint8 animalsCount, uint256[3] animalIds, uint256 id ) { Country storage country = countries[_countryId]; return(country.isoCode, country.animalsCount, country.animalIds, _countryId); } function getCountriesCount() public view returns(uint256 countriesCount) { return countries.length; } function getDevelopersFee() public view returns(uint8) { return developersFee; } function getMarketplaceContract() public view returns(address) { return marketplaceContract; } function getShouldGenerateDna() public view returns(bool) { return shouldGenerateDna; } function withdrawContract() public onlyOwner { msg.sender.transfer(address(this).balance); } function setDevelopersFee(uint8 _developersFee) public onlyOwner { require((_developersFee >= 0) && (_developersFee <= 8)); developersFee = _developersFee; } function setShouldGenerateDna(bool _shouldGenerateDna) public onlyAdmin { shouldGenerateDna = _shouldGenerateDna; } function addCountry(bytes2 isoCode) public onlyAdmin { Country memory country; country.isoCode = isoCode; countries.push(country); } function addAnimal(uint256 countryId, bytes32 animalName, uint8 rarity) public onlyAdmin { require((rarity >= 0) && (rarity < 3)); Country storage country = countries[countryId]; uint256 id = animals.length; // id is assigned before push Animal memory animal = Animal( false, // new animal is not sold yet startingAnimalPrice, rarity, animalName, countryId ); animals.push(animal); addAnimalIdToCountry(id, country); _mint(address(this), id); } function changeCountry(uint256 id, bytes2 isoCode) public onlyAdmin { Country storage country = countries[id]; country.isoCode = isoCode; } function changeAnimal(uint256 animalId, uint256 countryId, bytes32 name, uint8 rarity) public onlyAdmin { require(countryId < countries.length); Animal storage animal = animals[animalId]; if (animal.name != name) { animal.name = name; } if (animal.rarity != rarity) { require((rarity >= 0) && (rarity < 3)); animal.rarity = rarity; } if (animal.countryId != countryId) { Country storage country = countries[countryId]; uint256 oldCountryId = animal.countryId; addAnimalIdToCountry(animalId, country); removeAnimalIdFromCountry(animalId, oldCountryId); animal.countryId = countryId; } } function setRarityTargetValue(uint8 index, uint256 targetValue) public onlyAdmin { rarityTargetValue[index] = targetValue; } function calculateNextEtherValue(uint256 currentEtherValue) public pure returns(uint256) { if (currentEtherValue < 0.1 ether) { return currentEtherValue.mul(2); } else if (currentEtherValue < 0.5 ether) { return currentEtherValue.mul(3).div(2); // x1.5 } else if (currentEtherValue < 1 ether) { return currentEtherValue.mul(4).div(3); // x1.33 } else if (currentEtherValue < 5 ether) { return currentEtherValue.mul(5).div(4); // x1.25 } else if (currentEtherValue < 10 ether) { return currentEtherValue.mul(6).div(5); // x1.2 } else { return currentEtherValue.mul(7).div(6); // 1.16 } } function refundSender(address sender, uint256 etherToRefund) private { if (etherToRefund > 0) { sender.transfer(etherToRefund); } } function generateDna( address sender, uint256 animalId, uint256 pricePaid, Animal animal ) private { uint256 id = dnas.length; // id is assigned before push Dna memory dna = Dna( animalId, calculateAnimalEffectiveness(pricePaid, animal) ); dnas.push(dna); dnaIdToOwnerAddress[id] = sender; addressToDnaCount[sender] = addressToDnaCount[sender].add(1); } function calculateAnimalEffectiveness( uint256 pricePaid, Animal animal ) private view returns(uint8) { if (animal.isSold) { return 100; } uint256 effectiveness = 10; // 10-90; // more common the animal = cheaper effectiveness uint256 effectivenessPerEther = 10**18 * 80 / rarityTargetValue[animal.rarity]; effectiveness = effectiveness.add(pricePaid * effectivenessPerEther / 10**18); if (effectiveness > 90) { effectiveness = 90; } return uint8(effectiveness); } function addAnimalIdToCountry( uint256 animalId, Country storage country ) private { uint8 animalSlotIndex = country.animalsCount; require(animalSlotIndex < 3); country.animalIds[animalSlotIndex] = animalId; country.animalsCount += 1; } function removeAnimalIdFromCountry(uint256 animalId, uint256 countryId) private { Country storage country = countries[countryId]; for (uint8 i = 0; i < country.animalsCount; i++) { if (country.animalIds[i] == animalId) { if (i != country.animalsCount - 1) { country.animalIds[i] = country.animalIds[country.animalsCount - 1]; } country.animalsCount -= 1; return; } } } }
approve, not a transfer, let marketplace confirm the original owner and take ownership
function createAuction( uint256 _tokenId, uint128 startPrice, uint128 endPrice, uint128 duration ) external isNotFromContract { approve(address(marketplaceContract), _tokenId); marketplaceContract.createAuction(_tokenId, startPrice, endPrice, duration); }
7,325,527
./full_match/4/0xfBdD4577b7AeB49070b98d5F50147Ec5CA9766Bb/sources/FirmaPro/FirstTest.sol
Unpauses all token transfers. See {ERC1155Pausable} and {Pausable-_unpause}. Requirements: - the caller must have the `PAUSER_ROLE`./
function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), 'ERC1155: must have pauser role to unpause'); _unpause(); }
809,451
// pragma solidity >= 0.4.24 < 0.5.0; pragma solidity ^0.4.23; import "./SafeMath.sol"; import "./DOSOnChainSDK.sol"; import "./utils.sol"; contract OptionMarket is DOSOnChainSDK { using SafeMath for *; using utils for *; enum State { Open, Filled, Exercised } uint constant MIN_COLLATERAL = 1 trx; // orderId monotonously increase from 1. uint public orderId = 0; // amount of attr unable large than 15 struct Order { uint collateral; // Collateral in amount of sun. Both option maker and taker need to provide same amount of collateral. uint start; // Open order time in unix epoch format. uint expiration; // An option's expiration time in unix epoch format, after which an option order can be exercised. uint strikePrice; // Strike price specified by option maker (precise to 5 decimals) uint exercisePrice; // Exercise price fetched by oracle (precise to 5 decimals) address maker; // Option maker address taker; // Option taker bool maker_position; // 0: short; 1: long bool taker_position; // !maker_position uint8 leverage; // 1x, 2x, ... , 10x string symbol; // Crypto symbol like ETH, BTC, TRX, etc.; or stock symbol like AMZN, BABA, etc. Usually filled by frontend. State status; uint makerPayout; uint takerPayout; } // Global on-chain orderbooks, including all open and exercised orders. mapping(uint => Order) public orders; // Global list of open orders' order id. Build open order dasboard on frontend. uint[] public openOrders; // Per user open orders, build dashboard on /Personal page. mapping(address => uint[]) public openOrderByOwner; // Per user's filled orders. Build dashboard on /Personal frontend. mapping(address => uint[]) public filledOrderByOwner; mapping(uint => uint) queryToOrderId; mapping(uint => bool) orderInExercise; //event event LogOpen(address indexed makerAddr); event LogPartialFill(address indexed makerAddr,address indexed takerAddr); event LogFill(address indexed makerAddr,address indexed takerAddr); event LogCancel(address indexed makerAddr); event LogExec(address indexed makerAddr,address indexed takerAddr); constructor(address addr) DOSOnChainSDK(addr) public {} modifier validId(uint id) { require(orders[id].maker != 0); _; } // To get rid of too frequent arbitrage, an order can be filled until: // 1. 2h before expiration if window >= 12h // 2. 30min before expiration if 12h > window >= 1h // 3. anytime before expiration if 1h > window > 0 modifier canFill(uint id) { uint window = orders[id].expiration - orders[id].start; uint before = 0; if (window >= 12 hours) before = 2 hours; else if (window >= 1 hours) before = 30 minutes; else before = 0; assert(orders[id].expiration - before >= now); _; } //tron vm can not directly return array storage attr... function getOrders() public view returns(uint[]) { return openOrders; } function getOpenOrderByOwner() public view returns(uint[]) { return openOrderByOwner[msg.sender]; } function getFilledOrderByOwner() public view returns(uint[]) { return filledOrderByOwner[msg.sender]; } function open(string symbol, uint strikePrice, uint8 leverage, uint expiration, bool position) public payable returns (uint) { require(leverage >= 1 && leverage <= 10); require(expiration > now); require(msg.value >= MIN_COLLATERAL); ++orderId; orders[orderId] = Order(msg.value, now, expiration, strikePrice, 0, msg.sender, 0x0, position, !position, leverage, symbol, State.Open, 0, 0); openOrders.push(orderId); openOrderByOwner[msg.sender].push(orderId); emit LogOpen(msg.sender); return orderId; } // Maker can cancel an order if it's not (fully) taken. function cancelOrder(uint id) public validId(id) { Order memory order = orders[id]; require(order.taker == 0x0 && order.maker == msg.sender); delete orders[id]; removeByValue(openOrders, id); removeByValue(openOrderByOwner[msg.sender], id); order.maker.transfer(order.collateral); emit LogCancel(msg.sender); } // Taker can partially take an order before expiration. function partialFill(uint id) public payable validId(id) canFill(id) { require(orders[id].status == State.Open); require(msg.value >= MIN_COLLATERAL && orders[id].collateral.sub(msg.value) >= MIN_COLLATERAL); // Adjust partially filled order orders[id].collateral -= msg.value; // Create a new filled order. Order memory newOrder = orders[id]; ++orderId; newOrder.collateral = msg.value; newOrder.taker = msg.sender; newOrder.status = State.Filled; orders[orderId] = newOrder; filledOrderByOwner[newOrder.taker].push(orderId); filledOrderByOwner[newOrder.maker].push(orderId); emit LogPartialFill(orders[id].maker,msg.sender); } // Taker can take an order before expiration. function fill(uint id) public payable validId(id) canFill(id) { require(orders[id].status == State.Open); // Taker must provide same amount of collateral as deposited by the option maker. require(msg.value == orders[id].collateral); removeByValue(openOrders, id); removeByValue(openOrderByOwner[orders[id].maker], id); filledOrderByOwner[orders[id].maker].push(id); filledOrderByOwner[msg.sender].push(id); orders[id].taker = msg.sender; orders[id].status = State.Filled; emit LogFill(orders[id].maker,msg.sender); } // Either maker or taker can exercise a filled order to finalize at any time after expiration. // However the maximum profit/loss is the amount of collateral. // Contracts queries oracle to get final exercise price at timestamp expiration. function exercise(uint id) public validId(id) { require(orders[id].status == State.Filled && !orderInExercise[id]); require(block.timestamp > orders[id].expiration); require(msg.sender == orders[id].maker || msg.sender == orders[id].taker); string memory dataSource; string memory selector; (dataSource, selector) = buildOracleRequest(orders[id].symbol, orders[id].expiration); uint queryId = DOSQuery(30, dataSource, selector); queryToOrderId[queryId] = id; orderInExercise[id] = true; } function __callback__(uint queryId, bytes memory result) public { require(msg.sender == fromDOSProxyContract()); require(queryToOrderId[queryId] != 0); string memory price_str = string(result); uint price = price_str.str2Uint(); uint fractional = 0; int delimit_idx = price_str.indexOf('.'); if (delimit_idx != -1) { fractional = price_str.subStr(uint(delimit_idx + 1)).str2Uint(); } uint order_id = queryToOrderId[queryId]; Order storage order = orders[order_id]; order.exercisePrice = price * 1e4 + fractional; uint total = 2 * order.collateral; uint payToMaker = 0; // condition of Maker Long // payToMaker = collateral * (1 + leverage * (exercisePrice - strikePrice) / strikePrice); if(order.maker_position){ if (order.exercisePrice >= order.strikePrice && (order.exercisePrice - order.strikePrice).mul(order.leverage) >= order.strikePrice) { payToMaker = total; } else if (order.strikePrice >= order.exercisePrice && (order.strikePrice - order.exercisePrice).mul(order.leverage) >= order.strikePrice) { payToMaker = 0; } else { payToMaker = (order.exercisePrice.mul(order.leverage) - (order.leverage - 1).mul(order.strikePrice)).mul(order.collateral).div(order.strikePrice); } } // condition of Maker short else { if (order.exercisePrice >= order.strikePrice && (order.exercisePrice - order.strikePrice).mul(order.leverage) >= order.strikePrice) { payToMaker = 0; } else if (order.strikePrice >= order.exercisePrice && (order.strikePrice - order.exercisePrice).mul(order.leverage) >= order.strikePrice) { payToMaker = total; } else { payToMaker = ((order.leverage + 1).mul(order.strikePrice) - order.exercisePrice.mul(order.leverage)).mul(order.collateral).div(order.strikePrice); } } uint payToTaker = total.sub(payToMaker); order.status = State.Exercised; delete orderInExercise[order_id]; delete queryToOrderId[queryId]; order.makerPayout = payToMaker; order.takerPayout = payToTaker; order.maker.transfer(payToMaker); order.taker.transfer(payToTaker); emit LogExec(order.maker,order.taker); } // Build oracle request, returns (data source, selector) string. function buildOracleRequest(string symbol, uint timestamp) private view returns (string, string) { timestamp = min(now, timestamp); // Get historial price by https://min-api.cryptocompare.com/data/pricehistorical?e=binance&tsyms=USDT&fsym=ETH&ts=1545868355 return ( "https://min-api.cryptocompare.com/data/pricehistorical?e=binance&tsyms=USDT&fsym=".strConcat(symbol).strConcat("&ts=").strConcat(utils.uint2Str(timestamp)), "$.".strConcat(symbol).strConcat(".USDT") ); } function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } function removeByValue(uint[] storage arr, uint val) private { uint len = arr.length; for (uint i = 0; i < len; i++) { if (arr[i] == val) { arr[i] = arr[len - 1]; delete arr[len-1]; arr.length--; return; } } } }
condition of Maker Long payToMaker = collateral (1 + leverage (exercisePrice - strikePrice) / strikePrice); condition of Maker short
function __callback__(uint queryId, bytes memory result) public { require(msg.sender == fromDOSProxyContract()); require(queryToOrderId[queryId] != 0); string memory price_str = string(result); uint price = price_str.str2Uint(); uint fractional = 0; int delimit_idx = price_str.indexOf('.'); if (delimit_idx != -1) { fractional = price_str.subStr(uint(delimit_idx + 1)).str2Uint(); } uint order_id = queryToOrderId[queryId]; Order storage order = orders[order_id]; order.exercisePrice = price * 1e4 + fractional; uint total = 2 * order.collateral; uint payToMaker = 0; if(order.maker_position){ if (order.exercisePrice >= order.strikePrice && (order.exercisePrice - order.strikePrice).mul(order.leverage) >= order.strikePrice) { payToMaker = total; payToMaker = 0; payToMaker = (order.exercisePrice.mul(order.leverage) - (order.leverage - 1).mul(order.strikePrice)).mul(order.collateral).div(order.strikePrice); } } else { if (order.exercisePrice >= order.strikePrice && (order.exercisePrice - order.strikePrice).mul(order.leverage) >= order.strikePrice) { payToMaker = 0; payToMaker = total; payToMaker = ((order.leverage + 1).mul(order.strikePrice) - order.exercisePrice.mul(order.leverage)).mul(order.collateral).div(order.strikePrice); } } uint payToTaker = total.sub(payToMaker); order.status = State.Exercised; delete orderInExercise[order_id]; delete queryToOrderId[queryId]; order.makerPayout = payToMaker; order.takerPayout = payToTaker; order.maker.transfer(payToMaker); order.taker.transfer(payToTaker); emit LogExec(order.maker,order.taker); }
5,517,255
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title KYC * @dev KYC contract handles the white list for ASTCrowdsale contract * Only accounts registered in KYC contract can buy AST token. * Admins can register account, and the reason why */ contract KYC is Ownable { // check the address is registered for token sale // first boolean is true if presale else false // second boolean is true if registered else false mapping (address => mapping (bool => bool)) public registeredAddress; // check the address is admin of kyc contract mapping (address => bool) public admin; event Registered(address indexed _addr); event Unregistered(address indexed _addr); event SetAdmin(address indexed _addr); /** * @dev check whether the address is registered for token sale or not. * @param _addr address * @param _isPresale bool Whether the address is registered to presale or mainsale */ modifier onlyRegistered(address _addr, bool _isPresale) { require(registeredAddress[_addr][_isPresale]); _; } /** * @dev check whether the msg.sender is admin or not */ modifier onlyAdmin() { require(admin[msg.sender]); _; } function KYC() public { admin[msg.sender] = true; } /** * @dev set new admin as admin of KYC contract * @param _addr address The address to set as admin of KYC contract */ function setAdmin(address _addr, bool _value) public onlyOwner returns (bool) { require(_addr != address(0)); require(admin[_addr] == !_value); admin[_addr] = _value; SetAdmin(_addr); return true; } /** * @dev check the address is register * @param _addr address The address to check * @param _isPresale bool Whether the address is registered to presale or mainsale */ function isRegistered(address _addr, bool _isPresale) public view returns (bool) { return registeredAddress[_addr][_isPresale]; } /** * @dev register the address for token sale * @param _addr address The address to register for token sale * @param _isPresale bool Whether register to presale or mainsale */ function register(address _addr, bool _isPresale) public onlyAdmin { require(_addr != address(0) && registeredAddress[_addr][_isPresale] == false); registeredAddress[_addr][_isPresale] = true; Registered(_addr); } /** * @dev register the addresses for token sale * @param _addrs address[] The addresses to register for token sale * @param _isPresale bool Whether register to presale or mainsale */ function registerByList(address[] _addrs, bool _isPresale) public onlyAdmin { for(uint256 i = 0; i < _addrs.length; i++) { register(_addrs[i], _isPresale); } } /** * @dev unregister the registered address * @param _addr address The address to unregister for token sale * @param _isPresale bool Whether unregister to presale or mainsale */ function unregister(address _addr, bool _isPresale) public onlyAdmin onlyRegistered(_addr, _isPresale) { registeredAddress[_addr][_isPresale] = false; Unregistered(_addr); } /** * @dev unregister the registered addresses * @param _addrs address[] The addresses to unregister for token sale * @param _isPresale bool Whether unregister to presale or mainsale */ function unregisterByList(address[] _addrs, bool _isPresale) public onlyAdmin { for(uint256 i = 0; i < _addrs.length; i++) { unregister(_addrs[i], _isPresale); } } } contract PaymentFallbackReceiver { BTCPaymentI public payment; enum SaleType { pre, main } function PaymentFallbackReceiver(address _payment) public { require(_payment != address(0)); payment = BTCPaymentI(_payment); } modifier onlyPayment() { require(msg.sender == address(payment)); _; } event MintByBTC(SaleType _saleType, address indexed _beneficiary, uint256 _tokens); /** * @dev paymentFallBack() is called in BTCPayment.addPayment(). * Presale or Mainsale contract should mint token to beneficiary, * and apply corresponding ether amount to max ether cap. * @param _beneficiary ethereum address who receives tokens * @param _tokens amount of FXT to mint */ function paymentFallBack(address _beneficiary, uint256 _tokens) external onlyPayment(); } contract PresaleFallbackReceiver { bool public presaleFallBackCalled; function presaleFallBack(uint256 _presaleWeiRaised) public returns (bool); } contract BTCPaymentI is Ownable, PresaleFallbackReceiver { PaymentFallbackReceiver public presale; PaymentFallbackReceiver public mainsale; function addPayment(address _beneficiary, uint256 _tokens) public; function setPresale(address _presale) external; function setMainsale(address _mainsale) external; function presaleFallBack(uint256) public returns (bool); } contract BTCPayment is Ownable, PresaleFallbackReceiver { using SafeMath for uint256; PaymentFallbackReceiver public presale; PaymentFallbackReceiver public mainsale; event NewPayment(address _beneficiary, uint256 _tokens); function addPayment(address _beneficiary, uint256 _tokens) public onlyOwner { if (!presaleFallBackCalled) { presale.paymentFallBack(_beneficiary, _tokens); } else { mainsale.paymentFallBack(_beneficiary, _tokens); } NewPayment(_beneficiary, _tokens); } function setPresale(address _presale) external onlyOwner { require(presale == address(0)); presale = PaymentFallbackReceiver(_presale); // datatype conversion `address` to `PaymentFallbackReceiver`. not calling constructor `PaymentFallbackReceiver` } function setMainsale(address _mainsale) external onlyOwner { require(mainsale == address(0)); mainsale = PaymentFallbackReceiver(_mainsale); // datatype conversion `address` to `PaymentFallbackReceiver`. not calling constructor `PaymentFallbackReceiver` } /** * @dev Presale should notify that presale is finalized and mainsale * is going to start. */ function presaleFallBack(uint256) public returns (bool) { require(msg.sender == address(presale)); if (presaleFallBackCalled) return false; presaleFallBackCalled = true; return true; } }
set new admin as admin of KYC contract _addr address The address to set as admin of KYC contract/
function setAdmin(address _addr, bool _value) public onlyOwner returns (bool) { require(_addr != address(0)); require(admin[_addr] == !_value); admin[_addr] = _value; SetAdmin(_addr); return true; }
13,105,283
pragma solidity ^0.5.0; import "./oraclize/oraclizeAPI.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; contract Casino is usingOraclize { using SafeMath for uint256; enum State { Available, Started, Finished } State public state; uint256 betValue; address betOwner; address [] playersList; uint256 totalValue; constructor () public { //oraclize_setProof(proofType_Ledger); } modifier ifAvailable { require (state == State.Available); _; } modifier ifStarted { require (state == State.Started); _; } modifier checkValue (uint value) { require (value == betValue); _; } modifier ifFinished { require (state == State.Finished); _; } modifier checkOwner { require (msg.sender == betOwner); _; } function startGame(uint256 value) public ifAvailable payable { // require (value <= balanceOf(msg.sender)); betOwner = msg.sender; betValue = value; totalValue = totalValue.add(value); playersList.push(msg.sender); } function betIn(uint256 value) public ifStarted checkValue(value) payable { // require (value <= balanceOf(msg.sender)); totalValue = totalValue.add(value); playersList.push(msg.sender); } function endGame() public ifStarted checkOwner { requestRandom(); state = State.Finished; } function generateResults(uint number) internal ifFinished { require(number < playersList.length); // uint totalValue = betValue * playersList.length; address wonAddress = playersList[number]; for (uint i = 0 ; i < playersList.length ; ++i) { // _transfer(playerList[i], wonAddress, betValue); } state = State.Available; } function requestRandom() internal { uint countRandom = 4; uint delay = 0; uint callbackGas = 2000000; bytes32 queryId = oraclize_newRandomDSQuery(delay, countRandom, callbackGas); } // Results from oracle function __callback( bytes32 _queryId, string memory _result, bytes memory _proof ) public { require (msg.sender == oraclize_cbAddress()); require (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) == 0); uint limit = playersList.length; uint result = uint(keccak256(abi.encodePacked(_result))) % limit; generateResults(result); } }
uint totalValue = betValue playersList.length; _transfer(playerList[i], wonAddress, betValue);
function generateResults(uint number) internal ifFinished { require(number < playersList.length); address wonAddress = playersList[number]; for (uint i = 0 ; i < playersList.length ; ++i) { } state = State.Available; }
5,412,868
./full_match/44787/0x17A14408B17eD694283d3aafA57fe510987e8512/sources/contracts/StarFarm.sol
Deposit LP tokens to MasterChef for STAR allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; updatePool(_pid); (uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender()); uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100)); uint256 accStarPerShare = pool.accStarPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)).add(pool.extraAmount); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accStarPerShare = starReward.mul(1e12).div(lpSupply); } if(user.amount >0){ user.reward = user.reward.add(_amountpendingStar); } uint256 pending = user.reward; if(pending > 0) { starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100)); starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100)); pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100)); starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100)); pending = pending.sub(pending.mul(rewardRatio).div(100)); pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100)); starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100)); user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100)); starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100)); user.reward = 0; pool.accStarPerShare = accStarPerShare; } if (_amount > 0) { pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount); user.amount = user.amount.add(_amount); user.lastDeposit = block.timestamp; uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100); pool.extraAmount = pool.extraAmount.add(_extraAmount); if(isPoolUser[_pid][_msgSender()] == false){ userIndex[_pid][pool.size] = _msgSender(); pool.size += 1; isPoolUser[_pid][_msgSender()] = true; } } emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]); } event WidthdrawLog(uint256 _amount, uint256 _reward, uint256 _amountpendingStar, uint256 _amountGain,uint256 _extraAmount, uint256 _starReward); event GetReward(uint256 _lpSupply, uint256 multiplier,uint256 starReward,uint256 accStarPerShare,uint256 allocPoint, uint256 totalAllocPoint, uint256 _lastRewardBlock, uint256 _blockNumber); event widthLog(uint256 amountGain,uint256 accStarPerShare,uint256 lpSupply,uint256 amountpendingStar,uint256 reward);
13,290,041
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ contract SafeMath { uint constant DAY_IN_SECONDS = 86400; function mul(uint256 a, uint256 b) constant internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) constant internal returns (uint256) { assert(b != 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) constant internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) constant internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function mulByFraction(uint256 number, uint256 numerator, uint256 denominator) internal returns (uint256) { return div(mul(number, numerator), denominator); } // ICO date bonus calculation function dateBonus(uint startIco) internal returns (uint256) { // day from ICO start uint daysFromStart = (now - startIco) / DAY_IN_SECONDS + 1; if(daysFromStart >= 1 && daysFromStart <= 14) return 20; // +20% tokens if(daysFromStart >= 15 && daysFromStart <= 28) return 15; // +20% tokens if(daysFromStart >= 29 && daysFromStart <= 42) return 10; // +10% tokens if(daysFromStart >= 43) return 5; // +5% tokens // no discount return 0; } } /// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 /// @title Abstract token contract - Functions to be implemented by token contracts. contract AbstractToken { // This is not an abstract function, because solc won't recognize generated getter functions for public variables as functions function totalSupply() constant returns (uint256) {} function balanceOf(address owner) constant returns (uint256 balance); function transfer(address to, uint256 value) returns (bool success); function transferFrom(address from, address to, uint256 value) returns (bool success); function approve(address spender, uint256 value) returns (bool success); function allowance(address owner, address spender) constant returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Issuance(address indexed to, uint256 value); } contract StandardToken is AbstractToken { /* * Data structures */ mapping (address => uint256) balances; mapping (address => bool) ownerAppended; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; address[] public owners; /* * Read and write storage functions */ /// @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) returns (bool success) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(msg.sender, _to, _value); return true; } else { return false; } } /// @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) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(_from, _to, _value); return true; } else { return false; } } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* * Read storage functions */ /// @dev Returns number of allowed tokens for given address. /// @param _owner Address of token owner. /// @param _spender Address of token spender. function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract ShiftCashToken is StandardToken, SafeMath { /* * Token meta data */ string public constant name = "ShiftCashToken"; string public constant symbol = "SCASH"; uint public constant decimals = 18; // tottal supply address public icoContract = 0x0; /* * Modifiers */ modifier onlyIcoContract() { // only ICO contract is allowed to proceed require(msg.sender == icoContract); _; } /* * Contract functions */ /// @dev Contract is needed in icoContract address /// @param _icoContract Address of account which will be mint tokens function ShiftCashToken(address _icoContract) { assert(_icoContract != 0x0); icoContract = _icoContract; totalSupply = 0; } /// @dev Burns tokens from address. It's can be applied by account with address this.icoContract /// @param _from Address of account, from which will be burned tokens /// @param _value Amount of tokens, that will be burned function burnTokens(address _from, uint _value) onlyIcoContract { assert(_from != 0x0); require(_value > 0); balances[_from] = sub(balances[_from], _value); totalSupply = sub(totalSupply, _value); } /// @dev Adds tokens to address. It's can be applied by account with address this.icoContract /// @param _to Address of account to which the tokens will pass /// @param _value Amount of tokens function emitTokens(address _to, uint _value) onlyIcoContract { assert(_to != 0x0); require(_value > 0); balances[_to] = add(balances[_to], _value); totalSupply = add(totalSupply, _value); if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(msg.sender, _to, _value); } function getOwner(uint index) constant returns (address, uint256) { return (owners[index], balances[owners[index]]); } function getOwnerCount() constant returns (uint) { return owners.length; } } contract ShiftCashIco is SafeMath { /* * ICO meta data */ ShiftCashToken public shiftcashToken; AbstractToken public preIcoToken; enum State{ Pause, Init, Running, Stopped, Migrated } State public currentState = State.Pause; uint public startIcoDate = 0; // Address of account to which ethers will be tranfered in case of successful ICO address public escrow; // Address of manager address public icoManager; // Address of a account, that will transfer tokens from pre-ICO address public tokenImporter = 0x0; // Addresses of founders and bountyOwner address public founder1; address public bountyOwner; // BASE = 10^18 uint constant BASE = 1000000000000000000; // 5 778 000 SCASH tokens uint public constant supplyLimit = 5778000 * BASE; // 86 670 SCASH is token for bountyOwner uint public constant bountyOwnersTokens = 86670 * BASE; // 1 ETH = 450 SCASH uint public constant PRICE = 450; // 2018.07.05 07:00 UTC // founders' reward time uint public foundersRewardTime = 1530774000; // Amount of imported tokens from pre-ICO uint public importedTokens = 0; // Amount of sold tokens on ICO uint public soldTokensOnIco = 0; // Amount of issued tokens on pre-ICO uint public constant soldTokensOnPreIco = 69990267262342250546086; // Tokens to founders can be sent only if sentTokensToFounder == false and time > foundersRewardTime bool public sentTokensToFounder = false; // Tokens to bounty owner can be sent only after ICO bool public sentTokensToBountyOwner = false; uint public etherRaised = 0; /* * Modifiers */ modifier whenInitialized() { // only when contract is initialized require(currentState >= State.Init); _; } modifier onlyManager() { // only ICO manager can do this action require(msg.sender == icoManager); _; } modifier onIcoRunning() { // Checks, if ICO is running and has not been stopped require(currentState == State.Running); _; } modifier onIcoStopped() { // Checks if ICO was stopped or deadline is reached require(currentState == State.Stopped); _; } modifier notMigrated() { // Checks if base can be migrated require(currentState != State.Migrated); _; } modifier onlyImporter() { // only importer contract is allowed to proceed require(msg.sender == tokenImporter); _; } /// @dev Constructor of ICO. Requires address of icoManager, /// @param _icoManager Address of ICO manager /// @param _preIcoToken Address of pre-ICO contract function ShiftCashIco(address _icoManager, address _preIcoToken) { assert(_preIcoToken != 0x0); assert(_icoManager != 0x0); shiftcashToken = new ShiftCashToken(this); icoManager = _icoManager; preIcoToken = AbstractToken(_preIcoToken); } /// @dev Initialises addresses of founders, tokens owner, escrow. /// Initialises balances of tokens owner /// @param _founder1 Address of founder 1 /// @param _escrow Address of escrow function init(address _founder1, address _escrow) onlyManager { assert(currentState != State.Init); assert(_founder1 != 0x0); assert(_escrow != 0x0); founder1 = _founder1; escrow = _escrow; currentState = State.Init; } /// @dev Sets new state /// @param _newState Value of new state function setState(State _newState) public onlyManager { currentState = _newState; if(currentState == State.Running) { startIcoDate = now; } } /// @dev Sets new manager. Only manager can do it /// @param _newIcoManager Address of new ICO manager function setNewManager(address _newIcoManager) onlyManager { assert(_newIcoManager != 0x0); icoManager = _newIcoManager; } /// @dev Sets bounty owner. Only manager can do it /// @param _bountyOwner Address of Bounty owner function setBountyOwner(address _bountyOwner) onlyManager { assert(_bountyOwner != 0x0); bountyOwner = _bountyOwner; } // saves info if account's tokens were imported from pre-ICO mapping (address => bool) private importedFromPreIco; /// @dev Imports account's tokens from pre-ICO. It can be done only by user, ICO manager or token importer /// @param _account Address of account which tokens will be imported function importTokens(address _account) { // only token holder or manager can do migration require(msg.sender == icoManager || msg.sender == _account); require(!importedFromPreIco[_account]); uint preIcoBalance = preIcoToken.balanceOf(_account); if (preIcoBalance > 0) { shiftcashToken.emitTokens(_account, preIcoBalance); importedTokens = add(importedTokens, preIcoBalance); } importedFromPreIco[_account] = true; } /// @dev Buy quantity of tokens depending on the amount of sent ethers. /// @param _buyer Address of account which will receive tokens function buyTokens(address _buyer) private { assert(_buyer != 0x0); require(msg.value > 0); uint tokensToEmit = msg.value * PRICE; //calculate date bonus uint bonusPercent = dateBonus(startIcoDate); //total bonus tokens if(bonusPercent > 0){ tokensToEmit = tokensToEmit + mulByFraction(tokensToEmit, bonusPercent, 100); } require(add(soldTokensOnIco, tokensToEmit) <= supplyLimit); soldTokensOnIco = add(soldTokensOnIco, tokensToEmit); //emit tokens to token holder shiftcashToken.emitTokens(_buyer, tokensToEmit); etherRaised = add(etherRaised, msg.value); if(this.balance > 0) { require(escrow.send(this.balance)); } } /// @dev Fall back function function () payable onIcoRunning { buyTokens(msg.sender); } /// @dev Burn tokens from accounts only in state "not migrated". Only manager can do it /// @param _from Address of account function burnTokens(address _from, uint _value) onlyManager notMigrated { shiftcashToken.burnTokens(_from, _value); } /// @dev Partial withdraw. Only manager can do it function withdrawEther(uint _value) onlyManager { require(_value > 0); escrow.transfer(_value); } /// @dev Ether withdraw. Only manager can do it function withdrawAllEther() onlyManager { if(this.balance > 0) { escrow.transfer(this.balance); } } ///@dev Send tokens to bountyOwner depending on crowdsale results. Can be send only after ICO. function sendTokensToBountyOwner() onlyManager whenInitialized { require(!sentTokensToBountyOwner); //Calculate total tokens sold on pre-ICO and ICO uint tokensSold = add(soldTokensOnIco, soldTokensOnPreIco); //Calculate bounty tokens depending on total tokens sold uint bountyTokens = mulByFraction(tokensSold, 15, 1000); // 1.5% shiftcashToken.emitTokens(bountyOwner, bountyTokens); sentTokensToBountyOwner = true; } /// @dev Send tokens to founders. Can be sent only after shiftcashToken.rewardTime() (2018.07.05 0:00 UTC) function sendTokensToFounders() onlyManager whenInitialized { require(!sentTokensToFounder && now >= foundersRewardTime); //Calculate total tokens sold on pre-ICO and ICO uint tokensSold = add(soldTokensOnIco, soldTokensOnPreIco); //Calculate founder reward depending on total tokens sold uint totalRewardToFounder = mulByFraction(tokensSold, 1000, 10000); // 10% shiftcashToken.emitTokens(founder1, totalRewardToFounder); sentTokensToFounder = true; } }
Adds tokens to address. It's can be applied by account with address this.icoContract _to Address of account to which the tokens will pass _value Amount of tokens
function emitTokens(address _to, uint _value) onlyIcoContract { assert(_to != 0x0); require(_value > 0); balances[_to] = add(balances[_to], _value); totalSupply = add(totalSupply, _value); if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(msg.sender, _to, _value); }
12,981,597
import "../../contracts/PermissionManager.sol"; /** * Hashmap Permission Manager - test a permissioned hashmap */ contract HashmapPermissionManager is PermissionManager { uint constant MODIFY_MAP = 1234; constructor( address _owner, address _master ) public PermissionManager(_owner, _master) { // grant here grant('admin', msg.sender, MODIFY_MAP); } // overriding the base function - real check function canModifyMap(address _address) returns (bool) { uint permissions = MODIFY_MAP; return check(_address, permissions) == RestStatus.OK; } }
overriding the base function - real check
function canModifyMap(address _address) returns (bool) { uint permissions = MODIFY_MAP; return check(_address, permissions) == RestStatus.OK; }
5,382,256
// File: openzeppelin-solidity/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol pragma solidity ^0.5.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-solidity/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: openzeppelin-solidity/contracts/drafts/Counters.sol pragma solidity ^0.5.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ 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 current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: openzeppelin-solidity/contracts/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ 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_RECEIVED = 0x150b7a02; // 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(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = 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" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 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, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, 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. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @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) internal returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ 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(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @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 = _ownedTokens[from].length.sub(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). } /** * @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.sub(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; } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol pragma solidity ^0.5.0; contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _tokenURI)); } } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: if all token IDs share a prefix (e.g. if your URIs look like * `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}. * * _Available since v2.5.0._ */ function _setBaseURI(string memory baseURI) internal { _baseURI = baseURI; } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a preffix in {tokenURI} to each token's URI, when * they are non-empty. * * _Available since v2.5.0._ */ function baseURI() external view returns (string memory) { return _baseURI; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol pragma solidity ^0.5.0; /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Strings.sol pragma solidity ^0.5.0; library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } // File: contracts/ERC721Tradable.sol pragma solidity ^0.5.0; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ contract ERC721Tradable is ERC721Full, Ownable { using Strings for string; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) public ERC721Full(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to) public onlyOwner { uint256 newTokenId = _getNextTokenId(); _mint(_to, newTokenId); _incrementTokenId(); } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId() private view returns (uint256) { return _currentTokenId.add(1); } /** * @dev increments the value of _currentTokenId */ function _incrementTokenId() private { _currentTokenId++; } function baseTokenURI() public pure returns (string memory) { return ""; } function tokenURI(uint256 _tokenId) external view returns (string memory) { return Strings.strConcat(baseTokenURI(), Strings.uint2str(_tokenId)); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } } // File: contracts/VoxoDeus.sol pragma solidity ^0.5.0; /** * @title VoxoDeus * Voxodeus - a contract for my non-fungible creatures. */ contract VoxoDeus is ERC721Tradable { // contract Ape is ERC721Tradable, Ownable { constructor(address _proxyRegistryAddress) public ERC721Tradable("VoxoDeus", "VXO", _proxyRegistryAddress) {} function baseTokenURI() public pure returns (string memory) { return "https://api.voxodeus.io/api/voxodeus/"; } function contractURI() public pure returns (string memory) { return "https://api.voxodeus.io/contract/voxodeus"; } }
Internal function to transfer ownership of a given token ID to another address. As opposed to transferFrom, this imposes no restrictions on msg.sender. from current owner of the token to address to receive the ownership of the given token ID tokenId uint256 ID of the token to be transferred/
function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); }
246,124
./partial_match/3/0x518F906CC7aA2188C384dAF1D9F4806FC4Bf0e78/sources/BasicToken.sol
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
5,223,338
./full_match/3/0x3cF8f446865F3b27D40D6d1D919b3F6f4F784054/sources/browser/MasterChef.sol
View function to show all relevant platform info on the frontend
function getAllInfoFor(address _user) external view returns (bool poolActive, uint256[8] memory info) { poolActive = mkbPoolActive; info[0] = blocksUntilLaunch(); info[1] = blocksUntilMkbPoolCanBeActivated(); info[2] = blocksUntilSoftLaunchEnds(); info[3] = mkb.totalSupply(); info[4] = _getMkbPrice(); if (mkbPoolActive) { info[5] = IERC20(mkbPoolAddress).balanceOf(address(mkb)); } info[6] = mkb.balanceOf(_user); }
8,104,103
// 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); } /** * @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; } /** * @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); } /** * @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); } /** * @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); } } } } /** * @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; } } /** * @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); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } /** * @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); } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } /** * @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); } } // 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; } } } abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title FutureArtAAAPasses (VeeFriends Edition) * @author James Zaki * Based on ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ contract FutureArtAAAPasses is ContextMixin, ERC721Enumerable, ERC721Pausable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address immutable proxyRegistryAddress; uint256 immutable NFTLimit = 555; uint256 private _currentTokenId = 0; string private _uri; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress, string memory _URI ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _uri = _URI; _initializeEIP712(_name); } /** * @dev mints one token to each address. Supply limited to NFTLimit. * @param _addresses addresses of future owners of the tokens */ function mintToAddresses( address[] calldata _addresses ) public onlyOwner { uint256 lastId = _currentTokenId + _addresses.length; require(lastId <= NFTLimit, "FutureArtAAAPasses: total tokens must not exceed limit"); for (uint256 i = 0; i < _addresses.length; i++) { uint256 newTokenId = _getNextTokenId(); _mint(_addresses[i], newTokenId); _incrementTokenId(); } } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId() private view returns (uint256) { return _currentTokenId.add(1); } /** * @dev increments the value of _currentTokenId */ function _incrementTokenId() private { _currentTokenId++; } /** * @dev shared uri for nfts */ function tokenURI(uint256 /*_tokenId*/) override public view returns (string memory) { return _uri; } /** * @dev set _uri for all nfts */ function setURI(string memory _newURI) public onlyOwner { _uri = _newURI; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address tokenOwner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(tokenOwner)) == operator) { return true; } return super.isApprovedForAll(tokenOwner, operator); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Pauses all token transfers. */ function pause() public virtual onlyOwner { _pause(); } /** * @dev Unpauses all token transfers. */ function unpause() public virtual onlyOwner { _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } }
shared uri for nfts/
function tokenURI(uint256 /*_tokenId*/) override public view returns (string memory) { return _uri; }
9,911,643
./partial_match/56/0xC65f62d372aA50e99b2A564Ddb418A6bc84Faa15/sources/MeerkatToken.sol
Deposit Staking tokens to FairLaunchToken for MKAT allocation.
function deposit(address _for, uint256 _pid, uint256 _amount) public override { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_for]; if (user.fundedBy != address(0)) require(user.fundedBy == msg.sender, "bad sof"); require(pool.stakeToken != address(0), "deposit: not accept deposit"); updatePool(_pid); if (user.amount > 0) _harvest(_for, _pid); if (user.fundedBy == address(0)) user.fundedBy = msg.sender; IERC20(pool.stakeToken).safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accMkatPerShare).div(1e12); user.bonusDebt = user.amount.mul(pool.accMkatPerShareTilBonusEnd).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
11,075,778
./partial_match/1/0x054D996EEd5e726722c1b8F4D1DD0179f5a06A6c/sources/Delegate.sol
Unset a Trading Rule senderToken address Address of an ERC-20 token the delegate would send signerToken address Address of an ERC-20 token the consumer would send/ using non-zero rule.priceCoef for rule existence check Delete the rule.
function _unsetRule( address senderToken, address signerToken ) internal { if (rules[senderToken][signerToken].priceCoef > 0) { delete rules[senderToken][signerToken]; emit UnsetRule( owner(), senderToken, signerToken ); } }
3,598,630
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import '@openzeppelin/contracts/token/ERC1155/IERC1155.sol'; import {SDaoRegistrar} from '../SDaoRegistrar.sol'; interface IERC1155Minter is IERC1155 { function mint( address to, uint256 id, uint256 amount, bytes memory data ) external; } /** * @title SDaoRegistrarERC1155Generator contract. * @dev Implementation of the {ISDaoRegistrarERC1155Generator}. * A token is minted for each registration. * Only one token is allowed by account. */ abstract contract SDaoRegistrarERC1155Generator is SDaoRegistrar { IERC1155Minter public immutable ERC1155_MINTER; /** * @dev Constructor. * @param erc1155Minter The address of the ERC1155 Minter. */ constructor(IERC1155Minter erc1155Minter) { require( address(erc1155Minter) != address(0), 'SDAO_REGISTRAR_ERC1155_GENERATOR: INVALID_ERC721_ADDRESS' ); ERC1155_MINTER = erc1155Minter; } /** * @dev Hook that is called before any registration. * * It will pass if and only if the balance of the account is zero or the account is the owner. * Balance is computed based on a function which is implemented in the implementation contract. * * @param account The address for which the registration is made. * @param labelHash The hash of the label to register. */ function _beforeRegistration(address account, bytes32 labelHash) internal virtual override { super._beforeRegistration(account, labelHash); require( _balanceOf(account) == 0 || account == owner(), 'SDAO_REGISTRAR_ERC1155_GENERATOR: ALREADY_TOKEN_OWNER' ); } /** * @dev Hook that is called after any registration. * * One ERC1155 token is minted and given to the account. * * @param account The address for which the registration is made. * @param labelHash The hash of the label to register. */ function _afterRegistration(address account, bytes32 labelHash) internal virtual override { super._afterRegistration(account, labelHash); (uint256 id, bytes memory data) = _getToken(account, labelHash); ERC1155_MINTER.mint(account, id, 1, data); } /** * @dev Get token ID and token data. * @param account The address for which the registration is made. * @param labelHash The hash of the label to register. * @return The ID and the data of the token. */ function _getToken(address account, bytes32 labelHash) internal view virtual returns (uint256, bytes memory); /** * @dev Get balance of an address. * @param account The address for which the registration is made. * @return The ID and the data of the token. */ function _balanceOf(address account) internal virtual returns (uint256); }
Hook that is called after any registration. One ERC1155 token is minted and given to the account. account The address for which the registration is made. labelHash The hash of the label to register./
function _afterRegistration(address account, bytes32 labelHash) internal virtual override { super._afterRegistration(account, labelHash); (uint256 id, bytes memory data) = _getToken(account, labelHash); ERC1155_MINTER.mint(account, id, 1, data); }
907,588
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface TokenInterface { function APPROVE44(address, uint256) external; //inject NONSTANDARD NAMING function TRANSFER867(address, uint) external; //inject NONSTANDARD NAMING function TRANSFERFROM416(address, address, uint) external; //inject NONSTANDARD NAMING function DEPOSIT488() external payable; //inject NONSTANDARD NAMING function WITHDRAW102(uint) external; //inject NONSTANDARD NAMING function BALANCEOF737(address) external view returns (uint); //inject NONSTANDARD NAMING function DECIMALS200() external view returns (uint); //inject NONSTANDARD NAMING } interface MemoryInterface { function GETUINT774(uint id) external returns (uint num); //inject NONSTANDARD NAMING function SETUINT548(uint id, uint val) external; //inject NONSTANDARD NAMING } interface EventInterface { function EMITEVENT565(uint connectorType, uint connectorID, bytes32 eventCode, bytes calldata eventData) external; //inject NONSTANDARD NAMING } contract Stores { function GETETHADDR620() internal pure returns (address) { //inject NONSTANDARD NAMING return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address } function GETMEMORYADDR192() internal pure returns (address) { //inject NONSTANDARD NAMING return 0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F; // InstaMemory Address } function GETEVENTADDR446() internal pure returns (address) { //inject NONSTANDARD NAMING return 0x2af7ea6Cb911035f3eb1ED895Cb6692C39ecbA97; // InstaEvent Address } function GETUINT774(uint getId, uint val) internal returns (uint returnVal) { //inject NONSTANDARD NAMING returnVal = getId == 0 ? val : MemoryInterface(GETMEMORYADDR192()).GETUINT774(getId); } function SETUINT548(uint setId, uint val) virtual internal { //inject NONSTANDARD NAMING if (setId != 0) MemoryInterface(GETMEMORYADDR192()).SETUINT548(setId, val); } function EMITEVENT565(bytes32 eventCode, bytes memory eventData) virtual internal { //inject NONSTANDARD NAMING (uint model, uint id) = CONNECTORID65(); EventInterface(GETEVENTADDR446()).EMITEVENT565(model, id, eventCode, eventData); } function CONNECTORID65() public view returns(uint model, uint id) { //inject NONSTANDARD NAMING (model, id) = (1, 38); } } library SafeMath { function ADD435(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB700(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB700(a, b, "SafeMath: subtraction overflow"); } function SUB700(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 MUL278(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 DIV204(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV204(a, b, "SafeMath: division by zero"); } function DIV204(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD700(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD700(a, b, "SafeMath: modulo by zero"); } function MOD700(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract DSMath { uint constant wad945 = 10 ** 18; //inject NONSTANDARD NAMING uint constant ray928 = 10 ** 27; //inject NONSTANDARD NAMING function ADD435(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = SafeMath.ADD435(x, y); } function SUB700(uint x, uint y) internal virtual pure returns (uint z) { //inject NONSTANDARD NAMING z = SafeMath.SUB700(x, y); } function MUL278(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = SafeMath.MUL278(x, y); } function DIV204(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = SafeMath.DIV204(x, y); } function WMUL242(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = SafeMath.ADD435(SafeMath.MUL278(x, y), wad945 / 2) / wad945; } function WDIV461(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = SafeMath.ADD435(SafeMath.MUL278(x, wad945), y / 2) / y; } function RDIV516(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = SafeMath.ADD435(SafeMath.MUL278(x, ray928), y / 2) / y; } function RMUL757(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = SafeMath.ADD435(SafeMath.MUL278(x, y), ray928 / 2) / ray928; } } interface OneInchInterace { function SWAP155( //inject NONSTANDARD NAMING TokenInterface fromToken, TokenInterface toToken, uint256 fromTokenAmount, uint256 minReturnAmount, uint256 guaranteedAmount, address payable referrer, address[] calldata callAddresses, bytes calldata callDataConcat, uint256[] calldata starts, uint256[] calldata gasLimitsAndValues ) external payable returns (uint256 returnAmount); } interface OneProtoInterface { function SWAPWITHREFERRAL361( //inject NONSTANDARD NAMING TokenInterface fromToken, TokenInterface destToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 flags, // See contants in IOneSplit.sol address referral, uint256 feePercent ) external payable returns(uint256); function SWAPWITHREFERRALMULTI690( //inject NONSTANDARD NAMING TokenInterface[] calldata tokens, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256[] calldata flags, address referral, uint256 feePercent ) external payable returns(uint256 returnAmount); function GETEXPECTEDRETURN579( //inject NONSTANDARD NAMING TokenInterface fromToken, TokenInterface destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns( uint256 returnAmount, uint256[] memory distribution ); } interface OneProtoMappingInterface { function ONEPROTOADDRESS398() external view returns(address); //inject NONSTANDARD NAMING } contract OneHelpers is Stores, DSMath { function GETONEPROTOMAPPINGADDRESS394() internal pure returns (address payable) { //inject NONSTANDARD NAMING return 0x8d0287AFa7755BB5f2eFe686AA8d4F0A7BC4AE7F; } function GETONEPROTOADDRESS431() internal view returns (address payable) { //inject NONSTANDARD NAMING return payable(OneProtoMappingInterface(GETONEPROTOMAPPINGADDRESS394()).ONEPROTOADDRESS398()); } function GETONEINCHADDRESS518() internal pure returns (address) { //inject NONSTANDARD NAMING return 0x11111254369792b2Ca5d084aB5eEA397cA8fa48B; } function GETONEINCHTOKENTAKER586() internal pure returns (address payable) { //inject NONSTANDARD NAMING return 0xE4C9194962532fEB467DCe8b3d42419641c6eD2E; } function GETONEINCHSIG889() internal pure returns (bytes4) { //inject NONSTANDARD NAMING return 0xf88309d7; } function GETREFERRALADDR889() internal pure returns (address) { //inject NONSTANDARD NAMING return 0xa7615CD307F323172331865181DC8b80a2834324; } function CONVERT18TODEC395(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { //inject NONSTANDARD NAMING amt = (_amt / 10 ** (18 - _dec)); } function CONVERTTO18179(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { //inject NONSTANDARD NAMING amt = MUL278(_amt, 10 ** (18 - _dec)); } function GETTOKENBAL438(TokenInterface token) internal view returns(uint _amt) { //inject NONSTANDARD NAMING _amt = address(token) == GETETHADDR620() ? address(this).balance : token.BALANCEOF737(address(this)); } function GETTOKENSDEC172(TokenInterface buyAddr, TokenInterface sellAddr) internal view returns(uint buyDec, uint sellDec) { //inject NONSTANDARD NAMING buyDec = address(buyAddr) == GETETHADDR620() ? 18 : buyAddr.DECIMALS200(); sellDec = address(sellAddr) == GETETHADDR620() ? 18 : sellAddr.DECIMALS200(); } function GETSLIPPAGEAMT247( //inject NONSTANDARD NAMING TokenInterface _buyAddr, TokenInterface _sellAddr, uint _sellAmt, uint unitAmt ) internal view returns(uint _slippageAmt) { (uint _buyDec, uint _sellDec) = GETTOKENSDEC172(_buyAddr, _sellAddr); uint _sellAmt18 = CONVERTTO18179(_sellDec, _sellAmt); _slippageAmt = CONVERT18TODEC395(_buyDec, WMUL242(unitAmt, _sellAmt18)); } function CONVERTTOTOKENINTERFACE157(address[] memory tokens) internal pure returns(TokenInterface[] memory) { //inject NONSTANDARD NAMING TokenInterface[] memory _tokens = new TokenInterface[](tokens.length); for (uint i = 0; i < tokens.length; i++) { _tokens[i] = TokenInterface(tokens[i]); } return _tokens; } } contract OneProtoResolver is OneHelpers { struct OneProtoData { TokenInterface sellToken; TokenInterface buyToken; uint _sellAmt; uint _buyAmt; uint unitAmt; uint[] distribution; uint disableDexes; } function ONEPROTOSWAP794( //inject NONSTANDARD NAMING OneProtoInterface oneProtoContract, OneProtoData memory oneProtoData ) internal returns (uint buyAmt) { TokenInterface _sellAddr = oneProtoData.sellToken; TokenInterface _buyAddr = oneProtoData.buyToken; uint _sellAmt = oneProtoData._sellAmt; uint _slippageAmt = GETSLIPPAGEAMT247(_buyAddr, _sellAddr, _sellAmt, oneProtoData.unitAmt); uint ethAmt; if (address(_sellAddr) == GETETHADDR620()) { ethAmt = _sellAmt; } else { _sellAddr.APPROVE44(address(oneProtoContract), _sellAmt); } uint initalBal = GETTOKENBAL438(_buyAddr); oneProtoContract.SWAPWITHREFERRAL361.value(ethAmt)( _sellAddr, _buyAddr, _sellAmt, _slippageAmt, oneProtoData.distribution, oneProtoData.disableDexes, GETREFERRALADDR889(), 0 ); uint finalBal = GETTOKENBAL438(_buyAddr); buyAmt = SUB700(finalBal, initalBal); require(_slippageAmt <= buyAmt, "Too much slippage"); } struct OneProtoMultiData { address[] tokens; TokenInterface sellToken; TokenInterface buyToken; uint _sellAmt; uint _buyAmt; uint unitAmt; uint[] distribution; uint[] disableDexes; } function ONEPROTOSWAPMULTI285(OneProtoMultiData memory oneProtoData) internal returns (uint buyAmt) { //inject NONSTANDARD NAMING TokenInterface _sellAddr = oneProtoData.sellToken; TokenInterface _buyAddr = oneProtoData.buyToken; uint _sellAmt = oneProtoData._sellAmt; uint _slippageAmt = GETSLIPPAGEAMT247(_buyAddr, _sellAddr, _sellAmt, oneProtoData.unitAmt); OneProtoInterface oneSplitContract = OneProtoInterface(GETONEPROTOADDRESS431()); uint ethAmt; if (address(_sellAddr) == GETETHADDR620()) { ethAmt = _sellAmt; } else { _sellAddr.APPROVE44(address(oneSplitContract), _sellAmt); } uint initalBal = GETTOKENBAL438(_buyAddr); oneSplitContract.SWAPWITHREFERRALMULTI690.value(ethAmt)( CONVERTTOTOKENINTERFACE157(oneProtoData.tokens), _sellAmt, _slippageAmt, oneProtoData.distribution, oneProtoData.disableDexes, GETREFERRALADDR889(), 0 ); uint finalBal = GETTOKENBAL438(_buyAddr); buyAmt = SUB700(finalBal, initalBal); require(_slippageAmt <= buyAmt, "Too much slippage"); } } contract OneInchResolver is OneProtoResolver { function CHECKONEINCHSIG202(bytes memory callData) internal pure returns(bool isOk) { //inject NONSTANDARD NAMING bytes memory _data = callData; bytes4 sig; // solium-disable-next-line security/no-inline-assembly assembly { sig := mload(add(_data, 32)) } isOk = sig == GETONEINCHSIG889(); } struct OneInchData { TokenInterface sellToken; TokenInterface buyToken; uint _sellAmt; uint _buyAmt; uint unitAmt; bytes callData; } function ONEINCHSWAP719( //inject NONSTANDARD NAMING OneInchData memory oneInchData, uint ethAmt ) internal returns (uint buyAmt) { TokenInterface buyToken = oneInchData.buyToken; (uint _buyDec, uint _sellDec) = GETTOKENSDEC172(buyToken, oneInchData.sellToken); uint _sellAmt18 = CONVERTTO18179(_sellDec, oneInchData._sellAmt); uint _slippageAmt = CONVERT18TODEC395(_buyDec, WMUL242(oneInchData.unitAmt, _sellAmt18)); uint initalBal = GETTOKENBAL438(buyToken); // solium-disable-next-line security/no-call-value (bool success, ) = address(GETONEINCHADDRESS518()).call.value(ethAmt)(oneInchData.callData); if (!success) revert("1Inch-swap-failed"); uint finalBal = GETTOKENBAL438(buyToken); buyAmt = SUB700(finalBal, initalBal); require(_slippageAmt <= buyAmt, "Too much slippage"); } } contract OneProtoEventResolver is OneInchResolver { event LOGSELL607( //inject NONSTANDARD NAMING address indexed buyToken, address indexed sellToken, uint256 buyAmt, uint256 sellAmt, uint256 getId, uint256 setId ); function EMITLOGSELL642( //inject NONSTANDARD NAMING OneProtoData memory oneProtoData, uint256 getId, uint256 setId ) internal { bytes32 _eventCode; bytes memory _eventParam; emit LOGSELL607( address(oneProtoData.buyToken), address(oneProtoData.sellToken), oneProtoData._buyAmt, oneProtoData._sellAmt, getId, setId ); _eventCode = keccak256("LogSell(address,address,uint256,uint256,uint256,uint256)"); _eventParam = abi.encode( address(oneProtoData.buyToken), address(oneProtoData.sellToken), oneProtoData._buyAmt, oneProtoData._sellAmt, getId, setId ); EMITEVENT565(_eventCode, _eventParam); } event LOGSELLTWO221( //inject NONSTANDARD NAMING address indexed buyToken, address indexed sellToken, uint256 buyAmt, uint256 sellAmt, uint256 getId, uint256 setId ); function EMITLOGSELLTWO898( //inject NONSTANDARD NAMING OneProtoData memory oneProtoData, uint256 getId, uint256 setId ) internal { bytes32 _eventCode; bytes memory _eventParam; emit LOGSELLTWO221( address(oneProtoData.buyToken), address(oneProtoData.sellToken), oneProtoData._buyAmt, oneProtoData._sellAmt, getId, setId ); _eventCode = keccak256("LogSellTwo(address,address,uint256,uint256,uint256,uint256)"); _eventParam = abi.encode( address(oneProtoData.buyToken), address(oneProtoData.sellToken), oneProtoData._buyAmt, oneProtoData._sellAmt, getId, setId ); EMITEVENT565(_eventCode, _eventParam); } event LOGSELLMULTI397( //inject NONSTANDARD NAMING address[] tokens, address indexed buyToken, address indexed sellToken, uint256 buyAmt, uint256 sellAmt, uint256 getId, uint256 setId ); function EMITLOGSELLMULTI751( //inject NONSTANDARD NAMING OneProtoMultiData memory oneProtoData, uint256 getId, uint256 setId ) internal { bytes32 _eventCode; bytes memory _eventParam; emit LOGSELLMULTI397( oneProtoData.tokens, address(oneProtoData.buyToken), address(oneProtoData.sellToken), oneProtoData._buyAmt, oneProtoData._sellAmt, getId, setId ); _eventCode = keccak256("LogSellMulti(address[],address,address,uint256,uint256,uint256,uint256)"); _eventParam = abi.encode( oneProtoData.tokens, address(oneProtoData.buyToken), address(oneProtoData.sellToken), oneProtoData._buyAmt, oneProtoData._sellAmt, getId, setId ); EMITEVENT565(_eventCode, _eventParam); } } contract OneInchEventResolver is OneProtoEventResolver { event LOGSELLTHREE365( //inject NONSTANDARD NAMING address indexed buyToken, address indexed sellToken, uint256 buyAmt, uint256 sellAmt, uint256 getId, uint256 setId ); function EMITLOGSELLTHREE379( //inject NONSTANDARD NAMING OneInchData memory oneInchData, uint256 setId ) internal { bytes32 _eventCode; bytes memory _eventParam; emit LOGSELLTHREE365( address(oneInchData.buyToken), address(oneInchData.sellToken), oneInchData._buyAmt, oneInchData._sellAmt, 0, setId ); _eventCode = keccak256("LogSellThree(address,address,uint256,uint256,uint256,uint256)"); _eventParam = abi.encode( address(oneInchData.buyToken), address(oneInchData.sellToken), oneInchData._buyAmt, oneInchData._sellAmt, 0, setId ); EMITEVENT565(_eventCode, _eventParam); } } contract OneProtoResolverHelpers is OneInchEventResolver { function _SELL499( //inject NONSTANDARD NAMING OneProtoData memory oneProtoData, uint256 getId, uint256 setId ) internal { uint _sellAmt = GETUINT774(getId, oneProtoData._sellAmt); oneProtoData._sellAmt = _sellAmt == uint(-1) ? GETTOKENBAL438(oneProtoData.sellToken) : _sellAmt; OneProtoInterface oneProtoContract = OneProtoInterface(GETONEPROTOADDRESS431()); (, oneProtoData.distribution) = oneProtoContract.GETEXPECTEDRETURN579( oneProtoData.sellToken, oneProtoData.buyToken, oneProtoData._sellAmt, 5, 0 ); oneProtoData._buyAmt = ONEPROTOSWAP794( oneProtoContract, oneProtoData ); SETUINT548(setId, oneProtoData._buyAmt); EMITLOGSELL642(oneProtoData, getId, setId); } function _SELLTWO817( //inject NONSTANDARD NAMING OneProtoData memory oneProtoData, uint getId, uint setId ) internal { uint _sellAmt = GETUINT774(getId, oneProtoData._sellAmt); oneProtoData._sellAmt = _sellAmt == uint(-1) ? GETTOKENBAL438(oneProtoData.sellToken) : _sellAmt; oneProtoData._buyAmt = ONEPROTOSWAP794( OneProtoInterface(GETONEPROTOADDRESS431()), oneProtoData ); SETUINT548(setId, oneProtoData._buyAmt); EMITLOGSELLTWO898(oneProtoData, getId, setId); } function _SELLMULTI27( //inject NONSTANDARD NAMING OneProtoMultiData memory oneProtoData, uint getId, uint setId ) internal { uint _sellAmt = GETUINT774(getId, oneProtoData._sellAmt); oneProtoData._sellAmt = _sellAmt == uint(-1) ? GETTOKENBAL438(oneProtoData.sellToken) : _sellAmt; oneProtoData._buyAmt = ONEPROTOSWAPMULTI285(oneProtoData); SETUINT548(setId, oneProtoData._buyAmt); EMITLOGSELLMULTI751(oneProtoData, getId, setId); } } contract OneInchResolverHelpers is OneProtoResolverHelpers { function _SELLTHREE9( //inject NONSTANDARD NAMING OneInchData memory oneInchData, uint setId ) internal { TokenInterface _sellAddr = oneInchData.sellToken; uint ethAmt; if (address(_sellAddr) == GETETHADDR620()) { ethAmt = oneInchData._sellAmt; } else { TokenInterface(_sellAddr).APPROVE44(GETONEINCHTOKENTAKER586(), oneInchData._sellAmt); } require(CHECKONEINCHSIG202(oneInchData.callData), "Not-swap-function"); oneInchData._buyAmt = ONEINCHSWAP719(oneInchData, ethAmt); SETUINT548(setId, oneInchData._buyAmt); EMITLOGSELLTHREE379(oneInchData, setId); } } contract OneProto is OneInchResolverHelpers { function SELL474( //inject NONSTANDARD NAMING address buyAddr, address sellAddr, uint sellAmt, uint unitAmt, uint getId, uint setId ) external payable { OneProtoData memory oneProtoData = OneProtoData({ buyToken: TokenInterface(buyAddr), sellToken: TokenInterface(sellAddr), _sellAmt: sellAmt, unitAmt: unitAmt, distribution: new uint[](0), _buyAmt: 0, disableDexes: 0 }); _SELL499(oneProtoData, getId, setId); } function SELLTWO782( //inject NONSTANDARD NAMING address buyAddr, address sellAddr, uint sellAmt, uint unitAmt, uint[] calldata distribution, uint disableDexes, uint getId, uint setId ) external payable { OneProtoData memory oneProtoData = OneProtoData({ buyToken: TokenInterface(buyAddr), sellToken: TokenInterface(sellAddr), _sellAmt: sellAmt, unitAmt: unitAmt, distribution: distribution, disableDexes: disableDexes, _buyAmt: 0 }); _SELLTWO817(oneProtoData, getId, setId); } function SELLMULTI899( //inject NONSTANDARD NAMING address[] calldata tokens, uint sellAmt, uint unitAmt, uint[] calldata distribution, uint[] calldata disableDexes, uint getId, uint setId ) external payable { OneProtoMultiData memory oneProtoData = OneProtoMultiData({ tokens: tokens, buyToken: TokenInterface(address(tokens[tokens.length - 1])), sellToken: TokenInterface(address(tokens[0])), unitAmt: unitAmt, distribution: distribution, disableDexes: disableDexes, _sellAmt: sellAmt, _buyAmt: 0 }); _SELLMULTI27(oneProtoData, getId, setId); } } contract OneInch is OneProto { function SELLTHREE242( //inject NONSTANDARD NAMING address buyAddr, address sellAddr, uint sellAmt, uint unitAmt, bytes calldata callData, uint setId ) external payable { OneInchData memory oneInchData = OneInchData({ buyToken: TokenInterface(buyAddr), sellToken: TokenInterface(sellAddr), unitAmt: unitAmt, callData: callData, _sellAmt: sellAmt, _buyAmt: 0 }); _SELLTHREE9(oneInchData, setId); } } contract ConnectOne is OneInch { string public name = "1inch-1proto-v1"; }
inject NONSTANDARD NAMING
function EMITEVENT565(bytes32 eventCode, bytes memory eventData) virtual internal {
5,365,079
pragma solidity >=0.4.2; contract Election { struct Candidate { uint256 id; string name; uint256 voteCount; } // Store candidates mapping(uint256 => Candidate) public candidates; // Store and track accounts that already voted mapping(address => bool) public voters; // Voted event event votedEvent(uint256 indexed _candidateId); uint256 public candidatesCount; constructor() public { addCandidate("Elizabeth Warren"); addCandidate("Joe Biden"); addCandidate("Andrew Yang"); addCandidate("Pete Buttigiege"); addCandidate("Bernie Sanders"); addCandidate("Cory Booker"); } function addCandidate(string memory _name) private { candidatesCount++; candidates[candidatesCount] = Candidate(candidatesCount, _name, 0); } function vote(uint256 _candidateId) public { // Check that voter hasn't already voted require(!voters[msg.sender], "Already Voted sorry"); // Check candidate being voted or is valid require( _candidateId > 0 && _candidateId <= candidatesCount, "Candidate is invalid" ); // record that voter has voted voters[msg.sender] = true; // update candidate vote count candidates[_candidateId].voteCount++; // Trigger the voted even emit votedEvent(_candidateId); } }
Check that voter hasn't already voted Check candidate being voted or is valid record that voter has voted update candidate vote count Trigger the voted even
function vote(uint256 _candidateId) public { require(!voters[msg.sender], "Already Voted sorry"); require( _candidateId > 0 && _candidateId <= candidatesCount, "Candidate is invalid" ); voters[msg.sender] = true; candidates[_candidateId].voteCount++; emit votedEvent(_candidateId); }
1,759,844
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 _ADDBATCHTOOWNER461(address to, Batch memory batch) private {
6,431,921
// SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1TokenGateway } from "../../../iOVM/bridge/tokens/iOVM_L1TokenGateway.sol"; import { Abs_L1TokenGateway } from "./Abs_L1TokenGateway.sol"; import { iOVM_ERC20 } from "../../../iOVM/predeploys/iOVM_ERC20.sol"; import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_AddressManager } from "../../../libraries/resolver/Lib_AddressManager.sol"; /** * @title OVM_L1ERC20Gateway * @dev The L1 ERC20 Gateway is a contract which stores deposited L1 funds that are in use on L2. * It synchronizes a corresponding L2 ERC20 Gateway, informing it of deposits, and listening to it * for newly finalized withdrawals. * * NOTE: This contract extends Abs_L1TokenGateway, which is where we * takes care of most of the initialization and the cross-chain logic. * If you are looking to implement your own deposit/withdrawal contracts, you * may also want to extend the abstract contract in a similar manner. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1ERC20Gateway is Abs_L1TokenGateway, Lib_AddressResolver { /******************************** * External Contract References * ********************************/ iOVM_ERC20 public l1ERC20; /*************** * Constructor * ***************/ constructor() Abs_L1TokenGateway(address(0), address(0)) Lib_AddressResolver(address(0)) public {} /****************** * Initialization * ******************/ /** * @param _libAddressManager Address manager for this OE deployment * @param _l2DepositedERC20 L2 ERC20 implementation of iOVM_DepositedToken * @param _l1ERC20 L1 ERC20 Contract */ function initialize( address _libAddressManager, address _l2DepositedERC20, address _l1ERC20 ) public { require(libAddressManager == Lib_AddressManager(0), "Contract has already been initialized."); libAddressManager = Lib_AddressManager(_libAddressManager); l2DepositedToken = _l2DepositedERC20; l1ERC20 = iOVM_ERC20(_l1ERC20); messenger = resolve("Proxy__OVM_L1CrossDomainMessenger"); } /************** * Accounting * **************/ function depositByChainId(uint256 _chainId, uint256 _amount) external override { _initiateDepositByChainId(_chainId, msg.sender, msg.sender, _amount); } function depositToByChainId( uint256 _chainId, address _to, uint256 _amount ) external override { _initiateDepositByChainId(_chainId, msg.sender, _to, _amount); } /** * @dev When a deposit is initiated on L1, the L1 Gateway * transfers the funds to itself for future withdrawals * * @param _from L1 address ETH is being deposited from * param _to L2 address that the ETH is being deposited to * @param _amount Amount of ERC20 to send */ function _handleInitiateDeposit( address _from, address, // _to, uint256 _amount ) internal override { // Hold on to the newly deposited funds l1ERC20.transferFrom( _from, address(this), _amount ); } /** * @dev When a withdrawal is finalized on L1, the L1 Gateway * transfers the funds to the withdrawer * * @param _to L1 address that the ERC20 is being withdrawn to * @param _amount Amount of ERC20 to send */ function _handleFinalizeWithdrawal( address _to, uint _amount ) internal override { // Transfer withdrawn funds out to withdrawer l1ERC20.transfer(_to, _amount); } }
Accounting /
function depositByChainId(uint256 _chainId, uint256 _amount) external override { _initiateDepositByChainId(_chainId, msg.sender, msg.sender, _amount); }
7,278,617
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* A contract can have multiple functions of the same name but with different parameter types. This process is called “overloading” */ contract Overloading { /// @param status true function getStatus(bool status) public pure returns (bool) { return status; } /// @param status 1 function getStatus(uint1 status) public pure returns (uint1) { return status; } /// @param status 'true' function getStatus(bytes8 status) public pure returns (bytes8) { return status; } }
status 'true'
function getStatus(bytes8 status) public pure returns (bytes8) { return status; }
936,059
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //IERC721MultiClass interface import "./../interfaces/IERC721TransferFees.sol"; /** * @dev Abstract extension of ERC721TransferFees that attaches royalty fees */ abstract contract ERC721TransferFees is IERC721TransferFees { //10000 means 100.00% uint256 private constant TOTAL_ALLOWABLE_FEES = 10000; //mapping of `classId` to total fees (could be problematic if not synced) uint256 private _fees; //mapping of `recipient` to fee mapping(address => uint256) private _fee; //index mapping of `classId` to recipients (so we can loop the map) address[] private _recipients; /** * @dev Returns the fee of a `recipient` */ function feeOf(address recipient) public view override returns(uint256) { return _fee[recipient]; } /** * @dev Returns total fees */ function totalFees() public view override returns(uint256) { return _fees; } /** * @dev Sets a fee that will be collected during the exchange method */ function _allocateFee(address recipient, uint256 fee) internal virtual { require(fee > 0, "ERC721TransferFees: Fee should be more than 0"); //if no recipient if (_fee[recipient] == 0) { //add recipient _recipients.push(recipient); //map fee _fee[recipient] = fee; //add to total fee _fees += fee; //else there"s already an existing recipient } else { //remove old fee from total fee _fees -= _fee[recipient]; //map fee _fee[recipient] = fee; //add to total fee _fees += fee; } //safe check require( _fees <= TOTAL_ALLOWABLE_FEES, "ERC721TransferFees: Exceeds allowable fees" ); } /** * @dev Removes a fee */ function _deallocateFee(address recipient) internal virtual { //this is for the benefit of the sender so they //dont have to pay gas on things that dont matter require(_fee[recipient] != 0, "ERC721TransferFees: Recipient has no fees"); //deduct total fees _fees -= _fee[recipient]; //remove fees from the map delete _fee[recipient]; //Tricky logic to remove an element from an array... //if there are at least 2 elements in the array, if (_recipients.length > 1) { //find the recipient for (uint i = 0; i < _recipients.length; i++) { if(_recipients[i] == recipient) { //move the last element to the deleted element uint last = _recipients.length - 1; _recipients[i] = _recipients[last]; break; } } } //either way remove the last element _recipients.pop(); } /** * @dev Pays the amount to the recipients */ function _escrowFees(uint256 amount) internal virtual returns(uint256) { //placeholder for recipient in the loop address recipient; //release payments to recipients for (uint i = 0; i < _recipients.length; i++) { //get the recipient recipient = _recipients[i]; // (10 eth * 2000) / 10000 = payable(recipient).transfer( (amount * _fee[recipient]) / TOTAL_ALLOWABLE_FEES ); } //determine the remaining fee percent uint256 remainingFee = TOTAL_ALLOWABLE_FEES - _fees; //return the remainder amount return (amount * remainingFee) / TOTAL_ALLOWABLE_FEES; } }
Returns total fees/
function totalFees() public view override returns(uint256) { return _fees; }
5,373,142
//SPDX-License-Identifier: Unlicense pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract Pixels is ERC721 { uint256 public constant TOP_PRICE = 1e16; uint256 public constant MEDIUM_PRICE = 1e15; uint256 public constant LOW_PRICE = 5e14; uint32 public constant MAX_PROMOTIONAL_AREAS_SIZE = 100000; uint32[4] public MEDIUM; uint32[4] public TOP; uint32 public width = 1000; uint32 public height = 1000; //percentage with 10000 precision uint32 public fee; address creator; string public baseURI; uint32 public promotionalBought; struct Area { uint32[4] rect; //0 - X , 1- Y ,2 - width, 3 - height string ipfs; uint64 mintedAtBlock; } struct Sale { uint128 price; uint128 end; //end of sale timestamp } Area[] public areas; mapping(uint256 => Sale) public forSale; //tokenId -> Sale mapping(bytes32 => uint256) public commits; //commitment hash -> commit block address private vault; constructor( string memory _baseuri, address _vault, uint32 _medAreaSize, uint32 _topAreaSize ) ERC721("MillionPixelsGallery", "MPG") { creator = _vault; width = 1000; height = 1000; vault = _vault; fee = 375; //3.75 % baseURI = _baseuri; MEDIUM = [ width / 2 - _medAreaSize / 2, height / 2 - _medAreaSize / 2, _medAreaSize, _medAreaSize ]; TOP = [ width / 2 - _topAreaSize / 2, height / 2 - _topAreaSize / 2, _topAreaSize, _topAreaSize ]; } function _baseURI() internal view override returns (string memory) { return baseURI; } /** * @dev returns the rect of a token */ function getBounds(uint256 id) public view returns (uint32[4] memory) { return areas[id].rect; } /** * @dev returns areas length */ function getAreasCount() public view returns (uint256) { return areas.length; } /** * @dev given a rectangle, returns the cost in ETH */ function pixelsCost(uint32[4] memory area) public view returns (uint256) { uint256 topArea = uint256(overlap(area, TOP)); uint256 medArea = uint256(overlap(area, MEDIUM)); uint256 regular = uint256(area[2] * area[3]); uint256 cost = topArea * TOP_PRICE + ((medArea - topArea) * MEDIUM_PRICE) + ((regular - medArea) * LOW_PRICE); return cost; } /** * @dev given a rectangle checks if it does not intersect with existing Areas */ function isAreaAvailable(uint32[4] memory area) external view returns (uint256, bool) { require(area[0] + area[2] <= width && area[1] + area[3] <= height); for (uint256 i = 0; i < areas.length; i++) { if (_isIntersecting(areas[i].rect, area)) return (i, false); } return (0, true); } /** * @dev user must call this first before calling buyPixels * @param areaHash keccak256(rect:uint[4], commitNonce:uint, publickey:address) */ function commitToPixels(bytes32 areaHash) external { require(commits[areaHash] == 0, "commit already set"); commits[areaHash] = block.number; } /** * @dev generate a new NFT for unoccupied pixels * user must first send a commitment to buy that area (commitment=hash(area,ipfs,public address)) * @param area rectangle to generate NFT for * @param ipfs the ipfs hash containing display data for the NFT */ function buyPixels( uint32[4] memory area, uint256 commitNonce, string calldata ipfs ) external payable { require( area[0] + area[2] <= width && area[1] + area[3] <= height, "out of bounds" ); _checkCommit(area, commitNonce, _msgSender()); uint256 cost = _msgSender() == creator ? 0 : pixelsCost(area); require(cost <= msg.value, "Pixels: invalid payment"); if (_msgSender() == creator) { promotionalBought += area[2] * area[3]; require( promotionalBought <= MAX_PROMOTIONAL_AREAS_SIZE, "promotional areas exceeds limit" ); } Area memory bought; bought.rect = area; bought.mintedAtBlock = uint64(block.number); bought.ipfs = ipfs; areas.push(bought); _mint(_msgSender(), areas.length - 1); payable(vault).transfer(msg.value); } /** * @dev owner can put his NFT for sale * @param id token to sell * @param price price in eth(wei) * @param duration number of days sale is open for */ function sell( uint256 id, uint128 price, uint8 duration ) external { require(ERC721.ownerOf(id) == _msgSender(), "only owner can sell"); Sale storage r = forSale[id]; r.price = price; r.end = uint128(block.timestamp + duration * 1 days); } /** * @dev check if a token is for sale */ function isForSale(uint256 id) public view returns (bool) { Sale memory r = forSale[id]; return r.price > 0 && r.end > block.timestamp; } /** * @dev buy an area that is for sale * @param id token to buy * @param ipfsHash new content to attach to the bought NFT */ function buy(uint256 id, string calldata ipfsHash) external payable { Sale memory sale = forSale[id]; require(isForSale(id), "not for sale"); require(msg.value >= sale.price, "payment too low"); uint256 resellFee = (sale.price * fee) / 10000; areas[id].ipfs = ipfsHash; delete forSale[id]; payable(ERC721.ownerOf(id)).transfer(msg.value - resellFee); payable(vault).transfer(resellFee); _transfer(ERC721.ownerOf(id), _msgSender(), id); } /** * @dev set a new ipfs hash for token */ function setIPFSHash(uint256 id, string calldata ipfsHash) external { require(ERC721.ownerOf(id) == _msgSender(), "only owner can set ipfs"); areas[id].ipfs = ipfsHash; } function _isIntersecting(uint32[4] memory obj1, uint32[4] memory obj2) internal pure returns (bool) { // If one rectangle is on left side of other if (obj1[0] >= obj2[0] + obj2[2] || obj2[0] >= obj1[0] + obj1[2]) { return false; } // If one rectangle is above other if (obj1[1] >= obj2[1] + obj2[3] || obj2[1] >= obj1[1] + obj1[3]) { return false; } return true; } function overlap(uint32[4] memory obj1, uint32[4] memory obj2) public pure returns (uint32) { int32 x_overlap = _max( 0, _min(int32(obj1[0] + obj1[2]), int32(obj2[0] + obj2[2])) - _max(int32(obj1[0]), int32(obj2[0])) ); int32 y_overlap = _max( 0, _min(int32(obj1[1] + obj1[3]), int32(obj2[1] + obj2[3])) - _max(int32(obj1[1]), int32(obj2[1])) ); return uint32(x_overlap * y_overlap); } function _max(int32 a, int32 b) internal pure returns (int32) { return a >= b ? a : b; } function _min(int32 a, int32 b) internal pure returns (int32) { return a <= b ? a : b; } function _checkCommit( uint32[4] memory area, uint256 nonce, address buyer ) internal view { //check that area+ipfs+nonce hash = areaHash bytes32 areaHash = keccak256(abi.encodePacked(area, nonce, buyer)); uint256 atBlock = commits[areaHash]; require(atBlock > 0, "commit not set"); require(atBlock < block.number, "commit at current block"); if (areas.length == 0) return; //check that no areas bought after commit intersect for (uint256 i = areas.length - 1; i >= 0; i--) { //no need to check further back, only areas bought after commit if (areas[i].mintedAtBlock < atBlock) { break; } require( _isIntersecting(areas[i].rect, area) == false, "buy failed. intersection found" ); } } function removeFraud( uint256[] calldata fraudIndex, uint256[] calldata originalIndex ) external { for (uint256 i = 0; i < fraudIndex.length; i++) { require( areas[fraudIndex[i]].mintedAtBlock > areas[originalIndex[i]].mintedAtBlock && _isIntersecting( areas[fraudIndex[i]].rect, areas[originalIndex[i]].rect ), "not newer or not overlapping" ); delete areas[fraudIndex[i]]; delete forSale[fraudIndex[i]]; _burn(fraudIndex[i]); } } function setCreator(address _creator) external { require(creator == _msgSender(), "only creator can set new creator"); creator = _creator; } function setVault(address _vault) external { require(creator == _msgSender(), "only creator can set new vault"); vault = _vault; } function setFee(uint32 _fee) external { require(creator == _msgSender(), "only creator can set new fee"); require(_fee < fee, "can only lower fee"); fee = _fee; } function setBaseURI(string memory _baseuri) external { require(creator == _msgSender(), "only creator can set new baseURI"); baseURI = _baseuri; } } // 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; 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); }
owner can put his NFT for sale id token to sell price price in eth(wei) duration number of days sale is open for/
function sell( uint256 id, uint128 price, uint8 duration ) external { require(ERC721.ownerOf(id) == _msgSender(), "only owner can sell"); Sale storage r = forSale[id]; r.price = price; r.end = uint128(block.timestamp + duration * 1 days); }
463,685
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false struct Insurance { address owner; bytes32 key; uint256 amount; } struct Airline { //Struct to classify an airline and hold relevant info string name; address account; bool isRegistered; bool isAuthorized; bool operationalVote; } //constant M refers to number of airlines needed to use multi-party consensus uint256 private changeOperatingStatusVotes = 0; uint statusVotes; uint256 private authorizedAirlineCount = 0; mapping (address => mapping(address => uint8)) private multiCalls; address[] multiCallsArray = new address[](0); //array of addresses that have called the registerFlight function mapping(address => uint256) funds; // Mapping to store the funds contributed by the airline. The minnimum contribution to get authorized is 10 ether mapping(address => Airline) public airlines; // Mapping for storing employees. Question: Does this contract have to inheret from the app contract in order to use a mapping that maps to an Airline type? (airline type is stored in the app contract, maybe this will have to change) mapping(address => uint256) private authorizedAirlines; // Mapping for airlines authorized mapping(address => uint8) authorizedCaller; //mapping that stores the app contract addresses that //are authorized to call the data contract. If authorized, the mapping[address] //should equal 1 Insurance[] private insurance; mapping(address => uint256) private credit; mapping(address => uint256) private voteCounter; mapping(address => bool) private authorizedCallers; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AuthorizedCaller(address caller); event DeAuthorizedCaller(address caller); event Bought(address buyer, bytes32 flightKey, uint256 amount); event Creditted(bytes32 flightKey); event Paid(address insuree, uint256 amount); /** * Event fired when a new Airline is registered * "indexed" keyword indicates that the data should be stored as a "topic" in event log data. This makes it * searchable by event log filters. A maximum of three parameters may use the indexed keyword per event. */ event RegisterAirline(address indexed account); event AuthorizeAirline(address account); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; airlines[contractOwner] = Airline({ name: "Default Name", account: contractOwner, isRegistered: true, isAuthorized: true, operationalVote: true }); authorizedAirlineCount = authorizedAirlineCount.add(1); emit RegisterAirline(contractOwner); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireIsCallerAuthorized(address admin) { require(airlines[admin].isAuthorized, "Airline is not authorized"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /* authorize caller */ function authorizeCaller(address _caller) public onlyOwner returns(bool) { authorizedCaller[_caller] = 1; emit AuthorizedCaller(_caller); return true; } /* deauthorize caller */ function deAuthorizeCaller(address _caller) public onlyOwner returns(bool) { authorizedCaller[_caller] = 0; emit DeAuthorizedCaller(_caller); return true; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } //getters for fields of the Airline struct -- don function getAirlineName(address account) external view returns(string){ return airlines[account].name; } function getAuthorizedAirlineCount() external view returns(uint256) { return authorizedAirlineCount; } function getAirlineAccount(address account) external view returns(address){ return airlines[account].account; } function getRegistrationStatus(address account) external view returns(bool){ return airlines[account].isRegistered; } function getAuthorizationStatus(address account) external view returns(bool){ return airlines[account].isAuthorized; } function getOperationalVote(address account) external view returns(bool){ return airlines[account].operationalVote; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode, address caller ) external requireIsCallerAuthorized(caller) requireContractOwner { require(operational == airlines[caller].operationalVote, "Duplicate caller"); require(mode!=operational, "New mode must be different from existing mode"); if (authorizedAirlineCount < 4) { operational = mode; } else { //use multi-party consensus amount authorized airlines to reach 50% aggreement changeOperatingStatusVotes = changeOperatingStatusVotes.add(1); airlines[caller].operationalVote = mode; if (changeOperatingStatusVotes >= (authorizedAirlineCount.div(2))) { operational = mode; changeOperatingStatusVotes = authorizedAirlineCount - changeOperatingStatusVotes; } } } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( string name, address newAirline, address admin ) external requireIsOperational requireIsCallerAuthorized(admin) returns ( bool success, uint256 authorizedAirlineNumber, uint256 votes ) { require(!airlines[newAirline].isRegistered, "New Airline is already registered"); require(airlines[admin].isRegistered, "Admin Airline is not registered"); if (authorizedAirlineCount < 4) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: false, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, 1); } else { //multiparty consensus bool isDuplicate = false; //better to use an owner parameter than msg.sender here? if (multiCalls[newAirline][admin] == 1) { isDuplicate = true; } require(!isDuplicate, "Caller has already called this function"); multiCalls[newAirline][admin] = 1; voteCounter[newAirline] = voteCounter[newAirline].add(1); if (voteCounter[newAirline] >= (authorizedAirlineCount.div(2))) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: true, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, voteCounter[newAirline]); } else { return(false, authorizedAirlineCount, voteCounter[newAirline]); } } } /** * @dev Buy insurance for a flight */ function buy (address airline, string flight, uint256 timestamp, uint256 amount) external payable requireIsOperational { require(msg.value == amount, "Transaction is suspect"); uint256 newAmount = amount; if (amount > 1 ether) { uint256 creditAmount = amount - 1; newAmount = 1; credit[msg.sender] = creditAmount; } bytes32 key = getFlightKey(airline, flight, timestamp); Insurance memory newInsurance = Insurance(msg.sender, key, newAmount); insurance.push(newInsurance); emit Bought(msg.sender, key, amount); } /** * @dev Credits payouts to insurees */ function creditInsurees (address airline, string flight, uint256 timestamp) external view requireIsOperational { bytes32 flightKey = getFlightKey(airline, flight, timestamp); for (uint i=0; i < insurance.length; i++) { if (insurance[i].key == flightKey) { credit[insurance[i].owner] = insurance[i].amount.mul(15).div(10); Insurance memory insur = insurance[i]; insurance[i] = insurance[insurance.length - 1]; insurance[insurance.length - 1] = insur; delete insurance[insurance.length - 1]; insurance.length--; } } emit Creditted(flightKey); } /** * @dev Transfers eligible payout funds to insuree */ function pay () external payable requireIsOperational { require(credit[msg.sender] > 0, "Caller does not have any credit"); uint256 amountToReturn = credit[msg.sender]; credit[msg.sender] = 0; msg.sender.transfer(amountToReturn); emit Paid(msg.sender, amountToReturn); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( address sender ) public payable requireIsOperational { require(msg.value >= 10 ether, "Inadaquate funds"); require(airlines[sender].isRegistered, "Sending account must be registered before it can be funded"); uint256 existingAmount = funds[sender]; uint256 totalAmount = existingAmount.add(msg.value); funds[sender] = 0; sender.transfer(msg.value); //their code has the totalAmount being transferred to the contract account. Why? if (airlines[sender].isAuthorized == false) { airlines[sender].isAuthorized = true; authorizedAirlineCount = authorizedAirlineCount.add(1); emit AuthorizeAirline(sender); } funds[sender] = totalAmount; } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) view internal requireIsOperational returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable requireIsOperational { fund(msg.sender); } }
Add an airline to the registration queue Can only be called from FlightSuretyApp contract/
{ require(!airlines[newAirline].isRegistered, "New Airline is already registered"); require(airlines[admin].isRegistered, "Admin Airline is not registered"); function registerAirline ( string name, address newAirline, address admin ) external requireIsOperational requireIsCallerAuthorized(admin) returns ( bool success, uint256 authorizedAirlineNumber, uint256 votes ) if (authorizedAirlineCount < 4) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: false, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, 1); bool isDuplicate = false; if (multiCalls[newAirline][admin] == 1) { isDuplicate = true; } require(!isDuplicate, "Caller has already called this function"); multiCalls[newAirline][admin] = 1; voteCounter[newAirline] = voteCounter[newAirline].add(1); if (voteCounter[newAirline] >= (authorizedAirlineCount.div(2))) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: true, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, voteCounter[newAirline]); return(false, authorizedAirlineCount, voteCounter[newAirline]); } } function registerAirline ( string name, address newAirline, address admin ) external requireIsOperational requireIsCallerAuthorized(admin) returns ( bool success, uint256 authorizedAirlineNumber, uint256 votes ) if (authorizedAirlineCount < 4) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: false, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, 1); bool isDuplicate = false; if (multiCalls[newAirline][admin] == 1) { isDuplicate = true; } require(!isDuplicate, "Caller has already called this function"); multiCalls[newAirline][admin] = 1; voteCounter[newAirline] = voteCounter[newAirline].add(1); if (voteCounter[newAirline] >= (authorizedAirlineCount.div(2))) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: true, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, voteCounter[newAirline]); return(false, authorizedAirlineCount, voteCounter[newAirline]); } } function registerAirline ( string name, address newAirline, address admin ) external requireIsOperational requireIsCallerAuthorized(admin) returns ( bool success, uint256 authorizedAirlineNumber, uint256 votes ) if (authorizedAirlineCount < 4) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: false, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, 1); bool isDuplicate = false; if (multiCalls[newAirline][admin] == 1) { isDuplicate = true; } require(!isDuplicate, "Caller has already called this function"); multiCalls[newAirline][admin] = 1; voteCounter[newAirline] = voteCounter[newAirline].add(1); if (voteCounter[newAirline] >= (authorizedAirlineCount.div(2))) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: true, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, voteCounter[newAirline]); return(false, authorizedAirlineCount, voteCounter[newAirline]); } } function registerAirline ( string name, address newAirline, address admin ) external requireIsOperational requireIsCallerAuthorized(admin) returns ( bool success, uint256 authorizedAirlineNumber, uint256 votes ) if (authorizedAirlineCount < 4) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: false, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, 1); bool isDuplicate = false; if (multiCalls[newAirline][admin] == 1) { isDuplicate = true; } require(!isDuplicate, "Caller has already called this function"); multiCalls[newAirline][admin] = 1; voteCounter[newAirline] = voteCounter[newAirline].add(1); if (voteCounter[newAirline] >= (authorizedAirlineCount.div(2))) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: true, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, voteCounter[newAirline]); return(false, authorizedAirlineCount, voteCounter[newAirline]); } } function registerAirline ( string name, address newAirline, address admin ) external requireIsOperational requireIsCallerAuthorized(admin) returns ( bool success, uint256 authorizedAirlineNumber, uint256 votes ) if (authorizedAirlineCount < 4) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: false, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, 1); bool isDuplicate = false; if (multiCalls[newAirline][admin] == 1) { isDuplicate = true; } require(!isDuplicate, "Caller has already called this function"); multiCalls[newAirline][admin] = 1; voteCounter[newAirline] = voteCounter[newAirline].add(1); if (voteCounter[newAirline] >= (authorizedAirlineCount.div(2))) { airlines[newAirline] = Airline({ name: name, account: newAirline, isRegistered: true, isAuthorized: true, operationalVote: true }); emit RegisterAirline(newAirline); return(true, authorizedAirlineCount, voteCounter[newAirline]); return(false, authorizedAirlineCount, voteCounter[newAirline]); } } } else { }
12,808,329
// File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/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/ERC1155/IERC1155Receiver.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; /** * @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); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @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/token/ERC1155/extensions/IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; /** * @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/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/derpnationgames_flat.sol pragma solidity ^0.8.0; //import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; interface IDerpNation { function ownerOf(uint256 tokenId) external view returns (address); } /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, to, ids, amounts, data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _afterTokenTransfer(operator, from, to, ids, amounts, data); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _afterTokenTransfer(operator, from, to, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - Mints specific 'id' with an 'amount unsafely to 'to' without a safeTransfer check */ function _mintUnsafe( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); _afterTokenTransfer(operator, from, address(0), ids, amounts, ""); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} /** * @dev Hook that is called after any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } contract DerpNationGames is Ownable, ERC1155, ReentrancyGuard { event SaveGame(uint256 indexed gameId, uint16 version, uint256 indexed saveId); event UploadGame(uint256 indexed gameId, uint16 version); struct Game { uint256 price; uint256 startBlock; bytes32 dataHash; uint256 currentSupply; uint256 maxSupply; address creator; uint16 version; mapping(uint256 => bool) claimed; } mapping(uint256 => Game) public _games; uint256 public _gameId = 0; uint256 public _saveId = 0; address public _pixelPawnAddress = address(0); // mainnet pixelpawn address address public _derpNationAddress = address(0); uint256 public _whitelistBlocks = 3456; // 13ish hours receive() external payable {} fallback() external payable {} function deposit() public payable { } constructor() ERC1155("https://www.derpnation.xyz/dng_api/{id}.json") { } function updateURI(string memory newuri) public onlyOwner{ _setURI(newuri); } function updatePixelPawnAddress(address pp) public onlyOwner{ require(_pixelPawnAddress == address(0),"n4u"); _pixelPawnAddress = pp; } function updateWhitelistAddress(address wl) public onlyOwner{ require(_derpNationAddress == address(0),"n4u"); _derpNationAddress = wl; } function createGame(uint256 price, uint256 startBlock, bytes32 dataHash, uint256 maxSupply, address creator) public onlyOwner returns(uint256){ //allow creation of a game, ensure start block is greater than current block require(startBlock > block.number, "SB"); _gameId++; _games[_gameId].price = price; _games[_gameId].startBlock = startBlock; _games[_gameId].dataHash = dataHash; _games[_gameId].maxSupply = maxSupply; _games[_gameId].creator = creator; // mint 5 tokens to the owner of the contract, 150 to pixelPawn and 50 to the game creator _games[_gameId].currentSupply = 255; _mint(owner(),_gameId,5,""); _mintUnsafe(_pixelPawnAddress,_gameId, 200, ""); _mint(creator, _gameId, 50,""); return(_gameId); } function updateGame(uint256 currentGameId, uint256 startBlock, bytes32 dataHash, address creator) public onlyOwner{ //allows games to be updated with new versions and for the start block to be changed to // effectively start a mint or halt minting _games[currentGameId].startBlock = startBlock; _games[currentGameId].dataHash = dataHash; _games[_gameId].creator = creator; } function checkClaim(uint256 currentGameId, uint256 derpNationId) public view returns (bool){ return _games[currentGameId].claimed[derpNationId]; } function mint(uint256 currentGameId, uint256[] calldata derpNationIds, bool presale) public nonReentrant payable { // check that the sender is not a contract, that the value is correct and that the game isnt sold out require(msg.sender == tx.origin,"Nope"); require(msg.value == _games[currentGameId].price*derpNationIds.length, "Wrong Price"); require(_games[currentGameId].currentSupply+derpNationIds.length <= _games[currentGameId].maxSupply, "Sold out"); require(derpNationIds.length > 0, "min 1"); require(derpNationIds.length < 6, "max 5"); if(!presale) // if not presale, wait until whitelist period is over require(block.number >_games[currentGameId].startBlock + _whitelistBlocks, "PUB-Too soon"); else{ // check presale has begun require(block.number > _games[currentGameId].startBlock, "PRE-Too soon"); uint i = 0; //go over every ID they sent for(i=0;i<derpNationIds.length;i++){ // check that the sender owns the derp ID they say that they own, mark it as claimed require(IDerpNation(_derpNationAddress).ownerOf(derpNationIds[i]) == msg.sender, "Not yours"); require(_games[currentGameId].claimed[derpNationIds[i]] == false, "Already Claimed"); _games[currentGameId].claimed[derpNationIds[i]] = true; } } // current supply incremented, token minted to user and payment send to creator and derpNation _games[currentGameId].currentSupply+=derpNationIds.length; _mint(msg.sender,currentGameId,derpNationIds.length,""); if(msg.value > 0){ bool sent; bytes memory data; (sent, data) = payable(_derpNationAddress).call{value: (address(this).balance/10)}(""); require(sent, "Fts"); (sent, data) = payable(_games[currentGameId].creator).call{value: (address(this).balance)}(""); require(sent, "Fts"); } } function totalSupply(uint256 currentGameId) public view returns(uint256){ return _games[currentGameId].currentSupply; } function maxSupply(uint256 currentGameId) public view returns(uint256){ return _games[currentGameId].maxSupply; } function saveGame(uint256 currentGameId, uint16 version, string calldata note, bytes calldata data1,bytes calldata data2,bytes calldata data3,bytes calldata data4) external { _saveId++; emit SaveGame(currentGameId, version, _saveId); } function uploadGame(uint256 currentGameId, string calldata name, string calldata desc, bytes calldata data) external onlyOwner{ _games[currentGameId].version++; emit UploadGame(currentGameId, _games[currentGameId].version); } }
check that the sender is not a contract, that the value is correct and that the game isnt sold outgo over every ID they sent
function mint(uint256 currentGameId, uint256[] calldata derpNationIds, bool presale) public nonReentrant payable { require(msg.sender == tx.origin,"Nope"); require(msg.value == _games[currentGameId].price*derpNationIds.length, "Wrong Price"); require(_games[currentGameId].currentSupply+derpNationIds.length <= _games[currentGameId].maxSupply, "Sold out"); require(derpNationIds.length > 0, "min 1"); require(derpNationIds.length < 6, "max 5"); require(block.number >_games[currentGameId].startBlock + _whitelistBlocks, "PUB-Too soon"); require(block.number > _games[currentGameId].startBlock, "PRE-Too soon"); uint i = 0; for(i=0;i<derpNationIds.length;i++){ require(IDerpNation(_derpNationAddress).ownerOf(derpNationIds[i]) == msg.sender, "Not yours"); require(_games[currentGameId].claimed[derpNationIds[i]] == false, "Already Claimed"); _games[currentGameId].claimed[derpNationIds[i]] = true; } }
10,158,525
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Items. @author Tim Clancy This is the governing registry of all SuperFarm Item assets. */ contract FarmItemRecords is Ownable, ReentrancyGuard { /// A version number for this record contract's interface. uint256 public version = 1; /// A mapping for an array of all Fee1155s deployed by a particular address. mapping (address => address[]) public itemRecords; /// An event for tracking the creation of a new Item. event ItemCreated(address indexed itemAddress, address indexed creator); /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /** Construct a new item registry with a specific OpenSea proxy address. @param _proxyRegistryAddress An OpenSea proxy registry address. */ constructor(address _proxyRegistryAddress) public { proxyRegistryAddress = _proxyRegistryAddress; } /** Create a Fee1155 on behalf of the owner calling this function. The Fee1155 immediately mints a single-item collection. @param _uri The item group's metadata URI. @param _royaltyFee The creator's fee to apply to the created item. @param _initialSupply An array of per-item initial supplies which should be minted immediately. @param _maximumSupply An array of per-item maximum supplies. @param _recipients An array of addresses which will receive the initial supply minted for each corresponding item. @param _data Any associated data to use if items are minted this transaction. */ function createItem(string calldata _uri, uint256 _royaltyFee, uint256[] calldata _initialSupply, uint256[] calldata _maximumSupply, address[] calldata _recipients, bytes calldata _data) external nonReentrant returns (Fee1155) { FeeOwner royaltyFeeOwner = new FeeOwner(_royaltyFee, 30000); Fee1155 newItemGroup = new Fee1155(_uri, royaltyFeeOwner, proxyRegistryAddress); newItemGroup.create(_initialSupply, _maximumSupply, _recipients, _data); // Transfer ownership of the new Item to the user then store a reference. royaltyFeeOwner.transferOwnership(msg.sender); newItemGroup.transferOwnership(msg.sender); address itemAddress = address(newItemGroup); itemRecords[msg.sender].push(itemAddress); emit ItemCreated(itemAddress, msg.sender); return newItemGroup; } /** Allow a user to add an existing Item contract to the registry. @param _itemAddress The address of the Item contract to add for this user. */ function addItem(address _itemAddress) external { itemRecords[msg.sender].push(_itemAddress); } /** Get the number of entries in the Item records mapping for the given user. @return The number of Items added for a given address. */ function getItemCount(address _user) external view returns (uint256) { return itemRecords[_user].length; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title Represents ownership over a fee of some percentage. @author Tim Clancy */ contract FeeOwner is Ownable { using SafeMath for uint256; /// A version number for this FeeOwner contract's interface. uint256 public version = 1; /// The percent fee due to this contract's owner, represented as 1/1000th of a percent. That is, a 1% fee maps to 1000. uint256 public fee; /// The maximum configurable percent fee due to this contract's owner, represented as 1/1000th of a percent. uint256 public maximumFee; /// An event for tracking modification of the fee. event FeeChanged(uint256 oldFee, uint256 newFee); /** Construct a new FeeOwner by providing specifying a fee. @param _fee The percent fee to apply, represented as 1/1000th of a percent. @param _maximumFee The maximum possible fee that the owner can set. */ constructor(uint256 _fee, uint256 _maximumFee) public { require(_fee <= _maximumFee, "The fee cannot be set above its maximum."); fee = _fee; maximumFee = _maximumFee; } /** Allows the owner of this fee to modify what they take, within bounds. @param newFee The new fee to begin using. */ function changeFee(uint256 newFee) external onlyOwner { require(newFee <= maximumFee, "The fee cannot be set above its original maximum."); emit FeeChanged(fee, newFee); fee = newFee; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; /** @title An OpenSea delegate proxy contract which we include for whitelisting. @author OpenSea */ contract OwnableDelegateProxy { } /** @title An OpenSea proxy registry contract which we include for whitelisting. @author OpenSea */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** @title An ERC-1155 item creation contract which specifies an associated FeeOwner who receives royalties from sales of created items. @author Tim Clancy The fee set by the FeeOwner on this Item is honored by Shop contracts. In addition to the inherited OpenZeppelin dependency, this uses ideas from the original ERC-1155 reference implementation. */ contract Fee1155 is ERC1155, Ownable { using SafeMath for uint256; /// A version number for this fee-bearing 1155 item contract's interface. uint256 public version = 1; /// The ERC-1155 URI for looking up item metadata using {id} substitution. string public metadataUri; /// A user-specified FeeOwner to receive a portion of item sale earnings. FeeOwner public feeOwner; /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A counter to enforce unique IDs for each item group minted. uint256 public nextItemGroupId; /// This mapping tracks the number of unique items within each item group. mapping (uint256 => uint256) public itemGroupSizes; /// A mapping of item IDs to their circulating supplies. mapping (uint256 => uint256) public currentSupply; /// A mapping of item IDs to their maximum supplies; true NFTs are unique. mapping (uint256 => uint256) public maximumSupply; /// A mapping of all addresses approved to mint items on behalf of the owner. mapping (address => bool) public approvedMinters; /// An event for tracking the creation of an item group. event ItemGroupCreated(uint256 itemGroupId, uint256 itemGroupSize, address indexed creator); /// A custom modifier which permits only approved minters to mint items. modifier onlyMinters { require(msg.sender == owner() || approvedMinters[msg.sender], "You are not an approved minter for this item."); _; } /** Construct a new ERC-1155 item with an associated FeeOwner fee. @param _uri The metadata URI to perform token ID substitution in. @param _feeOwner The address of a FeeOwner who receives earnings from this item. @param _proxyRegistryAddress An OpenSea proxy registry address. */ constructor(string memory _uri, FeeOwner _feeOwner, address _proxyRegistryAddress) public ERC1155(_uri) { metadataUri = _uri; feeOwner = _feeOwner; proxyRegistryAddress = _proxyRegistryAddress; nextItemGroupId = 0; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. This function returns true if `_operator` is approved to transfer items owned by `_owner`. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** Allow the item owner to update the metadata URI of this collection. @param _uri The new URI to update to. */ function setURI(string calldata _uri) external onlyOwner { metadataUri = _uri; } /** Allows the owner of this contract to grant or remove approval to an external minter of items. @param _minter The external address allowed to mint items. @param _approval The updated `_minter` approval status. */ function approveMinter(address _minter, bool _approval) external onlyOwner { approvedMinters[_minter] = _approval; } /** This function creates an "item group" which may contain one or more individual items. The items within a group may be any combination of fungible or nonfungible. The distinction between a fungible and a nonfungible item is made by checking the item's possible `_maximumSupply`; nonfungible items will naturally have a maximum supply of one because they are unqiue. Creating an item through this function defines its maximum supply. The size of the item group is inferred from the size of the input arrays. The primary purpose of an item group is to create a collection of nonfungible items where each item within the collection is unique but they all share some data as a group. The primary example of this is something like a series of 100 trading cards where each card is unique with its issue number from 1 to 100 but all otherwise reflect the same metadata. In such an example, the `_maximumSupply` of each item is one and the size of the group would be specified by passing an array with 100 elements in it to this function: [ 1, 1, 1, ... 1 ]. Within an item group, items are 1-indexed with the 0-index of the item group supporting lookup of item group metadata. This 0-index metadata includes lookup via `maximumSupply` of the full count of items in the group should all of the items be minted, lookup via `currentSupply` of the number of items circulating from the group as a whole, and lookup via `groupSizes` of the number of unique items within the group. @param initialSupply An array of per-item initial supplies which should be minted immediately. @param _maximumSupply An array of per-item maximum supplies. @param recipients An array of addresses which will receive the initial supply minted for each corresponding item. @param data Any associated data to use if items are minted this transaction. */ function create(uint256[] calldata initialSupply, uint256[] calldata _maximumSupply, address[] calldata recipients, bytes calldata data) external onlyOwner returns (uint256) { uint256 groupSize = initialSupply.length; require(groupSize > 0, "You cannot create an empty item group."); require(initialSupply.length == _maximumSupply.length, "Initial supply length cannot be mismatched with maximum supply length."); require(initialSupply.length == recipients.length, "Initial supply length cannot be mismatched with recipients length."); // Create an item group of requested size using the next available ID. uint256 shiftedGroupId = nextItemGroupId << 128; itemGroupSizes[shiftedGroupId] = groupSize; emit ItemGroupCreated(shiftedGroupId, groupSize, msg.sender); // Record the supply cap of each item being created in the group. uint256 fullCollectionSize = 0; for (uint256 i = 0; i < groupSize; i++) { uint256 itemInitialSupply = initialSupply[i]; uint256 itemMaximumSupply = _maximumSupply[i]; fullCollectionSize = fullCollectionSize.add(itemMaximumSupply); require(itemMaximumSupply > 0, "You cannot create an item which is never mintable."); require(itemInitialSupply <= itemMaximumSupply, "You cannot create an item which exceeds its own supply cap."); // The item ID is offset by one because the zero index of the group is used to store the group size. uint256 itemId = shiftedGroupId.add(i + 1); maximumSupply[itemId] = itemMaximumSupply; // If this item is being initialized with a supply, mint to the recipient. if (itemInitialSupply > 0) { address itemRecipient = recipients[i]; _mint(itemRecipient, itemId, itemInitialSupply, data); currentSupply[itemId] = itemInitialSupply; } } // Also record the full size of the entire item group. maximumSupply[shiftedGroupId] = fullCollectionSize; // Increment our next item group ID and return our created item group ID. nextItemGroupId = nextItemGroupId.add(1); return shiftedGroupId; } /** Allow the item owner to mint a new item, so long as there is supply left to do so. @param to The address to send the newly-minted items to. @param id The ERC-1155 ID of the item being minted. @param amount The amount of the new item to mint. @param data Any associated data for this minting event that should be passed. */ function mint(address to, uint256 id, uint256 amount, bytes calldata data) external onlyMinters { uint256 groupId = id & GROUP_MASK; require(groupId != id, "You cannot mint an item with an issuance index of 0."); currentSupply[groupId] = currentSupply[groupId].add(amount); uint256 newSupply = currentSupply[id].add(amount); currentSupply[id] = newSupply; require(newSupply <= maximumSupply[id], "You cannot mint an item beyond its permitted maximum supply."); _mint(to, id, amount, data); } /** Allow the item owner to mint a new batch of items, so long as there is supply left to do so for each item. @param to The address to send the newly-minted items to. @param ids The ERC-1155 IDs of the items being minted. @param amounts The amounts of the new items to mint. @param data Any associated data for this minting event that should be passed. */ function mintBatch(address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external onlyMinters { require(ids.length > 0, "You cannot perform an empty mint."); require(ids.length == amounts.length, "Supplied IDs length cannot be mismatched with amounts length."); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 groupId = id & GROUP_MASK; require(groupId != id, "You cannot mint an item with an issuance index of 0."); currentSupply[groupId] = currentSupply[groupId].add(amount); uint256 newSupply = currentSupply[id].add(amount); currentSupply[id] = newSupply; require(newSupply <= maximumSupply[id], "You cannot mint an item beyond its permitted maximum supply."); } _mintBatch(to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC1155.sol"; import "./IERC1155MetadataURI.sol"; import "./IERC1155Receiver.sol"; import "../../utils/Context.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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 SafeMath for uint256; 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; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @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) external 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(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, 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(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); 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]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(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] = _balances[id][account].add(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 (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } 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), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); 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 (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } 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(to).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(to).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.6.2 <0.8.0; import "../../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.6.2 <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.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _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.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; /** @title A simple Shop contract for selling ERC-1155s for Ether via direct minting. @author Tim Clancy This contract is a limited subset of the Shop1155 contract designed to mint items directly to the user upon purchase. This shop additionally requires the owner to directly approve purchase requests from prospective buyers. */ contract ShopEtherMinter1155Curated is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 1; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A user-specified Fee1155 contract to support selling items from. Fee1155 public item; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// The Shop's inventory of item groups for sale. uint256[] public inventory; /// The Shop's price for each item group. mapping (uint256 => uint256) public prices; /// A mapping of each item group ID to an array of addresses with offers. mapping (uint256 => address[]) public bidders; /// A mapping for each item group ID to a mapping of address-price offers. mapping (uint256 => mapping (address => uint256)) public offers; /** Construct a new Shop by providing it a FeeOwner. @param _item The address of the Fee1155 item that will be minting sales. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. */ constructor(Fee1155 _item, FeeOwner _feeOwner) public { item = _item; feeOwner = _feeOwner; } /** Returns the length of the inventory array. @return the length of the inventory array. */ function getInventoryCount() external view returns (uint256) { return inventory.length; } /** Returns the length of the bidder array on an item group. @return the length of the bidder array on an item group. */ function getBidderCount(uint256 groupId) external view returns (uint256) { return bidders[groupId].length; } /** Allows the Shop owner to list a new set of NFT items for sale. @param _groupIds The item group IDs to list for sale in this shop. @param _prices The corresponding purchase price to mint an item of each group. */ function listItems(uint256[] calldata _groupIds, uint256[] calldata _prices) external onlyOwner { require(_groupIds.length > 0, "You must list at least one item."); require(_groupIds.length == _prices.length, "Items length cannot be mismatched with prices length."); // Iterate through every specified item group to list items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; uint256 price = _prices[i]; inventory.push(groupId); prices[groupId] = price; } } /** Allows the Shop owner to remove items from sale. @param _groupIds The group IDs currently listed in the shop to take off sale. */ function removeItems(uint256[] calldata _groupIds) external onlyOwner { require(_groupIds.length > 0, "You must remove at least one item."); // Iterate through every specified item group to remove items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; prices[groupId] = 0; } } /** Allows any user to place an offer to purchase an item group from this Shop. For this shop, users place an offer automatically at the price set by the Shop owner. This function takes a user's Ether into escrow for the offer. @param _itemGroupIds An array of (unique) item groups for a user to place an offer for. */ function makeOffers(uint256[] calldata _itemGroupIds) public nonReentrant payable { require(_itemGroupIds.length > 0, "You must make an offer for at least one item group."); // Iterate through every specified item to make an offer on items. for (uint256 i = 0; i < _itemGroupIds.length; i++) { uint256 groupId = _itemGroupIds[i]; uint256 price = prices[groupId]; require(price > 0, "You cannot make an offer for an item that is not listed."); // Record an offer for this item. bidders[groupId].push(msg.sender); offers[groupId][msg.sender] = msg.value; } } /** Allows any user to cancel an offer for items from this Shop. This function returns a user's Ether if there is any in escrow for the item group. @param _itemGroupIds An array of (unique) item groups for a user to cancel an offer for. */ function cancelOffers(uint256[] calldata _itemGroupIds) public nonReentrant { require(_itemGroupIds.length > 0, "You must cancel an offer for at least one item group."); // Iterate through every specified item to cancel offers on items. uint256 returnedOfferAmount = 0; for (uint256 i = 0; i < _itemGroupIds.length; i++) { uint256 groupId = _itemGroupIds[i]; uint256 offeredValue = offers[groupId][msg.sender]; returnedOfferAmount = returnedOfferAmount.add(offeredValue); offers[groupId][msg.sender] = 0; } // Return the user's escrowed offer Ether. (bool success, ) = payable(msg.sender).call{ value: returnedOfferAmount }(""); require(success, "Returning canceled offer amount failed."); } /** Allows the Shop owner to accept any valid offer from a user. Once the Shop owner accepts the offer, the Ether is distributed according to fees and the item is minted to the user. @param _groupIds The item group IDs to process offers for. @param _bidders The specific bidder for each item group ID to accept. @param _itemIds The specific item ID within the group to mint for the bidder. @param _amounts The amount of specific item to mint for the bidder. */ function acceptOffers(uint256[] calldata _groupIds, address[] calldata _bidders, uint256[] calldata _itemIds, uint256[] calldata _amounts) public nonReentrant onlyOwner { require(_groupIds.length > 0, "You must accept an offer for at least one item."); require(_groupIds.length == _bidders.length, "Group IDs length cannot be mismatched with bidders length."); require(_groupIds.length == _itemIds.length, "Group IDs length cannot be mismatched with item IDs length."); require(_groupIds.length == _amounts.length, "Group IDs length cannot be mismatched with item amounts length."); // Accept all offers and disperse fees accordingly. uint256 feePercent = feeOwner.fee(); uint256 itemRoyaltyPercent = item.feeOwner().fee(); for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; address bidder = _bidders[i]; uint256 itemId = _itemIds[i]; uint256 amount = _amounts[i]; // Verify that the offer being accepted is still valid. uint256 price = prices[groupId]; require(price > 0, "You cannot accept an offer for an item that is not listed."); uint256 offeredPrice = offers[groupId][bidder]; require(offeredPrice >= price, "You cannot accept an offer for less than the current asking price."); // Split fees for this purchase. uint256 feeValue = offeredPrice.mul(feePercent).div(100000); uint256 royaltyValue = offeredPrice.mul(itemRoyaltyPercent).div(100000); (bool success, ) = payable(feeOwner.owner()).call{ value: feeValue }(""); require(success, "Platform fee transfer failed."); (success, ) = payable(item.feeOwner().owner()).call{ value: royaltyValue }(""); require(success, "Creator royalty transfer failed."); (success, ) = payable(owner()).call{ value: offeredPrice.sub(feeValue).sub(royaltyValue) }(""); require(success, "Shop owner transfer failed."); // Mint the item. item.mint(bidder, itemId, amount, ""); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC1155Receiver.sol"; import "../../introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155NFTLockable.sol"; import "./Staker.sol"; /** @title A Shop contract for selling NFTs via direct minting through particular pools with specific participation requirements. @author Tim Clancy This launchpad contract is specifically optimized for SuperFarm direct use. */ contract ShopPlatformLaunchpad1155 is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 2; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A user-specified Fee1155 contract to support selling items from. Fee1155NFTLockable public item; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// A user-specified Staker contract to spend user points on. Staker[] public stakers; /** A limit on the number of items that a particular address may purchase across any number of pools in the launchpad. */ uint256 public globalPurchaseLimit; /// A mapping of addresses to the number of items each has purchased globally. mapping (address => uint256) public globalPurchaseCounts; /// The address of the orignal owner of the item contract. address public originalOwner; /// Whether ownership is locked to disable clawback. bool public ownershipLocked; /// A mapping of item group IDs to their next available issue number minus one. mapping (uint256 => uint256) public nextItemIssues; /// The next available ID to be assumed by the next whitelist added. uint256 public nextWhitelistId; /** A mapping of whitelist IDs to specific Whitelist elements. Whitelists may be shared between pools via specifying their ID in a pool requirement. */ mapping (uint256 => Whitelist) public whitelists; /// The next available ID to be assumed by the next pool added. uint256 public nextPoolId; /// A mapping of pool IDs to pools. mapping (uint256 => Pool) public pools; /** This struct is a source of mapping-free input to the `addPool` function. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. */ struct PoolInput { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; PoolRequirement requirement; } /** This struct tracks information about a single item pool in the Shop. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param purchaseCounts A mapping of addresses to the number of items each has purchased from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. @param itemGroups An array of all item groups currently present in this pool. @param currentPoolVersion A version number hashed with item group IDs before being used as keys to other mappings. This supports efficient invalidation of stale mappings. @param itemCaps A mapping of item group IDs to the maximum number this pool is allowed to mint. @param itemMinted A mapping of item group IDs to the number this pool has currently minted. @param itemPricesLength A mapping of item group IDs to the number of price assets available to purchase with. @param itemPrices A mapping of item group IDs to a mapping of available PricePair assets available to purchase with. */ struct Pool { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; mapping (address => uint256) purchaseCounts; PoolRequirement requirement; uint256[] itemGroups; uint256 currentPoolVersion; mapping (bytes32 => uint256) itemCaps; mapping (bytes32 => uint256) itemMinted; mapping (bytes32 => uint256) itemPricesLength; mapping (bytes32 => mapping (uint256 => PricePair)) itemPrices; } /** This struct tracks information about a prerequisite for a user to participate in a pool. @param requiredType A sentinel value for the specific type of asset being required. 0 = a pool which requires no specific assets to participate. 1 = an ERC-20 token, see `requiredAsset`. 2 = an NFT item, see `requiredAsset`. @param requiredAsset Some more specific information about the asset to require. If the `requiredType` is 1, we use this address to find the ERC-20 token that we should be specifically requiring holdings of. If the `requiredType` is 2, we use this address to find the item contract that we should be specifically requiring holdings of. @param requiredAmount The amount of the specified `requiredAsset` required. @param whitelistId The ID of an address whitelist to restrict participants in this pool. To participate, a purchaser must have their address present in the corresponding whitelist. Other requirements from `requiredType` apply. An ID of 0 is a sentinel value for no whitelist: a public pool. */ struct PoolRequirement { uint256 requiredType; address requiredAsset; uint256 requiredAmount; uint256 whitelistId; } /** This struct tracks information about a single asset with associated price that an item is being sold in the shop for. @param assetType A sentinel value for the specific type of asset being used. 0 = non-transferrable points from a Staker; see `asset`. 1 = Ether. 2 = an ERC-20 token, see `asset`. @param asset Some more specific information about the asset to charge in. If the `assetType` is 0, we convert the given address to an integer index for finding a specific Staker from `stakers`. If the `assetType` is 1, we ignore this field. If the `assetType` is 2, we use this address to find the ERC-20 token that we should be specifically charging with. @param price The amount of the specified `assetType` and `asset` to charge. */ struct PricePair { uint256 assetType; address asset; uint256 price; } /** This struct is a source of mapping-free input to the `addWhitelist` function. @param expiryBlock A block number after which this whitelist is automatically considered inactive, no matter the value of `isActive`. @param isActive Whether or not this whitelist is actively restricting purchases in blocks before `expiryBlock`. @param addresses An array of addresses to whitelist for participation in a purchase. */ struct WhitelistInput { uint256 expiryBlock; bool isActive; address[] addresses; } /** This struct tracks information about a single whitelist known to this launchpad. Whitelists may be shared across potentially-multiple item pools. @param expiryBlock A block number after which this whitelist is automatically considered inactive, no matter the value of `isActive`. @param isActive Whether or not this whitelist is actively restricting purchases in blocks before `expiryBlock`. @param currentWhitelistVersion A version number hashed with item group IDs before being used as keys to other mappings. This supports efficient invalidation of stale mappings. @param addresses A mapping of hashed addresses to a flag indicating whether this whitelist allows the address to participate in a purchase. */ struct Whitelist { uint256 expiryBlock; bool isActive; uint256 currentWhitelistVersion; mapping (bytes32 => bool) addresses; } /** This struct tracks information about a single item being sold in a pool. @param groupId The group ID of the specific NFT in the collection being sold by a pool. @param cap The maximum number of items that a pool may mint of the specified `groupId`. @param minted The number of items that a pool has currently minted of the specified `groupId`. @param prices The PricePair options that may be used to purchase this item from its pool. */ struct PoolItem { uint256 groupId; uint256 cap; uint256 minted; PricePair[] prices; } /** This struct contains the information gleaned from the `getPool` and `getPools` functions; it represents a single pool's data. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. @param itemMetadataUri The metadata URI of the item collection being sold by this launchpad. @param items An array of PoolItems representing each item for sale in the pool. */ struct PoolOutput { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; PoolRequirement requirement; string itemMetadataUri; PoolItem[] items; } /** This struct contains the information gleaned from the `getPool` and `getPools` functions; it represents a single pool's data. It also includes additional information relevant to a user's address lookup. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. @param itemMetadataUri The metadata URI of the item collection being sold by this launchpad. @param items An array of PoolItems representing each item for sale in the pool. @param purchaseCount The amount of items purchased from this pool by the specified address. @param whitelistStatus Whether or not the specified address is whitelisted for this pool. */ struct PoolAddressOutput { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; PoolRequirement requirement; string itemMetadataUri; PoolItem[] items; uint256 purchaseCount; bool whitelistStatus; } /// An event to track the original item contract owner clawing back ownership. event OwnershipClawback(); /// An event to track the original item contract owner locking future clawbacks. event OwnershipLocked(); /// An event to track the complete replacement of a pool's data. event PoolUpdated(uint256 poolId, PoolInput pool, uint256[] groupIds, uint256[] amounts, PricePair[][] pricePairs); /// An event to track the complete replacement of addresses in a whitelist. event WhitelistUpdated(uint256 whitelistId, address[] addresses); /// An event to track the addition of addresses to a whitelist. event WhitelistAddition(uint256 whitelistId, address[] addresses); /// An event to track the removal of addresses from a whitelist. event WhitelistRemoval(uint256 whitelistId, address[] addresses); // An event to track activating or deactivating a whitelist. event WhitelistActiveUpdate(uint256 whitelistId, bool isActive); // An event to track the purchase of items from a pool. event ItemPurchased(uint256 poolId, uint256[] itemIds, uint256 assetId, uint256[] amounts, address user); /// @dev a modifier which allows only `originalOwner` to call a function. modifier onlyOriginalOwner() { require(originalOwner == _msgSender(), "You are not the original owner of this contract."); _; } /** Construct a new Shop by providing it a FeeOwner. @param _item The address of the Fee1155NFTLockable item that will be minting sales. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. @param _stakers The addresses of any Stakers to permit spending points from. @param _globalPurchaseLimit A global limit on the number of items that a single address may purchase across all pools in the launchpad. */ constructor(Fee1155NFTLockable _item, FeeOwner _feeOwner, Staker[] memory _stakers, uint256 _globalPurchaseLimit) public { item = _item; feeOwner = _feeOwner; stakers = _stakers; globalPurchaseLimit = _globalPurchaseLimit; nextWhitelistId = 1; originalOwner = item.owner(); ownershipLocked = false; } /** A function which allows the caller to retrieve information about specific pools, the items for sale within, and the collection this launchpad uses. @param poolIds An array of pool IDs to retrieve information about. */ function getPools(uint256[] calldata poolIds) external view returns (PoolOutput[] memory) { PoolOutput[] memory poolOutputs = new PoolOutput[](poolIds.length); for (uint256 i = 0; i < poolIds.length; i++) { uint256 poolId = poolIds[i]; // Process output for each pool. PoolItem[] memory poolItems = new PoolItem[](pools[poolId].itemGroups.length); for (uint256 j = 0; j < pools[poolId].itemGroups.length; j++) { uint256 itemGroupId = pools[poolId].itemGroups[j]; bytes32 itemKey = keccak256(abi.encodePacked(pools[poolId].currentPoolVersion, itemGroupId)); // Parse each price the item is sold at. PricePair[] memory itemPrices = new PricePair[](pools[poolId].itemPricesLength[itemKey]); for (uint256 k = 0; k < pools[poolId].itemPricesLength[itemKey]; k++) { itemPrices[k] = pools[poolId].itemPrices[itemKey][k]; } // Track the item. poolItems[j] = PoolItem({ groupId: itemGroupId, cap: pools[poolId].itemCaps[itemKey], minted: pools[poolId].itemMinted[itemKey], prices: itemPrices }); } // Track the pool. poolOutputs[i] = PoolOutput({ name: pools[poolId].name, startBlock: pools[poolId].startBlock, endBlock: pools[poolId].endBlock, purchaseLimit: pools[poolId].purchaseLimit, requirement: pools[poolId].requirement, itemMetadataUri: item.metadataUri(), items: poolItems }); } // Return the pools. return poolOutputs; } /** A function which allows the caller to retrieve the number of items specific addresses have purchased from specific pools. @param poolIds The IDs of the pools to check for addresses in `purchasers`. @param purchasers The addresses to check the purchase counts for. */ function getPurchaseCounts(uint256[] calldata poolIds, address[] calldata purchasers) external view returns (uint256[][] memory) { uint256[][] memory purchaseCounts; for (uint256 i = 0; i < poolIds.length; i++) { uint256 poolId = poolIds[i]; for (uint256 j = 0; j < purchasers.length; j++) { address purchaser = purchasers[j]; purchaseCounts[j][i] = pools[poolId].purchaseCounts[purchaser]; } } return purchaseCounts; } /** A function which allows the caller to retrieve information about specific pools, the items for sale within, and the collection this launchpad uses. A provided address differentiates this function from `getPools`; the added address enables this function to retrieve pool data as well as whitelisting and purchase count details for the provided address. @param poolIds An array of pool IDs to retrieve information about. @param userAddress An address which enables this function to support additional relevant data lookups. */ function getPoolsWithAddress(uint256[] calldata poolIds, address userAddress) external view returns (PoolAddressOutput[] memory) { PoolAddressOutput[] memory poolOutputs = new PoolAddressOutput[](poolIds.length); for (uint256 i = 0; i < poolIds.length; i++) { uint256 poolId = poolIds[i]; // Process output for each pool. PoolItem[] memory poolItems = new PoolItem[](pools[poolId].itemGroups.length); for (uint256 j = 0; j < pools[poolId].itemGroups.length; j++) { uint256 itemGroupId = pools[poolId].itemGroups[j]; bytes32 itemKey = keccak256(abi.encodePacked(pools[poolId].currentPoolVersion, itemGroupId)); // Parse each price the item is sold at. PricePair[] memory itemPrices = new PricePair[](pools[poolId].itemPricesLength[itemKey]); for (uint256 k = 0; k < pools[poolId].itemPricesLength[itemKey]; k++) { itemPrices[k] = pools[poolId].itemPrices[itemKey][k]; } // Track the item. poolItems[j] = PoolItem({ groupId: itemGroupId, cap: pools[poolId].itemCaps[itemKey], minted: pools[poolId].itemMinted[itemKey], prices: itemPrices }); } // Track the pool. uint256 whitelistId = pools[poolId].requirement.whitelistId; bytes32 addressKey = keccak256(abi.encode(whitelists[whitelistId].currentWhitelistVersion, userAddress)); poolOutputs[i] = PoolAddressOutput({ name: pools[poolId].name, startBlock: pools[poolId].startBlock, endBlock: pools[poolId].endBlock, purchaseLimit: pools[poolId].purchaseLimit, requirement: pools[poolId].requirement, itemMetadataUri: item.metadataUri(), items: poolItems, purchaseCount: pools[poolId].purchaseCounts[userAddress], whitelistStatus: whitelists[whitelistId].addresses[addressKey] }); } // Return the pools. return poolOutputs; } /** A function which allows the original owner of the item contract to revoke ownership from the launchpad. */ function ownershipClawback() external onlyOriginalOwner { require(!ownershipLocked, "Ownership transfers have been locked."); item.transferOwnership(originalOwner); // Emit an event that the original owner of the item contract has clawed the contract back. emit OwnershipClawback(); } /** A function which allows the original owner of this contract to lock all future ownership clawbacks. */ function lockOwnership() external onlyOriginalOwner { ownershipLocked = true; // Emit an event that the contract's ownership transferrance is locked. emit OwnershipLocked(); } /** Allow the owner of the Shop to add a new pool of items to purchase. @param pool The PoolInput full of data defining the pool's operation. @param _groupIds The specific Fee1155 item group IDs to sell in this pool, keyed to `_amounts`. @param _amounts The maximum amount of each particular groupId that can be sold by this pool. @param _pricePairs The asset address to price pairings to use for selling each item. */ function addPool(PoolInput calldata pool, uint256[] calldata _groupIds, uint256[] calldata _amounts, PricePair[][] memory _pricePairs) external onlyOwner { updatePool(nextPoolId, pool, _groupIds, _amounts, _pricePairs); // Increment the ID which will be used by the next pool added. nextPoolId = nextPoolId.add(1); } /** Allow the owner of the Shop to update an existing pool of items. @param poolId The ID of the pool to update. @param pool The PoolInput full of data defining the pool's operation. @param _groupIds The specific Fee1155 item group IDs to sell in this pool, keyed to `_amounts`. @param _amounts The maximum amount of each particular groupId that can be sold by this pool. @param _pricePairs The asset address to price pairings to use for selling each item. */ function updatePool(uint256 poolId, PoolInput calldata pool, uint256[] calldata _groupIds, uint256[] calldata _amounts, PricePair[][] memory _pricePairs) public onlyOwner { require(poolId <= nextPoolId, "You cannot update a non-existent pool."); require(pool.endBlock >= pool.startBlock, "You cannot create a pool which ends before it starts."); require(_groupIds.length > 0, "You must list at least one item group."); require(_groupIds.length == _amounts.length, "Item groups length cannot be mismatched with mintable amounts length."); require(_groupIds.length == _pricePairs.length, "Item groups length cannot be mismatched with price pair inputlength."); // Immediately store some given information about this pool. uint256 newPoolVersion = pools[poolId].currentPoolVersion.add(1); pools[poolId] = Pool({ name: pool.name, startBlock: pool.startBlock, endBlock: pool.endBlock, purchaseLimit: pool.purchaseLimit, itemGroups: _groupIds, currentPoolVersion: newPoolVersion, requirement: pool.requirement }); // Store the amount of each item group that this pool may mint. for (uint256 i = 0; i < _groupIds.length; i++) { require(_amounts[i] > 0, "You cannot add an item with no mintable amount."); bytes32 itemKey = keccak256(abi.encode(newPoolVersion, _groupIds[i])); pools[poolId].itemCaps[itemKey] = _amounts[i]; // Store future purchase information for the item group. for (uint256 j = 0; j < _pricePairs[i].length; j++) { pools[poolId].itemPrices[itemKey][j] = _pricePairs[i][j]; } pools[poolId].itemPricesLength[itemKey] = _pricePairs[i].length; } // Emit an event indicating that a pool has been updated. emit PoolUpdated(poolId, pool, _groupIds, _amounts, _pricePairs); } /** Allow the owner to add a new whitelist. @param whitelist The WhitelistInput full of data defining the new whitelist. */ function addWhitelist(WhitelistInput memory whitelist) external onlyOwner { updateWhitelist(nextWhitelistId, whitelist); // Increment the ID which will be used by the next whitelist added. nextWhitelistId = nextWhitelistId.add(1); } /** Allow the owner to update a whitelist. @param whitelistId The whitelist ID to replace with the new whitelist. @param whitelist The WhitelistInput full of data defining the new whitelist. */ function updateWhitelist(uint256 whitelistId, WhitelistInput memory whitelist) public onlyOwner { uint256 newWhitelistVersion = whitelists[whitelistId].currentWhitelistVersion.add(1); // Immediately store some given information about this whitelist. whitelists[whitelistId] = Whitelist({ expiryBlock: whitelist.expiryBlock, isActive: whitelist.isActive, currentWhitelistVersion: newWhitelistVersion }); // Invalidate the old mapping and store the new participation flags. for (uint256 i = 0; i < whitelist.addresses.length; i++) { bytes32 addressKey = keccak256(abi.encode(newWhitelistVersion, whitelist.addresses[i])); whitelists[whitelistId].addresses[addressKey] = true; } // Emit an event to track the new, replaced state of the whitelist. emit WhitelistUpdated(whitelistId, whitelist.addresses); } /** Allow the owner to add specified addresses to a whitelist. @param whitelistId The ID of the whitelist to add users to. @param addresses The array of addresses to add. */ function addToWhitelist(uint256 whitelistId, address[] calldata addresses) public onlyOwner { uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; for (uint256 i = 0; i < addresses.length; i++) { bytes32 addressKey = keccak256(abi.encode(whitelistVersion, addresses[i])); whitelists[whitelistId].addresses[addressKey] = true; } // Emit an event to track the addition of new addresses to the whitelist. emit WhitelistAddition(whitelistId, addresses); } /** Allow the owner to remove specified addresses from a whitelist. @param whitelistId The ID of the whitelist to remove users from. @param addresses The array of addresses to remove. */ function removeFromWhitelist(uint256 whitelistId, address[] calldata addresses) public onlyOwner { uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; for (uint256 i = 0; i < addresses.length; i++) { bytes32 addressKey = keccak256(abi.encode(whitelistVersion, addresses[i])); whitelists[whitelistId].addresses[addressKey] = false; } // Emit an event to track the removal of addresses from the whitelist. emit WhitelistRemoval(whitelistId, addresses); } /** Allow the owner to manually set the active status of a specific whitelist. @param whitelistId The ID of the whitelist to update the active flag for. @param isActive The boolean flag to enable or disable the whitelist. */ function setWhitelistActive(uint256 whitelistId, bool isActive) public onlyOwner { whitelists[whitelistId].isActive = isActive; // Emit an event to track whitelist activation status changes. emit WhitelistActiveUpdate(whitelistId, isActive); } /** A function which allows the caller to retrieve whether or not addresses can participate in some given whitelists. @param whitelistIds The IDs of the whitelists to check for addresses. @param addresses The addresses to check whitelist eligibility for. */ function getWhitelistStatus(uint256[] calldata whitelistIds, address[] calldata addresses) external view returns (bool[][] memory) { bool[][] memory whitelistStatus; for (uint256 i = 0; i < whitelistIds.length; i++) { uint256 whitelistId = whitelistIds[i]; uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; for (uint256 j = 0; j < addresses.length; j++) { bytes32 addressKey = keccak256(abi.encode(whitelistVersion, addresses[j])); whitelistStatus[j][i] = whitelists[whitelistId].addresses[addressKey]; } } return whitelistStatus; } /** Allow a user to purchase an item from a pool. @param poolId The ID of the particular pool that the user would like to purchase from. @param groupId The item group ID that the user would like to purchase. @param assetId The type of payment asset that the user would like to purchase with. @param amount The amount of item that the user would like to purchase. */ function mintFromPool(uint256 poolId, uint256 groupId, uint256 assetId, uint256 amount) external nonReentrant payable { require(amount > 0, "You must purchase at least one item."); require(poolId < nextPoolId, "You can only purchase items from an active pool."); // Verify that the asset being used in the purchase is valid. bytes32 itemKey = keccak256(abi.encode(pools[poolId].currentPoolVersion, groupId)); require(assetId < pools[poolId].itemPricesLength[itemKey], "Your specified asset ID is not valid."); // Verify that the pool is still running its sale. require(block.number >= pools[poolId].startBlock && block.number <= pools[poolId].endBlock, "This pool is not currently running its sale."); // Verify that the pool is respecting per-address global purchase limits. uint256 userGlobalPurchaseAmount = amount.add(globalPurchaseCounts[msg.sender]); require(userGlobalPurchaseAmount <= globalPurchaseLimit, "You may not purchase any more items from this sale."); // Verify that the pool is respecting per-address pool purchase limits. uint256 userPoolPurchaseAmount = amount.add(pools[poolId].purchaseCounts[msg.sender]); require(userPoolPurchaseAmount <= pools[poolId].purchaseLimit, "You may not purchase any more items from this pool."); // Verify that the pool is either public, whitelist-expired, or an address is whitelisted. { uint256 whitelistId = pools[poolId].requirement.whitelistId; uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; bytes32 addressKey = keccak256(abi.encode(whitelistVersion, msg.sender)); bool addressWhitelisted = whitelists[whitelistId].addresses[addressKey]; require(whitelistId == 0 || block.number > whitelists[whitelistId].expiryBlock || addressWhitelisted || !whitelists[whitelistId].isActive, "You are not whitelisted on this pool."); } // Verify that the pool is not depleted by the user's purchase. uint256 newCirculatingTotal = pools[poolId].itemMinted[itemKey].add(amount); require(newCirculatingTotal <= pools[poolId].itemCaps[itemKey], "There are not enough items available for you to purchase."); // Verify that the user meets any requirements gating participation in this pool. PoolRequirement memory poolRequirement = pools[poolId].requirement; if (poolRequirement.requiredType == 1) { IERC20 requiredToken = IERC20(poolRequirement.requiredAsset); require(requiredToken.balanceOf(msg.sender) >= poolRequirement.requiredAmount, "You do not have enough required token to participate in this pool."); } // TODO: supporting item gate requirement requires upgrading the Fee1155 contract. // else if (poolRequirement.requiredType == 2) { // Fee1155 requiredItem = Fee1155(poolRequirement.requiredAsset); // require(requiredItem.balanceOf(msg.sender) >= poolRequirement.requiredAmount, // "You do not have enough required item to participate in this pool."); // } // Process payment for the user. // If the sentinel value for the point asset type is found, sell for points. // This involves converting the asset from an address to a Staker index. PricePair memory sellingPair = pools[poolId].itemPrices[itemKey][assetId]; if (sellingPair.assetType == 0) { uint256 stakerIndex = uint256(sellingPair.asset); stakers[stakerIndex].spendPoints(msg.sender, sellingPair.price.mul(amount)); // If the sentinel value for the Ether asset type is found, sell for Ether. } else if (sellingPair.assetType == 1) { uint256 etherPrice = sellingPair.price.mul(amount); require(msg.value >= etherPrice, "You did not send enough Ether to complete this purchase."); (bool success, ) = payable(owner()).call{ value: msg.value }(""); require(success, "Shop owner transfer failed."); // Otherwise, attempt to sell for an ERC20 token. } else { IERC20 sellingAsset = IERC20(sellingPair.asset); uint256 tokenPrice = sellingPair.price.mul(amount); require(sellingAsset.balanceOf(msg.sender) >= tokenPrice, "You do not have enough token to complete this purchase."); sellingAsset.safeTransferFrom(msg.sender, owner(), tokenPrice); } // If payment is successful, mint each of the user's purchased items. uint256[] memory itemIds = new uint256[](amount); uint256[] memory amounts = new uint256[](amount); uint256 nextIssueNumber = nextItemIssues[groupId]; { uint256 shiftedGroupId = groupId << 128; for (uint256 i = 1; i <= amount; i++) { uint256 itemId = shiftedGroupId.add(nextIssueNumber).add(i); itemIds[i - 1] = itemId; amounts[i - 1] = 1; } } // Mint the items. item.createNFT(msg.sender, itemIds, amounts, ""); // Update the tracker for available item issue numbers. nextItemIssues[groupId] = nextIssueNumber.add(amount); // Update the count of circulating items from this pool. pools[poolId].itemMinted[itemKey] = newCirculatingTotal; // Update the pool's count of items that a user has purchased. pools[poolId].purchaseCounts[msg.sender] = userPoolPurchaseAmount; // Update the global count of items that a user has purchased. globalPurchaseCounts[msg.sender] = userGlobalPurchaseAmount; // Emit an event indicating a successful purchase. emit ItemPurchased(poolId, itemIds, assetId, amounts, msg.sender); } /** Sweep all of a particular ERC-20 token from the contract. @param _token The token to sweep the balance from. */ function sweep(IERC20 _token) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.safeTransferFrom(address(this), msg.sender, balance); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; /** @title An OpenSea delegate proxy contract which we include for whitelisting. @author OpenSea */ contract OwnableDelegateProxy { } /** @title An OpenSea proxy registry contract which we include for whitelisting. @author OpenSea */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** @title An ERC-1155 item creation contract which specifies an associated FeeOwner who receives royalties from sales of created items. @author Tim Clancy The fee set by the FeeOwner on this Item is honored by Shop contracts. In addition to the inherited OpenZeppelin dependency, this uses ideas from the original ERC-1155 reference implementation. */ contract Fee1155NFTLockable is ERC1155, Ownable { using SafeMath for uint256; /// A version number for this fee-bearing 1155 item contract's interface. uint256 public version = 1; /// The ERC-1155 URI for looking up item metadata using {id} substitution. string public metadataUri; /// A user-specified FeeOwner to receive a portion of item sale earnings. FeeOwner public feeOwner; /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /// A counter to enforce unique IDs for each item group minted. uint256 public nextItemGroupId; /// This mapping tracks the number of unique items within each item group. mapping (uint256 => uint256) public itemGroupSizes; /// Whether or not the item collection has been locked to further minting. bool public locked; /// An event for tracking the creation of an item group. event ItemGroupCreated(uint256 itemGroupId, uint256 itemGroupSize, address indexed creator); /** Construct a new ERC-1155 item with an associated FeeOwner fee. @param _uri The metadata URI to perform token ID substitution in. @param _feeOwner The address of a FeeOwner who receives earnings from this item. */ constructor(string memory _uri, FeeOwner _feeOwner, address _proxyRegistryAddress) public ERC1155(_uri) { metadataUri = _uri; feeOwner = _feeOwner; proxyRegistryAddress = _proxyRegistryAddress; nextItemGroupId = 0; locked = false; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. This function returns true if `_operator` is approved to transfer items owned by `_owner`. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** Allow the item owner to update the metadata URI of this collection. @param _uri The new URI to update to. */ function setURI(string calldata _uri) external onlyOwner { metadataUri = _uri; } /** Allow the item owner to forever lock this contract to further item minting. */ function lock() external onlyOwner { locked = true; } /** Create a new NFT item group of a specific size. NFTs within a group share a group ID in the upper 128-bits of their full item ID. Within a group NFTs can be distinguished for the purposes of serializing issue numbers. @param recipient The address to receive all NFTs within the newly-created group. @param ids The item IDs for the new items to create. @param amounts The amount of each corresponding item ID to create. @param data Any associated data to use on items minted in this transaction. */ function createNFT(address recipient, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external onlyOwner returns (uint256) { require(!locked, "You cannot create more NFTs on a locked collection."); require(ids.length > 0, "You cannot create an empty item group."); require(ids.length == amounts.length, "IDs length cannot be mismatched with amounts length."); // Create an item group of requested size using the next available ID. uint256 shiftedGroupId = nextItemGroupId << 128; itemGroupSizes[shiftedGroupId] = ids.length; // Mint the entire batch of items. _mintBatch(recipient, ids, amounts, data); // Increment our next item group ID and return our created item group ID. nextItemGroupId = nextItemGroupId.add(1); emit ItemGroupCreated(shiftedGroupId, ids.length, msg.sender); return shiftedGroupId; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title An asset staking contract. @author Tim Clancy This staking contract disburses tokens from its internal reservoir according to a fixed emission schedule. Assets can be assigned varied staking weights. This code is inspired by and modified from Sushi's Master Chef contract. https://github.com/sushiswap/sushiswap/blob/master/contracts/MasterChef.sol */ contract Staker is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // A user-specified, descriptive name for this Staker. string public name; // The token to disburse. IERC20 public token; // The amount of the disbursed token deposited by users. This is used for the // special case where a staking pool has been created for the disbursed token. // This is required to prevent the Staker itself from reducing emissions. uint256 public totalTokenDeposited; // A flag signalling whether the contract owner can add or set developers. bool public canAlterDevelopers; // An array of developer addresses for finding shares in the share mapping. address[] public developerAddresses; // A mapping of developer addresses to their percent share of emissions. // Share percentages are represented as 1/1000th of a percent. That is, a 1% // share of emissions should map an address to 1000. mapping (address => uint256) public developerShares; // A flag signalling whether or not the contract owner can alter emissions. bool public canAlterTokenEmissionSchedule; bool public canAlterPointEmissionSchedule; // The token emission schedule of the Staker. This emission schedule maps a // block number to the amount of tokens or points that should be disbursed with every // block beginning at said block number. struct EmissionPoint { uint256 blockNumber; uint256 rate; } // An array of emission schedule key blocks for finding emission rate changes. uint256 public tokenEmissionBlockCount; mapping (uint256 => EmissionPoint) public tokenEmissionBlocks; uint256 public pointEmissionBlockCount; mapping (uint256 => EmissionPoint) public pointEmissionBlocks; // Store the very earliest possible emission block for quick reference. uint256 MAX_INT = 2**256 - 1; uint256 internal earliestTokenEmissionBlock; uint256 internal earliestPointEmissionBlock; // Information for each pool that can be staked in. // - token: the address of the ERC20 asset that is being staked in the pool. // - strength: the relative token emission strength of this pool. // - lastRewardBlock: the last block number where token distribution occurred. // - tokensPerShare: accumulated tokens per share times 1e12. // - pointsPerShare: accumulated points per share times 1e12. struct PoolInfo { IERC20 token; uint256 tokenStrength; uint256 tokensPerShare; uint256 pointStrength; uint256 pointsPerShare; uint256 lastRewardBlock; } IERC20[] public poolTokens; // Stored information for each available pool per its token address. mapping (IERC20 => PoolInfo) public poolInfo; // Information for each user per staking pool: // - amount: the amount of the pool asset being provided by the user. // - tokenPaid: the value of the user's total earning that has been paid out. // -- pending reward = (user.amount * pool.tokensPerShare) - user.rewardDebt. // - pointPaid: the value of the user's total point earnings that has been paid out. struct UserInfo { uint256 amount; uint256 tokenPaid; uint256 pointPaid; } // Stored information for each user staking in each pool. mapping (IERC20 => mapping (address => UserInfo)) public userInfo; // The total sum of the strength of all pools. uint256 public totalTokenStrength; uint256 public totalPointStrength; // The total amount of the disbursed token ever emitted by this Staker. uint256 public totalTokenDisbursed; // Users additionally accrue non-token points for participating via staking. mapping (address => uint256) public userPoints; mapping (address => uint256) public userSpentPoints; // A map of all external addresses that are permitted to spend user points. mapping (address => bool) public approvedPointSpenders; // Events for depositing assets into the Staker and later withdrawing them. event Deposit(address indexed user, IERC20 indexed token, uint256 amount); event Withdraw(address indexed user, IERC20 indexed token, uint256 amount); // An event for tracking when a user has spent points. event SpentPoints(address indexed source, address indexed user, uint256 amount); /** Construct a new Staker by providing it a name and the token to disburse. @param _name The name of the Staker contract. @param _token The token to reward stakers in this contract with. */ constructor(string memory _name, IERC20 _token) public { name = _name; token = _token; token.approve(address(this), MAX_INT); canAlterDevelopers = true; canAlterTokenEmissionSchedule = true; earliestTokenEmissionBlock = MAX_INT; canAlterPointEmissionSchedule = true; earliestPointEmissionBlock = MAX_INT; } /** Add a new developer to the Staker or overwrite an existing one. This operation requires that developer address addition is not locked. @param _developerAddress The additional developer's address. @param _share The share in 1/1000th of a percent of each token emission sent to this new developer. */ function addDeveloper(address _developerAddress, uint256 _share) external onlyOwner { require(canAlterDevelopers, "This Staker has locked the addition of developers; no more may be added."); developerAddresses.push(_developerAddress); developerShares[_developerAddress] = _share; } /** Permanently forfeits owner ability to alter the state of Staker developers. Once called, this function is intended to give peace of mind to the Staker's developers and community that the fee structure is now immutable. */ function lockDevelopers() external onlyOwner { canAlterDevelopers = false; } /** A developer may at any time update their address or voluntarily reduce their share of emissions by calling this function from their current address. Note that updating a developer's share to zero effectively removes them. @param _newDeveloperAddress An address to update this developer's address. @param _newShare The new share in 1/1000th of a percent of each token emission sent to this developer. */ function updateDeveloper(address _newDeveloperAddress, uint256 _newShare) external { uint256 developerShare = developerShares[msg.sender]; require(developerShare > 0, "You are not a developer of this Staker."); require(_newShare <= developerShare, "You cannot increase your developer share."); developerShares[msg.sender] = 0; developerAddresses.push(_newDeveloperAddress); developerShares[_newDeveloperAddress] = _newShare; } /** Set new emission details to the Staker or overwrite existing ones. This operation requires that emission schedule alteration is not locked. @param _tokenSchedule An array of EmissionPoints defining the token schedule. @param _pointSchedule An array of EmissionPoints defining the point schedule. */ function setEmissions(EmissionPoint[] memory _tokenSchedule, EmissionPoint[] memory _pointSchedule) external onlyOwner { if (_tokenSchedule.length > 0) { require(canAlterTokenEmissionSchedule, "This Staker has locked the alteration of token emissions."); tokenEmissionBlockCount = _tokenSchedule.length; for (uint256 i = 0; i < tokenEmissionBlockCount; i++) { tokenEmissionBlocks[i] = _tokenSchedule[i]; if (earliestTokenEmissionBlock > _tokenSchedule[i].blockNumber) { earliestTokenEmissionBlock = _tokenSchedule[i].blockNumber; } } } require(tokenEmissionBlockCount > 0, "You must set the token emission schedule."); if (_pointSchedule.length > 0) { require(canAlterPointEmissionSchedule, "This Staker has locked the alteration of point emissions."); pointEmissionBlockCount = _pointSchedule.length; for (uint256 i = 0; i < pointEmissionBlockCount; i++) { pointEmissionBlocks[i] = _pointSchedule[i]; if (earliestPointEmissionBlock > _pointSchedule[i].blockNumber) { earliestPointEmissionBlock = _pointSchedule[i].blockNumber; } } } require(tokenEmissionBlockCount > 0, "You must set the point emission schedule."); } /** Permanently forfeits owner ability to alter the emission schedule. Once called, this function is intended to give peace of mind to the Staker's developers and community that the inflation rate is now immutable. */ function lockTokenEmissions() external onlyOwner { canAlterTokenEmissionSchedule = false; } /** Permanently forfeits owner ability to alter the emission schedule. Once called, this function is intended to give peace of mind to the Staker's developers and community that the inflation rate is now immutable. */ function lockPointEmissions() external onlyOwner { canAlterPointEmissionSchedule = false; } /** Returns the length of the developer address array. @return the length of the developer address array. */ function getDeveloperCount() external view returns (uint256) { return developerAddresses.length; } /** Returns the length of the staking pool array. @return the length of the staking pool array. */ function getPoolCount() external view returns (uint256) { return poolTokens.length; } /** Returns the amount of token that has not been disbursed by the Staker yet. @return the amount of token that has not been disbursed by the Staker yet. */ function getRemainingToken() external view returns (uint256) { return token.balanceOf(address(this)); } /** Allows the contract owner to add a new asset pool to the Staker or overwrite an existing one. @param _token The address of the asset to base this staking pool off of. @param _tokenStrength The relative strength of the new asset for earning token. @param _pointStrength The relative strength of the new asset for earning points. */ function addPool(IERC20 _token, uint256 _tokenStrength, uint256 _pointStrength) external onlyOwner { require(tokenEmissionBlockCount > 0 && pointEmissionBlockCount > 0, "Staking pools cannot be addded until an emission schedule has been defined."); uint256 lastTokenRewardBlock = block.number > earliestTokenEmissionBlock ? block.number : earliestTokenEmissionBlock; uint256 lastPointRewardBlock = block.number > earliestPointEmissionBlock ? block.number : earliestPointEmissionBlock; uint256 lastRewardBlock = lastTokenRewardBlock > lastPointRewardBlock ? lastTokenRewardBlock : lastPointRewardBlock; if (address(poolInfo[_token].token) == address(0)) { poolTokens.push(_token); totalTokenStrength = totalTokenStrength.add(_tokenStrength); totalPointStrength = totalPointStrength.add(_pointStrength); poolInfo[_token] = PoolInfo({ token: _token, tokenStrength: _tokenStrength, tokensPerShare: 0, pointStrength: _pointStrength, pointsPerShare: 0, lastRewardBlock: lastRewardBlock }); } else { totalTokenStrength = totalTokenStrength.sub(poolInfo[_token].tokenStrength).add(_tokenStrength); poolInfo[_token].tokenStrength = _tokenStrength; totalPointStrength = totalPointStrength.sub(poolInfo[_token].pointStrength).add(_pointStrength); poolInfo[_token].pointStrength = _pointStrength; } } /** Uses the emission schedule to calculate the total amount of staking reward token that was emitted between two specified block numbers. @param _fromBlock The block to begin calculating emissions from. @param _toBlock The block to calculate total emissions up to. */ function getTotalEmittedTokens(uint256 _fromBlock, uint256 _toBlock) public view returns (uint256) { require(_toBlock >= _fromBlock, "Tokens cannot be emitted from a higher block to a lower block."); uint256 totalEmittedTokens = 0; uint256 workingRate = 0; uint256 workingBlock = _fromBlock; for (uint256 i = 0; i < tokenEmissionBlockCount; ++i) { uint256 emissionBlock = tokenEmissionBlocks[i].blockNumber; uint256 emissionRate = tokenEmissionBlocks[i].rate; if (_toBlock < emissionBlock) { totalEmittedTokens = totalEmittedTokens.add(_toBlock.sub(workingBlock).mul(workingRate)); return totalEmittedTokens; } else if (workingBlock < emissionBlock) { totalEmittedTokens = totalEmittedTokens.add(emissionBlock.sub(workingBlock).mul(workingRate)); workingBlock = emissionBlock; } workingRate = emissionRate; } if (workingBlock < _toBlock) { totalEmittedTokens = totalEmittedTokens.add(_toBlock.sub(workingBlock).mul(workingRate)); } return totalEmittedTokens; } /** Uses the emission schedule to calculate the total amount of points emitted between two specified block numbers. @param _fromBlock The block to begin calculating emissions from. @param _toBlock The block to calculate total emissions up to. */ function getTotalEmittedPoints(uint256 _fromBlock, uint256 _toBlock) public view returns (uint256) { require(_toBlock >= _fromBlock, "Points cannot be emitted from a higher block to a lower block."); uint256 totalEmittedPoints = 0; uint256 workingRate = 0; uint256 workingBlock = _fromBlock; for (uint256 i = 0; i < pointEmissionBlockCount; ++i) { uint256 emissionBlock = pointEmissionBlocks[i].blockNumber; uint256 emissionRate = pointEmissionBlocks[i].rate; if (_toBlock < emissionBlock) { totalEmittedPoints = totalEmittedPoints.add(_toBlock.sub(workingBlock).mul(workingRate)); return totalEmittedPoints; } else if (workingBlock < emissionBlock) { totalEmittedPoints = totalEmittedPoints.add(emissionBlock.sub(workingBlock).mul(workingRate)); workingBlock = emissionBlock; } workingRate = emissionRate; } if (workingBlock < _toBlock) { totalEmittedPoints = totalEmittedPoints.add(_toBlock.sub(workingBlock).mul(workingRate)); } return totalEmittedPoints; } /** Update the pool corresponding to the specified token address. @param _token The address of the asset to update the corresponding pool for. */ function updatePool(IERC20 _token) internal { PoolInfo storage pool = poolInfo[_token]; if (block.number <= pool.lastRewardBlock) { return; } uint256 poolTokenSupply = pool.token.balanceOf(address(this)); if (address(_token) == address(token)) { poolTokenSupply = totalTokenDeposited; } if (poolTokenSupply <= 0) { pool.lastRewardBlock = block.number; return; } // Calculate tokens and point rewards for this pool. uint256 totalEmittedTokens = getTotalEmittedTokens(pool.lastRewardBlock, block.number); uint256 tokensReward = totalEmittedTokens.mul(pool.tokenStrength).div(totalTokenStrength).mul(1e12); uint256 totalEmittedPoints = getTotalEmittedPoints(pool.lastRewardBlock, block.number); uint256 pointsReward = totalEmittedPoints.mul(pool.pointStrength).div(totalPointStrength).mul(1e30); // Directly pay developers their corresponding share of tokens and points. for (uint256 i = 0; i < developerAddresses.length; ++i) { address developer = developerAddresses[i]; uint256 share = developerShares[developer]; uint256 devTokens = tokensReward.mul(share).div(100000); tokensReward = tokensReward - devTokens; uint256 devPoints = pointsReward.mul(share).div(100000); pointsReward = pointsReward - devPoints; token.safeTransferFrom(address(this), developer, devTokens.div(1e12)); userPoints[developer] = userPoints[developer].add(devPoints.div(1e30)); } // Update the pool rewards per share to pay users the amount remaining. pool.tokensPerShare = pool.tokensPerShare.add(tokensReward.div(poolTokenSupply)); pool.pointsPerShare = pool.pointsPerShare.add(pointsReward.div(poolTokenSupply)); pool.lastRewardBlock = block.number; } /** A function to easily see the amount of token rewards pending for a user on a given pool. Returns the pending reward token amount. @param _token The address of a particular staking pool asset to check for a pending reward. @param _user The user address to check for a pending reward. @return the pending reward token amount. */ function getPendingTokens(IERC20 _token, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_token]; UserInfo storage user = userInfo[_token][_user]; uint256 tokensPerShare = pool.tokensPerShare; uint256 poolTokenSupply = pool.token.balanceOf(address(this)); if (address(_token) == address(token)) { poolTokenSupply = totalTokenDeposited; } if (block.number > pool.lastRewardBlock && poolTokenSupply > 0) { uint256 totalEmittedTokens = getTotalEmittedTokens(pool.lastRewardBlock, block.number); uint256 tokensReward = totalEmittedTokens.mul(pool.tokenStrength).div(totalTokenStrength).mul(1e12); tokensPerShare = tokensPerShare.add(tokensReward.div(poolTokenSupply)); } return user.amount.mul(tokensPerShare).div(1e12).sub(user.tokenPaid); } /** A function to easily see the amount of point rewards pending for a user on a given pool. Returns the pending reward point amount. @param _token The address of a particular staking pool asset to check for a pending reward. @param _user The user address to check for a pending reward. @return the pending reward token amount. */ function getPendingPoints(IERC20 _token, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_token]; UserInfo storage user = userInfo[_token][_user]; uint256 pointsPerShare = pool.pointsPerShare; uint256 poolTokenSupply = pool.token.balanceOf(address(this)); if (address(_token) == address(token)) { poolTokenSupply = totalTokenDeposited; } if (block.number > pool.lastRewardBlock && poolTokenSupply > 0) { uint256 totalEmittedPoints = getTotalEmittedPoints(pool.lastRewardBlock, block.number); uint256 pointsReward = totalEmittedPoints.mul(pool.pointStrength).div(totalPointStrength).mul(1e30); pointsPerShare = pointsPerShare.add(pointsReward.div(poolTokenSupply)); } return user.amount.mul(pointsPerShare).div(1e30).sub(user.pointPaid); } /** Return the number of points that the user has available to spend. @return the number of points that the user has available to spend. */ function getAvailablePoints(address _user) public view returns (uint256) { uint256 concreteTotal = userPoints[_user]; uint256 pendingTotal = 0; for (uint256 i = 0; i < poolTokens.length; ++i) { IERC20 poolToken = poolTokens[i]; uint256 _pendingPoints = getPendingPoints(poolToken, _user); pendingTotal = pendingTotal.add(_pendingPoints); } uint256 spentTotal = userSpentPoints[_user]; return concreteTotal.add(pendingTotal).sub(spentTotal); } /** Return the total number of points that the user has ever accrued. @return the total number of points that the user has ever accrued. */ function getTotalPoints(address _user) external view returns (uint256) { uint256 concreteTotal = userPoints[_user]; uint256 pendingTotal = 0; for (uint256 i = 0; i < poolTokens.length; ++i) { IERC20 poolToken = poolTokens[i]; uint256 _pendingPoints = getPendingPoints(poolToken, _user); pendingTotal = pendingTotal.add(_pendingPoints); } return concreteTotal.add(pendingTotal); } /** Return the total number of points that the user has ever spent. @return the total number of points that the user has ever spent. */ function getSpentPoints(address _user) external view returns (uint256) { return userSpentPoints[_user]; } /** Deposit some particular assets to a particular pool on the Staker. @param _token The asset to stake into its corresponding pool. @param _amount The amount of the provided asset to stake. */ function deposit(IERC20 _token, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_token]; require(pool.tokenStrength > 0 || pool.pointStrength > 0, "You cannot deposit assets into an inactive pool."); UserInfo storage user = userInfo[_token][msg.sender]; updatePool(_token); if (user.amount > 0) { uint256 pendingTokens = user.amount.mul(pool.tokensPerShare).div(1e12).sub(user.tokenPaid); token.safeTransferFrom(address(this), msg.sender, pendingTokens); totalTokenDisbursed = totalTokenDisbursed.add(pendingTokens); uint256 pendingPoints = user.amount.mul(pool.pointsPerShare).div(1e30).sub(user.pointPaid); userPoints[msg.sender] = userPoints[msg.sender].add(pendingPoints); } pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); if (address(_token) == address(token)) { totalTokenDeposited = totalTokenDeposited.add(_amount); } user.amount = user.amount.add(_amount); user.tokenPaid = user.amount.mul(pool.tokensPerShare).div(1e12); user.pointPaid = user.amount.mul(pool.pointsPerShare).div(1e30); emit Deposit(msg.sender, _token, _amount); } /** Withdraw some particular assets from a particular pool on the Staker. @param _token The asset to withdraw from its corresponding staking pool. @param _amount The amount of the provided asset to withdraw. */ function withdraw(IERC20 _token, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_token]; UserInfo storage user = userInfo[_token][msg.sender]; require(user.amount >= _amount, "You cannot withdraw that much of the specified token; you are not owed it."); updatePool(_token); uint256 pendingTokens = user.amount.mul(pool.tokensPerShare).div(1e12).sub(user.tokenPaid); token.safeTransferFrom(address(this), msg.sender, pendingTokens); totalTokenDisbursed = totalTokenDisbursed.add(pendingTokens); uint256 pendingPoints = user.amount.mul(pool.pointsPerShare).div(1e30).sub(user.pointPaid); userPoints[msg.sender] = userPoints[msg.sender].add(pendingPoints); if (address(_token) == address(token)) { totalTokenDeposited = totalTokenDeposited.sub(_amount); } user.amount = user.amount.sub(_amount); user.tokenPaid = user.amount.mul(pool.tokensPerShare).div(1e12); user.pointPaid = user.amount.mul(pool.pointsPerShare).div(1e30); pool.token.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _token, _amount); } /** Allows the owner of this Staker to grant or remove approval to an external spender of the points that users accrue from staking resources. @param _spender The external address allowed to spend user points. @param _approval The updated user approval status. */ function approvePointSpender(address _spender, bool _approval) external onlyOwner { approvedPointSpenders[_spender] = _approval; } /** Allows an approved spender of points to spend points on behalf of a user. @param _user The user whose points are being spent. @param _amount The amount of the user's points being spent. */ function spendPoints(address _user, uint256 _amount) external { require(approvedPointSpenders[msg.sender], "You are not permitted to spend user points."); uint256 _userPoints = getAvailablePoints(_user); require(_userPoints >= _amount, "The user does not have enough points to spend the requested amount."); userSpentPoints[_user] = userSpentPoints[_user].add(_amount); emit SpentPoints(msg.sender, _user, _amount); } /** Sweep all of a particular ERC-20 token from the contract. @param _token The token to sweep the balance from. */ function sweep(IERC20 _token) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.safeTransferFrom(address(this), msg.sender, balance); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./Token.sol"; import "./Staker.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Stakers. @author Tim Clancy This is the governing registry of all SuperFarm Staker assets. */ contract FarmStakerRecords is Ownable, ReentrancyGuard { /// A struct used to specify token and pool strengths for adding a pool. struct PoolData { IERC20 poolToken; uint256 tokenStrength; uint256 pointStrength; } /// A version number for this record contract's interface. uint256 public version = 1; /// A mapping for an array of all Stakers deployed by a particular address. mapping (address => address[]) public farmRecords; /// An event for tracking the creation of a new Staker. event FarmCreated(address indexed farmAddress, address indexed creator); /** Create a Staker on behalf of the owner calling this function. The Staker supports immediate specification of the emission schedule and pool strength. @param _name The name of the Staker to create. @param _token The Token to reward stakers in the Staker with. @param _tokenSchedule An array of EmissionPoints defining the token schedule. @param _pointSchedule An array of EmissionPoints defining the point schedule. @param _initialPools An array of pools to initially add to the new Staker. */ function createFarm(string calldata _name, IERC20 _token, Staker.EmissionPoint[] memory _tokenSchedule, Staker.EmissionPoint[] memory _pointSchedule, PoolData[] calldata _initialPools) nonReentrant external returns (Staker) { Staker newStaker = new Staker(_name, _token); // Establish the emissions schedule and add the token pools. newStaker.setEmissions(_tokenSchedule, _pointSchedule); for (uint256 i = 0; i < _initialPools.length; i++) { newStaker.addPool(_initialPools[i].poolToken, _initialPools[i].tokenStrength, _initialPools[i].pointStrength); } // Transfer ownership of the new Staker to the user then store a reference. newStaker.transferOwnership(msg.sender); address stakerAddress = address(newStaker); farmRecords[msg.sender].push(stakerAddress); emit FarmCreated(stakerAddress, msg.sender); return newStaker; } /** Allow a user to add an existing Staker contract to the registry. @param _farmAddress The address of the Staker contract to add for this user. */ function addFarm(address _farmAddress) external { farmRecords[msg.sender].push(_farmAddress); } /** Get the number of entries in the Staker records mapping for the given user. @return The number of Stakers added for a given address. */ function getFarmCount(address _user) external view returns (uint256) { return farmRecords[_user].length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** @title A basic ERC-20 token with voting functionality. @author Tim Clancy This contract is used when deploying SuperFarm ERC-20 tokens. This token is created with a fixed, immutable cap and includes voting rights. Voting functionality is copied and modified from Sushi, and in turn from YAM: https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol Which is in turn copied and modified from COMPOUND: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol */ contract Token is ERC20Capped, Ownable { /// A version number for this Token contract's interface. uint256 public version = 1; /** Construct a new Token by providing it a name, ticker, and supply cap. @param _name The name of the new Token. @param _ticker The ticker symbol of the new Token. @param _cap The supply cap of the new Token. */ constructor (string memory _name, string memory _ticker, uint256 _cap) public ERC20(_name, _ticker) ERC20Capped(_cap) { } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** Allows Token creator to mint `_amount` of this Token to the address `_to`. New tokens of this Token cannot be minted if it would exceed the supply cap. Users are delegated votes when they are minted Token. @param _to the address to mint Tokens to. @param _amount the amount of new Token to mint. */ function mint(address _to, uint256 _amount) external onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** Allows users to transfer tokens to a recipient, moving delegated votes with the transfer. @param recipient The address to transfer tokens to. @param amount The amount of tokens to send to `recipient`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); _moveDelegates(_delegates[msg.sender], _delegates[recipient], amount); return true; } /// @dev A mapping to record delegates for each address. mapping (address => address) internal _delegates; /// A checkpoint structure to mark some number of votes from a given block. struct Checkpoint { uint32 fromBlock; uint256 votes; } /// A mapping to record indexed Checkpoint votes for each address. mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// A mapping to record the number of Checkpoints for each address. mapping (address => uint32) public numCheckpoints; /// The EIP-712 typehash for the contract's domain. bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// The EIP-712 typehash for the delegation struct used by the contract. bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// A mapping to record per-address states for signing / validating signatures. mapping (address => uint) public nonces; /// An event emitted when an address changes its delegate. event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// An event emitted when the vote balance of a delegated address changes. event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** Return the address delegated to by `delegator`. @return The address delegated to by `delegator`. */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** Delegate votes from `msg.sender` to `delegatee`. @param delegatee The address to delegate votes to. */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** Delegate votes from signatory to `delegatee`. @param delegatee The address to delegate votes to. @param nonce The contract state required for signature matching. @param expiry The time at which to expire the signature. @param v The recovery byte of the signature. @param r Half of the ECDSA signature pair. @param s Half of the ECDSA signature pair. */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Invalid signature."); require(nonce == nonces[signatory]++, "Invalid nonce."); require(now <= expiry, "Signature expired."); return _delegate(signatory, delegatee); } /** Get the current votes balance for the address `account`. @param account The address to get the votes balance of. @return The number of current votes for `account`. */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** Determine the prior number of votes for an address as of a block number. @dev The block number must be a finalized block or else this function will revert to prevent misinformation. @param account The address to check. @param blockNumber The block number to get the vote balance at. @return The number of votes the account had as of the given block. */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "The specified block is not yet finalized."); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check the most recent balance. if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Then check the implicit zero balance. if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** An internal function to actually perform the delegation of votes. @param delegator The address delegating to `delegatee`. @param delegatee The address receiving delegated votes. */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; /* console.log('a-', currentDelegate, delegator, delegatee); */ emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } /** An internal function to move delegated vote amounts between addresses. @param srcRep the previous representative who received delegated votes. @param dstRep the new representative to receive these delegated votes. @param amount the amount of delegated votes to move between representatives. */ function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { // Decrease the number of votes delegated to the previous representative. if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } // Increase the number of votes delegated to the new representative. if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** An internal function to write a checkpoint of modified vote amounts. This function is guaranteed to add at most one checkpoint per block. @param delegatee The address whose vote count is changed. @param nCheckpoints The number of checkpoints by address `delegatee`. @param oldVotes The prior vote count of address `delegatee`. @param newVotes The new vote count of address `delegatee`. */ function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal { uint32 blockNumber = safe32(block.number, "Block number exceeds 32 bits."); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** A function to safely limit a number to less than 2^32. @param n the number to limit. @param errorMessage the error message to revert with should `n` be too large. @return The number `n` limited to 32 bits. */ function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** A function to return the ID of the contract's particular network or chain. @return The ID of the contract's network or chain. */ function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20Capped is ERC20 { using SafeMath for uint256; uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap_) internal { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= cap(), "ERC20Capped: cap exceeded"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./Token.sol"; /** @title A vault for securely holding tokens. @author Tim Clancy The purpose of this contract is to hold a single type of ERC-20 token securely behind a Compound Timelock governed by a Gnosis MultiSigWallet. Tokens may only leave the vault with multisignature permission and after passing through a mandatory timelock. The justification for the timelock is such that, if the multisignature wallet is ever compromised, the team will have two days to act in mitigating the potential damage from the attacker's `sentTokens` call. Such mitigation efforts may include calling `panic` from a separate, uncompromised and non-timelocked multisignature wallet, or finding some way to issue a new token entirely. */ contract TokenVault is Ownable, ReentrancyGuard { using SafeMath for uint256; /// A version number for this TokenVault contract's interface. uint256 public version = 1; /// A user-specified, descriptive name for this TokenVault. string public name; /// The token to hold safe. Token public token; /** The panic owner is an optional address allowed to immediately send the contents of the vault to the address specified in `panicDestination`. The intention of this system is to support a series of cascading vaults secured by their own multisignature wallets. If, for instance, vault one is compromised via its attached multisignature wallet, vault two could intercede to save the tokens from vault one before the malicious token send clears the owning timelock. */ address public panicOwner; /// An optional address where tokens may be immediately sent by `panicOwner`. address public panicDestination; /** A counter to limit the number of times a vault can panic before burning the underlying supply of tokens. This limit is in place to protect against a situation where multiple vaults linked in a circle are all compromised. In the event of such an attack, this still gives the original multisignature holders the chance to burn the tokens by repeatedly calling `panic` before the attacker can use `sendTokens`. */ uint256 public panicLimit; /// A counter for the number of times this vault has panicked. uint256 public panicCounter; /// A flag to determine whether or not this vault can alter its `panicOwner` and `panicDestination`. bool public canAlterPanicDetails; /// An event for tracking a change in panic details. event PanicDetailsChange(address indexed panicOwner, address indexed panicDestination); /// An event for tracking a lock on alteration of panic details. event PanicDetailsLocked(); /// An event for tracking a disbursement of tokens. event TokenSend(uint256 tokenAmount); /// An event for tracking a panic transfer of tokens. event PanicTransfer(uint256 panicCounter, uint256 tokenAmount, address indexed destination); /// An event for tracking a panic burn of tokens. event PanicBurn(uint256 panicCounter, uint256 tokenAmount); /// @dev a modifier which allows only `panicOwner` to call a function. modifier onlyPanicOwner() { require(panicOwner == _msgSender(), "TokenVault: caller is not the panic owner"); _; } /** Construct a new TokenVault by providing it a name and the token to disburse. @param _name The name of the TokenVault. @param _token The token to store and disburse. @param _panicOwner The address to grant emergency withdrawal powers to. @param _panicDestination The destination to withdraw to in emergency. @param _panicLimit A limit for the number of times `panic` can be called before tokens burn. */ constructor(string memory _name, Token _token, address _panicOwner, address _panicDestination, uint256 _panicLimit) public { name = _name; token = _token; panicOwner = _panicOwner; panicDestination = _panicDestination; panicLimit = _panicLimit; panicCounter = 0; canAlterPanicDetails = true; uint256 MAX_INT = 2**256 - 1; token.approve(address(this), MAX_INT); } /** Allows the owner of the TokenVault to update the `panicOwner` and `panicDestination` details governing its panic functionality. @param _panicOwner The new panic owner to set. @param _panicDestination The new emergency destination to send tokens to. */ function changePanicDetails(address _panicOwner, address _panicDestination) external nonReentrant onlyOwner { require(canAlterPanicDetails, "You cannot change panic details on a vault which is locked."); panicOwner = _panicOwner; panicDestination = _panicDestination; emit PanicDetailsChange(panicOwner, panicDestination); } /** Allows the owner of the TokenVault to lock the vault to all future panic detail changes. */ function lock() external nonReentrant onlyOwner { canAlterPanicDetails = false; emit PanicDetailsLocked(); } /** Allows the TokenVault owner to send tokens out of the vault. @param _recipients The array of addresses to receive tokens. @param _amounts The array of amounts sent to each address in `_recipients`. */ function sendTokens(address[] calldata _recipients, uint256[] calldata _amounts) external nonReentrant onlyOwner { require(_recipients.length > 0, "You must send tokens to at least one recipient."); require(_recipients.length == _amounts.length, "Recipients length cannot be mismatched with amounts length."); // Iterate through every specified recipient and send tokens. uint256 totalAmount = 0; for (uint256 i = 0; i < _recipients.length; i++) { address recipient = _recipients[i]; uint256 amount = _amounts[i]; token.transfer(recipient, amount); totalAmount = totalAmount.add(amount); } emit TokenSend(totalAmount); } /** Allow the TokenVault's `panicOwner` to immediately send its contents to a predefined `panicDestination`. This can be used to circumvent the timelock in case of an emergency. */ function panic() external nonReentrant onlyPanicOwner { uint256 totalBalance = token.balanceOf(address(this)); // If the panic limit is reached, burn the tokens. if (panicCounter == panicLimit) { token.burn(totalBalance); emit PanicBurn(panicCounter, totalBalance); // Otherwise, drain the vault to the panic destination. } else { if (panicDestination == address(0)) { token.burn(totalBalance); emit PanicBurn(panicCounter, totalBalance); } else { token.transfer(panicDestination, totalBalance); emit PanicTransfer(panicCounter, totalBalance, panicDestination); } panicCounter = panicCounter.add(1); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title A token vesting contract for streaming claims. @author SuperFarm This vesting contract allows users to claim vested tokens with every block. */ contract VestStream is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint64; using SafeERC20 for IERC20; /// The token to disburse in vesting. IERC20 public token; // Information for a particular token claim. // - totalAmount: the total size of the token claim. // - startTime: the timestamp in seconds when the vest begins. // - endTime: the timestamp in seconds when the vest completely matures. // - lastCLaimTime: the timestamp in seconds of the last time the claim was utilized. // - amountClaimed: the total amount claimed from the entire claim. struct Claim { uint256 totalAmount; uint64 startTime; uint64 endTime; uint64 lastClaimTime; uint256 amountClaimed; } // A mapping of addresses to the claim received. mapping(address => Claim) private claims; /// An event for tracking the creation of a token vest claim. event ClaimCreated(address creator, address beneficiary); /// An event for tracking a user claiming some of their vested tokens. event Claimed(address beneficiary, uint256 amount); /** Construct a new VestStream by providing it a token to disburse. @param _token The token to vest to claimants in this contract. */ constructor(IERC20 _token) public { token = _token; uint256 MAX_INT = 2**256 - 1; token.approve(address(this), MAX_INT); } /** A function which allows the caller to retrieve information about a specific claim via its beneficiary. @param beneficiary the beneficiary to query claims for. */ function getClaim(address beneficiary) external view returns (Claim memory) { require(beneficiary != address(0), "The zero address may not be a claim beneficiary."); return claims[beneficiary]; } /** A function which allows the caller to retrieve information about a specific claim's remaining claimable amount. @param beneficiary the beneficiary to query claims for. */ function claimableAmount(address beneficiary) public view returns (uint256) { Claim memory claim = claims[beneficiary]; // Early-out if the claim has not started yet. if (claim.startTime == 0 || block.timestamp < claim.startTime) { return 0; } // Calculate the current releasable token amount. uint64 currentTimestamp = uint64(block.timestamp) > claim.endTime ? claim.endTime : uint64(block.timestamp); uint256 claimPercent = currentTimestamp.sub(claim.startTime).mul(1e18).div(claim.endTime.sub(claim.startTime)); uint256 claimAmount = claim.totalAmount.mul(claimPercent).div(1e18); // Reduce the unclaimed amount by the amount already claimed. uint256 unclaimedAmount = claimAmount.sub(claim.amountClaimed); return unclaimedAmount; } /** Sweep all of a particular ERC-20 token from the contract. @param _token The token to sweep the balance from. */ function sweep(IERC20 _token) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.safeTransferFrom(address(this), msg.sender, balance); } /** A function which allows the caller to create toke vesting claims for some beneficiaries. The disbursement token will be taken from the claim creator. @param _beneficiaries an array of addresses to construct token claims for. @param _totalAmounts the total amount of tokens to be disbursed to each beneficiary. @param _startTime a timestamp when this claim is to begin vesting. @param _endTime a timestamp when this claim is to reach full maturity. */ function createClaim(address[] memory _beneficiaries, uint256[] memory _totalAmounts, uint64 _startTime, uint64 _endTime) external onlyOwner { require(_beneficiaries.length > 0, "You must specify at least one beneficiary for a claim."); require(_beneficiaries.length == _totalAmounts.length, "Beneficiaries and their amounts may not be mismatched."); require(_endTime >= _startTime, "You may not create a claim which ends before it starts."); // After validating the details for this token claim, initialize a claim for // each specified beneficiary. for (uint i = 0; i < _beneficiaries.length; i++) { address _beneficiary = _beneficiaries[i]; uint256 _totalAmount = _totalAmounts[i]; require(_beneficiary != address(0), "The zero address may not be a beneficiary."); require(_totalAmount > 0, "You may not create a zero-token claim."); // Establish a claim for this particular beneficiary. Claim memory claim = Claim({ totalAmount: _totalAmount, startTime: _startTime, endTime: _endTime, lastClaimTime: _startTime, amountClaimed: 0 }); claims[_beneficiary] = claim; emit ClaimCreated(msg.sender, _beneficiary); } } /** A function which allows the caller to send a claim's unclaimed amount to the beneficiary of the claim. @param beneficiary the beneficiary to claim for. */ function claim(address beneficiary) external nonReentrant { Claim memory _claim = claims[beneficiary]; // Verify that the claim is still active. require(_claim.lastClaimTime < _claim.endTime, "This claim has already been completely claimed."); // Calculate the current releasable token amount. uint64 currentTimestamp = uint64(block.timestamp) > _claim.endTime ? _claim.endTime : uint64(block.timestamp); uint256 claimPercent = currentTimestamp.sub(_claim.startTime).mul(1e18).div(_claim.endTime.sub(_claim.startTime)); uint256 claimAmount = _claim.totalAmount.mul(claimPercent).div(1e18); // Reduce the unclaimed amount by the amount already claimed. uint256 unclaimedAmount = claimAmount.sub(_claim.amountClaimed); // Transfer the unclaimed tokens to the beneficiary. token.safeTransferFrom(address(this), beneficiary, unclaimedAmount); // Update the amount currently claimed by the user. _claim.amountClaimed = claimAmount; // Update the last time the claim was utilized. _claim.lastClaimTime = currentTimestamp; // Update the claim structure being tracked. claims[beneficiary] = _claim; // Emit an event for this token claim. emit Claimed(beneficiary, unclaimedAmount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title An OpenSea mock proxy contract which we use to test whitelisting. @author OpenSea */ contract MockProxyRegistry is Ownable { using SafeMath for uint256; /// A mapping of testing proxies. mapping(address => address) public proxies; /** Allow the registry owner to set a proxy on behalf of an address. @param _address The address that the proxy will act on behalf of. @param _proxyForAddress The proxy that will act on behalf of the address. */ function setProxy(address _address, address _proxyForAddress) external onlyOwner { proxies[_address] = _proxyForAddress; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; /** @title A simple Shop contract for selling ERC-1155s for Ether via direct minting. @author Tim Clancy This contract is a limited subset of the Shop1155 contract designed to mint items directly to the user upon purchase. */ contract ShopEtherMinter1155 is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 1; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A user-specified Fee1155 contract to support selling items from. Fee1155 public item; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// The Shop's inventory of item groups for sale. uint256[] public inventory; /// The Shop's price for each item group. mapping (uint256 => uint256) public prices; /** Construct a new Shop by providing it a FeeOwner. @param _item The address of the Fee1155 item that will be minting sales. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. */ constructor(Fee1155 _item, FeeOwner _feeOwner) public { item = _item; feeOwner = _feeOwner; } /** Returns the length of the inventory array. @return the length of the inventory array. */ function getInventoryCount() external view returns (uint256) { return inventory.length; } /** Allows the Shop owner to list a new set of NFT items for sale. @param _groupIds The item group IDs to list for sale in this shop. @param _prices The corresponding purchase price to mint an item of each group. */ function listItems(uint256[] calldata _groupIds, uint256[] calldata _prices) external onlyOwner { require(_groupIds.length > 0, "You must list at least one item."); require(_groupIds.length == _prices.length, "Items length cannot be mismatched with prices length."); // Iterate through every specified item group to list items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; uint256 price = _prices[i]; inventory.push(groupId); prices[groupId] = price; } } /** Allows the Shop owner to remove items from sale. @param _groupIds The group IDs currently listed in the shop to take off sale. */ function removeItems(uint256[] calldata _groupIds) external onlyOwner { require(_groupIds.length > 0, "You must remove at least one item."); // Iterate through every specified item group to remove items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; prices[groupId] = 0; } } /** Allows any user to purchase items from this Shop. Users supply specfic item IDs within the groups listed for sale and supply the corresponding amount of Ether to cover the purchase prices. @param _itemIds The specific item IDs to purchase from this shop. */ function purchaseItems(uint256[] calldata _itemIds) public nonReentrant payable { require(_itemIds.length > 0, "You must purchase at least one item."); // Iterate through every specified item to list items. uint256 feePercent = feeOwner.fee(); uint256 itemRoyaltyPercent = item.feeOwner().fee(); for (uint256 i = 0; i < _itemIds.length; i++) { uint256 itemId = _itemIds[i]; uint256 groupId = itemId & GROUP_MASK; uint256 price = prices[groupId]; require(price > 0, "You cannot purchase an item that is not listed."); // Split fees for this purchase. uint256 feeValue = price.mul(feePercent).div(100000); uint256 royaltyValue = price.mul(itemRoyaltyPercent).div(100000); (bool success, ) = payable(feeOwner.owner()).call{ value: feeValue }(""); require(success, "Platform fee transfer failed."); (success, ) = payable(item.feeOwner().owner()).call{ value: royaltyValue }(""); require(success, "Creator royalty transfer failed."); (success, ) = payable(owner()).call{ value: price.sub(feeValue).sub(royaltyValue) }(""); require(success, "Shop owner transfer failed."); // Mint the item. item.mint(msg.sender, itemId, 1, ""); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // TRUFFLE import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract SuperVestCliff { using SafeMath for uint256; using Address for address; address public tokenAddress; event Claimed( address owner, address beneficiary, uint256 amount, uint256 index ); event ClaimCreated(address owner, address beneficiary, uint256 index); struct Claim { address owner; address beneficiary; uint256[] timePeriods; uint256[] tokenAmounts; uint256 totalAmount; uint256 amountClaimed; uint256 periodsClaimed; } Claim[] private claims; mapping(address => uint256[]) private _ownerClaims; mapping(address => uint256[]) private _beneficiaryClaims; constructor(address _tokenAddress) public { tokenAddress = _tokenAddress; } /** * Get Owner Claims * * @param owner - Claim Owner Address */ function ownerClaims(address owner) external view returns (uint256[] memory) { require(owner != address(0), "Owner address cannot be 0"); return _ownerClaims[owner]; } /** * Get Beneficiary Claims * * @param beneficiary - Claim Owner Address */ function beneficiaryClaims(address beneficiary) external view returns (uint256[] memory) { require(beneficiary != address(0), "Beneficiary address cannot be 0"); return _beneficiaryClaims[beneficiary]; } /** * Get Amount Claimed * * @param index - Claim Index */ function claimed(uint256 index) external view returns (uint256) { return claims[index].amountClaimed; } /** * Get Total Claim Amount * * @param index - Claim Index */ function totalAmount(uint256 index) external view returns (uint256) { return claims[index].totalAmount; } /** * Get Time Periods of Claim * * @param index - Claim Index */ function timePeriods(uint256 index) external view returns (uint256[] memory) { return claims[index].timePeriods; } /** * Get Token Amounts of Claim * * @param index - Claim Index */ function tokenAmounts(uint256 index) external view returns (uint256[] memory) { return claims[index].tokenAmounts; } /** * Create a Claim - To Vest Tokens to Beneficiary * * @param _beneficiary - Tokens will be claimed by _beneficiary * @param _timePeriods - uint256 Array of Epochs * @param _tokenAmounts - uin256 Array of Amounts to transfer at each time period */ function createClaim( address _beneficiary, uint256[] memory _timePeriods, uint256[] memory _tokenAmounts ) public returns (bool) { require( _timePeriods.length == _tokenAmounts.length, "_timePeriods & _tokenAmounts length mismatch" ); require(tokenAddress.isContract(), "Invalid tokenAddress"); require(_beneficiary != address(0), "Cannot Vest to address 0"); // Calculate total amount uint256 _totalAmount = 0; for (uint256 i = 0; i < _tokenAmounts.length; i++) { _totalAmount = _totalAmount.add(_tokenAmounts[i]); } require(_totalAmount > 0, "Provide Token Amounts to Vest"); require( ERC20(tokenAddress).allowance(msg.sender, address(this)) >= _totalAmount, "Provide token allowance to SuperVestCliff contract" ); // Transfer Tokens to SuperStreamClaim ERC20(tokenAddress).transferFrom( msg.sender, address(this), _totalAmount ); // Create Claim Claim memory claim = Claim({ owner: msg.sender, beneficiary: _beneficiary, timePeriods: _timePeriods, tokenAmounts: _tokenAmounts, totalAmount: _totalAmount, amountClaimed: 0, periodsClaimed: 0 }); claims.push(claim); uint256 index = claims.length - 1; // Map Claim Index to Owner & Beneficiary _ownerClaims[msg.sender].push(index); _beneficiaryClaims[_beneficiary].push(index); emit ClaimCreated(msg.sender, _beneficiary, index); return true; } /** * Claim Tokens * * @param index - Index of the Claim */ function claim(uint256 index) external { Claim storage claim = claims[index]; // Check if msg.sender is the beneficiary require( claim.beneficiary == msg.sender, "Only beneficiary can claim tokens" ); // Check if anything is left to release require( claim.periodsClaimed < claim.timePeriods.length, "Nothing to release" ); // Calculate releasable amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); claim.periodsClaimed = claim.periodsClaimed.add(1); } else { break; } } // If there is any amount to release require(amount > 0, "Nothing to release"); // Transfer Tokens from Owner to Beneficiary ERC20(tokenAddress).transfer(claim.beneficiary, amount); claim.amountClaimed = claim.amountClaimed.add(amount); emit Claimed(claim.owner, claim.beneficiary, amount, index); } /** * Get Amount of tokens that can be claimed * * @param index - Index of the Claim */ function claimableAmount(uint256 index) public view returns (uint256) { Claim storage claim = claims[index]; // Calculate Claimable Amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); } else { break; } } return amount; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // TRUFFLE import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract SuperNFTVestStream { using SafeMath for uint256; using Address for address; address public tokenAddress; address public nftAddress; event Claimed( address owner, uint256 nftId, address beneficiary, uint256 amount, uint256 index ); event ClaimCreated( address owner, uint256 nftId, uint256 totalAmount, uint256 index ); struct Claim { address owner; uint256 nftId; uint256[] timePeriods; uint256[] tokenAmounts; uint256 totalAmount; uint256 amountClaimed; uint256 periodsClaimed; } Claim[] private claims; struct StreamInfo { uint256 startTime; bool notOverflow; uint256 startDiff; uint256 diff; uint256 amountPerBlock; uint256[] _timePeriods; uint256[] _tokenAmounts; } mapping(address => uint256[]) private _ownerClaims; mapping(uint256 => uint256[]) private _nftClaims; constructor(address _tokenAddress, address _nftAddress) public { require( _tokenAddress.isContract(), "_tokenAddress must be a contract address" ); require( _nftAddress.isContract(), "_nftAddress must be a contract address" ); tokenAddress = _tokenAddress; nftAddress = _nftAddress; } /** * Get Owner Claims * * @param owner - Claim Owner Address */ function ownerClaims(address owner) external view returns (uint256[] memory) { require(owner != address(0), "Owner address cannot be 0"); return _ownerClaims[owner]; } /** * Get NFT Claims * * @param nftId - NFT ID */ function nftClaims(uint256 nftId) external view returns (uint256[] memory) { require(nftId != 0, "nftId cannot be 0"); return _nftClaims[nftId]; } /** * Get Amount Claimed * * @param index - Claim Index */ function claimed(uint256 index) external view returns (uint256) { return claims[index].amountClaimed; } /** * Get Total Claim Amount * * @param index - Claim Index */ function totalAmount(uint256 index) external view returns (uint256) { return claims[index].totalAmount; } /** * Get Time Periods of Claim * * @param index - Claim Index */ function timePeriods(uint256 index) external view returns (uint256[] memory) { return claims[index].timePeriods; } /** * Get Token Amounts of Claim * * @param index - Claim Index */ function tokenAmounts(uint256 index) external view returns (uint256[] memory) { return claims[index].tokenAmounts; } /** * Create a Claim - To Vest Tokens to NFT * * @param _nftId - Tokens will be claimed by owner of _nftId * @param _startBlock - Block Number to start vesting from * @param _stopBlock - Block Number to end vesting at (Release all tokens) * @param _totalAmount - Total Amount to be Vested * @param _blockTime - Block Time (used for predicting _timePeriods) */ function createClaim( uint256 _nftId, uint256 _startBlock, uint256 _stopBlock, uint256 _totalAmount, uint256 _blockTime ) external returns (bool) { require(_nftId != 0, "Cannot Vest to NFT 0"); require( _stopBlock > _startBlock, "_stopBlock must be greater than _startBlock" ); require(tokenAddress.isContract(), "Invalid tokenAddress"); require(_totalAmount > 0, "Provide Token Amounts to Vest"); require( ERC20(tokenAddress).allowance(msg.sender, address(this)) >= _totalAmount, "Provide token allowance to SuperNFTVestStream contract" ); // Calculate estimated epoch for _startBlock StreamInfo memory streamInfo = StreamInfo(0, false, 0, 0, 0, new uint256[](0), new uint256[](0)); (streamInfo.notOverflow, streamInfo.startDiff) = _startBlock.trySub( block.number ); if (streamInfo.notOverflow) { // If Not Overflow streamInfo.startTime = block.timestamp.add( _blockTime.mul(streamInfo.startDiff) ); } else { // If Overflow streamInfo.startDiff = block.number.sub(_startBlock); streamInfo.startTime = block.timestamp.sub( _blockTime.mul(streamInfo.startDiff) ); } // Calculate _timePeriods & _tokenAmounts streamInfo.diff = _stopBlock.sub(_startBlock); streamInfo.amountPerBlock = _totalAmount.div(streamInfo.diff); streamInfo._timePeriods = new uint256[](streamInfo.diff); streamInfo._tokenAmounts = new uint256[](streamInfo.diff); streamInfo._timePeriods[0] = streamInfo.startTime; streamInfo._tokenAmounts[0] = streamInfo.amountPerBlock; for (uint256 i = 1; i < streamInfo.diff; i++) { streamInfo._timePeriods[i] = streamInfo._timePeriods[i - 1].add( _blockTime ); streamInfo._tokenAmounts[i] = streamInfo.amountPerBlock; } // Transfer Tokens to SuperVestStream ERC20(tokenAddress).transferFrom( msg.sender, address(this), _totalAmount ); // Create Claim Claim memory claim = Claim({ owner: msg.sender, nftId: _nftId, timePeriods: streamInfo._timePeriods, tokenAmounts: streamInfo._tokenAmounts, totalAmount: _totalAmount, amountClaimed: 0, periodsClaimed: 0 }); claims.push(claim); uint256 index = claims.length - 1; // Map Claim Index to Owner & Beneficiary _ownerClaims[msg.sender].push(index); _nftClaims[_nftId].push(index); emit ClaimCreated(msg.sender, _nftId, _totalAmount, index); return true; } /** * Claim Tokens * * @param index - Index of the Claim */ function claim(uint256 index) external { Claim storage claim = claims[index]; // Check if msg.sender is the owner of the NFT require( msg.sender == ERC721(nftAddress).ownerOf(claim.nftId), "msg.sender must own the NFT" ); // Check if anything is left to release require( claim.periodsClaimed < claim.timePeriods.length, "Nothing to release" ); // Calculate releasable amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); claim.periodsClaimed = claim.periodsClaimed.add(1); } else { break; } } // If there is any amount to release require(amount > 0, "Nothing to release"); // Transfer Tokens from Owner to Beneficiary ERC20(tokenAddress).transfer(msg.sender, amount); claim.amountClaimed = claim.amountClaimed.add(amount); emit Claimed(claim.owner, claim.nftId, msg.sender, amount, index); } /** * Get Amount of tokens that can be claimed * * @param index - Index of the Claim */ function claimableAmount(uint256 index) public view returns (uint256) { Claim storage claim = claims[index]; // Calculate Claimable Amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); } else { break; } } return amount; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../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.6.2 <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.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // TRUFFLE import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract SuperNFTVestCliff { using SafeMath for uint256; using Address for address; address public tokenAddress; address public nftAddress; event Claimed( address owner, uint256 nftId, address beneficiary, uint256 amount, uint256 index ); event ClaimCreated( address owner, uint256 nftId, uint256 totalAmount, uint256 index ); struct Claim { address owner; uint256 nftId; uint256[] timePeriods; uint256[] tokenAmounts; uint256 totalAmount; uint256 amountClaimed; uint256 periodsClaimed; } Claim[] private claims; mapping(address => uint256[]) private _ownerClaims; mapping(uint256 => uint256[]) private _nftClaims; constructor(address _tokenAddress, address _nftAddress) public { require( _tokenAddress.isContract(), "_tokenAddress must be a contract address" ); require( _nftAddress.isContract(), "_nftAddress must be a contract address" ); tokenAddress = _tokenAddress; nftAddress = _nftAddress; } /** * Get Owner Claims * * @param owner - Claim Owner Address */ function ownerClaims(address owner) external view returns (uint256[] memory) { require(owner != address(0), "Owner address cannot be 0"); return _ownerClaims[owner]; } /** * Get NFT Claims * * @param nftId - NFT ID */ function nftClaims(uint256 nftId) external view returns (uint256[] memory) { require(nftId != 0, "nftId cannot be 0"); return _nftClaims[nftId]; } /** * Get Amount Claimed * * @param index - Claim Index */ function claimed(uint256 index) external view returns (uint256) { return claims[index].amountClaimed; } /** * Get Total Claim Amount * * @param index - Claim Index */ function totalAmount(uint256 index) external view returns (uint256) { return claims[index].totalAmount; } /** * Get Time Periods of Claim * * @param index - Claim Index */ function timePeriods(uint256 index) external view returns (uint256[] memory) { return claims[index].timePeriods; } /** * Get Token Amounts of Claim * * @param index - Claim Index */ function tokenAmounts(uint256 index) external view returns (uint256[] memory) { return claims[index].tokenAmounts; } /** * Create a Claim - To Vest Tokens to NFT * * @param _nftId - Tokens will be claimed by owner of _nftId * @param _timePeriods - uint256 Array of Epochs * @param _tokenAmounts - uin256 Array of Amounts to transfer at each time period */ function createClaim( uint256 _nftId, uint256[] memory _timePeriods, uint256[] memory _tokenAmounts ) public returns (bool) { require(_nftId != 0, "Cannot Vest to NFT 0"); require( _timePeriods.length == _tokenAmounts.length, "_timePeriods & _tokenAmounts length mismatch" ); // Calculate total amount uint256 _totalAmount = 0; for (uint256 i = 0; i < _tokenAmounts.length; i++) { _totalAmount = _totalAmount.add(_tokenAmounts[i]); } require(_totalAmount > 0, "Provide Token Amounts to Vest"); require( ERC20(tokenAddress).allowance(msg.sender, address(this)) >= _totalAmount, "Provide token allowance to SuperStreamClaim contract" ); // Transfer Tokens to SuperStreamClaim ERC20(tokenAddress).transferFrom( msg.sender, address(this), _totalAmount ); // Create Claim Claim memory claim = Claim({ owner: msg.sender, nftId: _nftId, timePeriods: _timePeriods, tokenAmounts: _tokenAmounts, totalAmount: _totalAmount, amountClaimed: 0, periodsClaimed: 0 }); claims.push(claim); uint256 index = claims.length.sub(1); // Map Claim Index to Owner & Beneficiary _ownerClaims[msg.sender].push(index); _nftClaims[_nftId].push(index); emit ClaimCreated(msg.sender, _nftId, _totalAmount, index); return true; } /** * Claim Tokens * * @param index - Index of the Claim */ function claim(uint256 index) external { Claim storage claim = claims[index]; // Check if msg.sender is the owner of the NFT require( msg.sender == ERC721(nftAddress).ownerOf(claim.nftId), "msg.sender must own the NFT" ); // Check if anything is left to release require( claim.periodsClaimed < claim.timePeriods.length, "Nothing to release" ); // Calculate releasable amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); claim.periodsClaimed = claim.periodsClaimed.add(1); } else { break; } } // If there is any amount to release require(amount > 0, "Nothing to release"); // Transfer Tokens from Owner to Beneficiary ERC20(tokenAddress).transfer(msg.sender, amount); claim.amountClaimed = claim.amountClaimed.add(amount); emit Claimed(claim.owner, claim.nftId, msg.sender, amount, index); } /** * Get Amount of tokens that can be claimed * * @param index - Index of the Claim */ function claimableAmount(uint256 index) public view returns (uint256) { Claim storage claim = claims[index]; // Calculate Claimable Amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); } else { break; } } return amount; } } pragma solidity ^0.6.2; // REMIX // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/token/ERC721/ERC721.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/token/ERC20/ERC20.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/utils/Counters.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/utils/EnumerableSet.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/math/SafeMath.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/utils/Address.sol"; // TRUFFLE import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; // SuperNFT SMART CONTRACT contract SuperNFT is ERC721 { using EnumerableSet for EnumerableSet.UintSet; using Counters for Counters.Counter; Counters.Counter private _tokenIds; mapping(string => uint8) hashes; /** * Mint + Issue NFT * * @param recipient - NFT will be issued to recipient * @param hash - Artwork IPFS hash * @param data - Artwork URI/Data */ function issueToken( address recipient, string memory hash, string memory data ) public returns (uint256) { require(hashes[hash] != 1); hashes[hash] = 1; _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _mint(recipient, newTokenId); _setTokenURI(newTokenId, data); return newTokenId; } constructor() public ERC721("SUPER NFT", "SNFT") {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ 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 current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; /** @title An OpenSea delegate proxy contract which we include for whitelisting. @author OpenSea */ contract OwnableDelegateProxy { } /** @title An OpenSea proxy registry contract which we include for whitelisting. @author OpenSea */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** @title An ERC-1155 item creation contract which specifies an associated FeeOwner who receives royalties from sales of created items. @author Tim Clancy The fee set by the FeeOwner on this Item is honored by Shop contracts. In addition to the inherited OpenZeppelin dependency, this uses ideas from the original ERC-1155 reference implementation. */ contract Fee1155NFT is ERC1155, Ownable { using SafeMath for uint256; /// A version number for this fee-bearing 1155 item contract's interface. uint256 public version = 1; /// The ERC-1155 URI for looking up item metadata using {id} substitution. string public metadataUri; /// A user-specified FeeOwner to receive a portion of item sale earnings. FeeOwner public feeOwner; /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /// A counter to enforce unique IDs for each item group minted. uint256 public nextItemGroupId; /// This mapping tracks the number of unique items within each item group. mapping (uint256 => uint256) public itemGroupSizes; /// An event for tracking the creation of an item group. event ItemGroupCreated(uint256 itemGroupId, uint256 itemGroupSize, address indexed creator); /** Construct a new ERC-1155 item with an associated FeeOwner fee. @param _uri The metadata URI to perform token ID substitution in. @param _feeOwner The address of a FeeOwner who receives earnings from this item. */ constructor(string memory _uri, FeeOwner _feeOwner, address _proxyRegistryAddress) public ERC1155(_uri) { metadataUri = _uri; feeOwner = _feeOwner; proxyRegistryAddress = _proxyRegistryAddress; nextItemGroupId = 0; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. This function returns true if `_operator` is approved to transfer items owned by `_owner`. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** Allow the item owner to update the metadata URI of this collection. @param _uri The new URI to update to. */ function setURI(string calldata _uri) external onlyOwner { metadataUri = _uri; } /** Create a new NFT item group of a specific size. NFTs within a group share a group ID in the upper 128-bits of their full item ID. Within a group NFTs can be distinguished for the purposes of serializing issue numbers. @param recipient The address to receive all NFTs within the newly-created group. @param groupSize The number of individual NFTs to create within the group. @param data Any associated data to use on items minted in this transaction. */ function createNFT(address recipient, uint256 groupSize, bytes calldata data) external onlyOwner returns (uint256) { require(groupSize > 0, "You cannot create an empty item group."); // Create an item group of requested size using the next available ID. uint256 shiftedGroupId = nextItemGroupId << 128; itemGroupSizes[shiftedGroupId] = groupSize; // Record the supply cap of each item being created in the group. uint256[] memory itemIds = new uint256[](groupSize); uint256[] memory amounts = new uint256[](groupSize); for (uint256 i = 1; i <= groupSize; i++) { itemIds[i - 1] = shiftedGroupId.add(i); amounts[i - 1] = 1; } // Mint the entire batch of items. _mintBatch(recipient, itemIds, amounts, data); // Increment our next item group ID and return our created item group ID. nextItemGroupId = nextItemGroupId.add(1); emit ItemGroupCreated(shiftedGroupId, groupSize, msg.sender); return shiftedGroupId; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; import "./Staker.sol"; /** @title A simple Shop contract for selling ERC-1155s for points, Ether, or ERC-20 tokens. @author Tim Clancy This contract allows its owner to list NFT items for sale. NFT items are purchased by users using points spent on a corresponding Staker contract. The Shop must be approved by the owner of the Staker contract. */ contract Shop1155 is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 1; /// A user-specified, descriptive name for this Shop. string public name; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// A user-specified Staker contract to spend user points on. Staker[] public stakers; /** This struct tracks information about a single asset with associated price that an item is being sold in the shop for. @param assetType A sentinel value for the specific type of asset being used. 0 = non-transferrable points from a Staker; see `asset`. 1 = Ether. 2 = an ERC-20 token, see `asset`. @param asset Some more specific information about the asset to charge in. If the `assetType` is 0, we convert the given address to an integer index for finding a specific Staker from `stakers`. If the `assetType` is 1, we ignore this field. If the `assetType` is 2, we use this address to find the ERC-20 token that we should be specifically charging with. @param price The amount of the specified `assetType` and `asset` to charge. */ struct PricePair { uint256 assetType; address asset; uint256 price; } /** This struct tracks information about each item of inventory in the Shop. @param token The address of a Fee1155 collection contract containing the item we want to sell. @param id The specific ID of the item within the Fee1155 from `token`. @param amount The amount of this specific item on sale in the Shop. */ struct ShopItem { Fee1155 token; uint256 id; uint256 amount; } // The Shop's inventory of items for sale. uint256 nextItemId; mapping (uint256 => ShopItem) public inventory; mapping (uint256 => uint256) public pricePairLengths; mapping (uint256 => mapping (uint256 => PricePair)) public prices; /** Construct a new Shop by providing it a name, FeeOwner, optional Stakers. Any attached Staker contracts must also approve this Shop to spend points. @param _name The name of the Shop contract. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. @param _stakers The addresses of any Stakers to permit spending points from. */ constructor(string memory _name, FeeOwner _feeOwner, Staker[] memory _stakers) public { name = _name; feeOwner = _feeOwner; stakers = _stakers; nextItemId = 0; } /** Returns the length of the Staker array. @return the length of the Staker array. */ function getStakerCount() external view returns (uint256) { return stakers.length; } /** Returns the number of items in the Shop's inventory. @return the number of items in the Shop's inventory. */ function getInventoryCount() external view returns (uint256) { return nextItemId; } /** Allows the Shop owner to add newly-supported Stakers for point spending. @param _stakers The array of new Stakers to add. */ function addStakers(Staker[] memory _stakers) external onlyOwner { for (uint256 i = 0; i < _stakers.length; i++) { stakers.push(_stakers[i]); } } /** Allows the Shop owner to list a new set of NFT items for sale. @param _pricePairs The asset address to price pairings to use for selling each item. @param _items The array of Fee1155 item contracts to sell from. @param _ids The specific Fee1155 item IDs to sell. @param _amounts The amount of inventory being listed for each item. */ function listItems(PricePair[] memory _pricePairs, Fee1155[] calldata _items, uint256[][] calldata _ids, uint256[][] calldata _amounts) external nonReentrant onlyOwner { require(_items.length > 0, "You must list at least one item."); require(_items.length == _ids.length, "Items length cannot be mismatched with IDs length."); require(_items.length == _amounts.length, "Items length cannot be mismatched with amounts length."); // Iterate through every specified Fee1155 contract to list items. for (uint256 i = 0; i < _items.length; i++) { Fee1155 item = _items[i]; uint256[] memory ids = _ids[i]; uint256[] memory amounts = _amounts[i]; require(ids.length > 0, "You must specify at least one item ID."); require(ids.length == amounts.length, "Item IDs length cannot be mismatched with amounts length."); // For each Fee1155 contract, add the requested item IDs to the Shop. for (uint256 j = 0; j < ids.length; j++) { uint256 id = ids[j]; uint256 amount = amounts[j]; require(amount > 0, "You cannot list an item with no starting amount."); inventory[nextItemId + j] = ShopItem({ token: item, id: id, amount: amount }); for (uint k = 0; k < _pricePairs.length; k++) { prices[nextItemId + j][k] = _pricePairs[k]; } pricePairLengths[nextItemId + j] = _pricePairs.length; } nextItemId = nextItemId.add(ids.length); // Batch transfer the listed items to the Shop contract. item.safeBatchTransferFrom(msg.sender, address(this), ids, amounts, ""); } } /** Allows the Shop owner to remove items. @param _itemId The id of the specific inventory item of this shop to remove. @param _amount The amount of the specified item to remove. */ function removeItem(uint256 _itemId, uint256 _amount) external nonReentrant onlyOwner { ShopItem storage item = inventory[_itemId]; require(item.amount >= _amount && item.amount != 0, "There is not enough of your desired item to remove."); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); } /** Allows the Shop owner to adjust the prices of an NFT item set. @param _itemId The id of the specific inventory item of this shop to adjust. @param _pricePairs The asset-price pairs at which to sell a single instance of the item. */ function changeItemPrice(uint256 _itemId, PricePair[] memory _pricePairs) external onlyOwner { for (uint i = 0; i < _pricePairs.length; i++) { prices[_itemId][i] = _pricePairs[i]; } pricePairLengths[_itemId] = _pricePairs.length; } /** Allows any user to purchase an item from this Shop provided they have enough of the asset being used to purchase with. @param _itemId The ID of the specific inventory item of this shop to buy. @param _amount The amount of the specified item to purchase. @param _assetId The index of the asset from the item's asset-price pairs to attempt this purchase using. */ function purchaseItem(uint256 _itemId, uint256 _amount, uint256 _assetId) external nonReentrant payable { ShopItem storage item = inventory[_itemId]; require(item.amount >= _amount && item.amount != 0, "There is not enough of your desired item in stock to purchase."); require(_assetId < pricePairLengths[_itemId], "Your specified asset ID is not valid."); PricePair memory sellingPair = prices[_itemId][_assetId]; // If the sentinel value for the point asset type is found, sell for points. // This involves converting the asset from an address to a Staker index. if (sellingPair.assetType == 0) { uint256 stakerIndex = uint256(sellingPair.asset); stakers[stakerIndex].spendPoints(msg.sender, sellingPair.price.mul(_amount)); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); // If the sentinel value for the Ether asset type is found, sell for Ether. } else if (sellingPair.assetType == 1) { uint256 etherPrice = sellingPair.price.mul(_amount); require(msg.value >= etherPrice, "You did not send enough Ether to complete this purchase."); uint256 feePercent = feeOwner.fee(); uint256 feeValue = msg.value.mul(feePercent).div(100000); uint256 itemRoyaltyPercent = item.token.feeOwner().fee(); uint256 royaltyValue = msg.value.mul(itemRoyaltyPercent).div(100000); (bool success, ) = payable(feeOwner.owner()).call{ value: feeValue }(""); require(success, "Platform fee transfer failed."); (success, ) = payable(item.token.feeOwner().owner()).call{ value: royaltyValue }(""); require(success, "Creator royalty transfer failed."); (success, ) = payable(owner()).call{ value: msg.value.sub(feeValue).sub(royaltyValue) }(""); require(success, "Shop owner transfer failed."); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); // Otherwise, attempt to sell for an ERC20 token. } else { IERC20 sellingAsset = IERC20(sellingPair.asset); uint256 tokenPrice = sellingPair.price.mul(_amount); require(sellingAsset.balanceOf(msg.sender) >= tokenPrice, "You do not have enough token to complete this purchase."); uint256 feePercent = feeOwner.fee(); uint256 feeValue = tokenPrice.mul(feePercent).div(100000); uint256 itemRoyaltyPercent = item.token.feeOwner().fee(); uint256 royaltyValue = tokenPrice.mul(itemRoyaltyPercent).div(100000); sellingAsset.safeTransferFrom(msg.sender, feeOwner.owner(), feeValue); sellingAsset.safeTransferFrom(msg.sender, item.token.feeOwner().owner(), royaltyValue); sellingAsset.safeTransferFrom(msg.sender, owner(), tokenPrice.sub(feeValue).sub(royaltyValue)); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./FeeOwner.sol"; import "./Shop1155.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Shops. @author Tim Clancy This is the governing registry of all SuperFarm Shop assets. */ contract FarmShopRecords is Ownable, ReentrancyGuard { /// A version number for this record contract's interface. uint256 public version = 1; /// The current platform fee owner to force when creating Shops. FeeOwner public platformFeeOwner; /// A mapping for an array of all Shop1155s deployed by a particular address. mapping (address => address[]) public shopRecords; /// An event for tracking the creation of a new Shop. event ShopCreated(address indexed shopAddress, address indexed creator); /** Construct a new registry of SuperFarm records with a specified platform fee owner. @param _feeOwner The address of the FeeOwner due a portion of all Shop earnings. */ constructor(FeeOwner _feeOwner) public { platformFeeOwner = _feeOwner; } /** Allows the registry owner to update the platform FeeOwner to use upon Shop creation. @param _feeOwner The address of the FeeOwner to make the new platform fee owner. */ function changePlatformFeeOwner(FeeOwner _feeOwner) external onlyOwner { platformFeeOwner = _feeOwner; } /** Create a Shop1155 on behalf of the owner calling this function. The Shop supports immediately registering attached Stakers if provided. @param _name The name of the Shop to create. @param _stakers An array of Stakers to attach to the new Shop. */ function createShop(string calldata _name, Staker[] calldata _stakers) external nonReentrant returns (Shop1155) { Shop1155 newShop = new Shop1155(_name, platformFeeOwner, _stakers); // Transfer ownership of the new Shop to the user then store a reference. newShop.transferOwnership(msg.sender); address shopAddress = address(newShop); shopRecords[msg.sender].push(shopAddress); emit ShopCreated(shopAddress, msg.sender); return newShop; } /** Get the number of entries in the Shop records mapping for the given user. @return The number of Shops added for a given address. */ function getShopCount(address _user) external view returns (uint256) { return shopRecords[_user].length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./Token.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Tokens. @author Tim Clancy This is the governing registry of all SuperFarm Token assets. */ contract FarmTokenRecords is Ownable, ReentrancyGuard { /// A version number for this record contract's interface. uint256 public version = 1; /// A mapping for an array of all Tokens deployed by a particular address. mapping (address => address[]) public tokenRecords; /// An event for tracking the creation of a new Token. event TokenCreated(address indexed tokenAddress, address indexed creator); /** Create a Token on behalf of the owner calling this function. The Token supports immediate minting at the time of creation to particular addresses. @param _name The name of the Token to create. @param _ticker The ticker symbol of the Token to create. @param _cap The supply cap of the Token. @param _directMintAddresses An array of addresses to mint directly to. @param _directMintAmounts An array of Token amounts to mint to keyed addresses. */ function createToken(string calldata _name, string calldata _ticker, uint256 _cap, address[] calldata _directMintAddresses, uint256[] calldata _directMintAmounts) external nonReentrant returns (Token) { require(_directMintAddresses.length == _directMintAmounts.length, "Direct mint addresses length cannot be mismatched with mint amounts length."); // Create the token and optionally mint any specified addresses. Token newToken = new Token(_name, _ticker, _cap); for (uint256 i = 0; i < _directMintAddresses.length; i++) { address directMintAddress = _directMintAddresses[i]; uint256 directMintAmount = _directMintAmounts[i]; newToken.mint(directMintAddress, directMintAmount); } // Transfer ownership of the new Token to the user then store a reference. newToken.transferOwnership(msg.sender); address tokenAddress = address(newToken); tokenRecords[msg.sender].push(tokenAddress); emit TokenCreated(tokenAddress, msg.sender); return newToken; } /** Allow a user to add an existing Token contract to the registry. @param _tokenAddress The address of the Token contract to add for this user. */ function addToken(address _tokenAddress) external { tokenRecords[msg.sender].push(_tokenAddress); } /** Get the number of entries in the Token records mapping for the given user. @return The number of Tokens added for a given address. */ function getTokenCount(address _user) external view returns (uint256) { return tokenRecords[_user].length; } } // SPDX-License-Identifier: BSD-3-Clause // Modified from https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return 'Transaction reverted silently'; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{ value: value }(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { return block.timestamp; } }
/ Verify that the asset being used in the purchase is valid. Verify that the pool is still running its sale. Verify that the pool is respecting per-address global purchase limits. Verify that the pool is respecting per-address pool purchase limits. Verify that the pool is either public, whitelist-expired, or an address is whitelisted. If the sentinel value for the Ether asset type is found, sell for Ether. Otherwise, attempt to sell for an ERC20 token.
function mintFromPool(uint256 poolId, uint256 groupId, uint256 assetId, uint256 amount) external nonReentrant payable { require(amount > 0, "You must purchase at least one item."); require(poolId < nextPoolId, "You can only purchase items from an active pool."); bytes32 itemKey = keccak256(abi.encode(pools[poolId].currentPoolVersion, groupId)); require(assetId < pools[poolId].itemPricesLength[itemKey], "Your specified asset ID is not valid."); require(block.number >= pools[poolId].startBlock && block.number <= pools[poolId].endBlock, "This pool is not currently running its sale."); uint256 userGlobalPurchaseAmount = amount.add(globalPurchaseCounts[msg.sender]); require(userGlobalPurchaseAmount <= globalPurchaseLimit, "You may not purchase any more items from this sale."); uint256 userPoolPurchaseAmount = amount.add(pools[poolId].purchaseCounts[msg.sender]); require(userPoolPurchaseAmount <= pools[poolId].purchaseLimit, "You may not purchase any more items from this pool."); { uint256 whitelistId = pools[poolId].requirement.whitelistId; uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; bytes32 addressKey = keccak256(abi.encode(whitelistVersion, msg.sender)); bool addressWhitelisted = whitelists[whitelistId].addresses[addressKey]; require(whitelistId == 0 || block.number > whitelists[whitelistId].expiryBlock || addressWhitelisted || !whitelists[whitelistId].isActive, "You are not whitelisted on this pool."); } require(newCirculatingTotal <= pools[poolId].itemCaps[itemKey], "There are not enough items available for you to purchase."); if (poolRequirement.requiredType == 1) { IERC20 requiredToken = IERC20(poolRequirement.requiredAsset); require(requiredToken.balanceOf(msg.sender) >= poolRequirement.requiredAmount, "You do not have enough required token to participate in this pool."); } if (sellingPair.assetType == 0) { uint256 stakerIndex = uint256(sellingPair.asset); stakers[stakerIndex].spendPoints(msg.sender, sellingPair.price.mul(amount)); uint256 etherPrice = sellingPair.price.mul(amount); require(msg.value >= etherPrice, "You did not send enough Ether to complete this purchase."); require(success, "Shop owner transfer failed."); IERC20 sellingAsset = IERC20(sellingPair.asset); uint256 tokenPrice = sellingPair.price.mul(amount); require(sellingAsset.balanceOf(msg.sender) >= tokenPrice, "You do not have enough token to complete this purchase."); sellingAsset.safeTransferFrom(msg.sender, owner(), tokenPrice); } uint256[] memory amounts = new uint256[](amount); uint256 nextIssueNumber = nextItemIssues[groupId]; { uint256 shiftedGroupId = groupId << 128; for (uint256 i = 1; i <= amount; i++) { uint256 itemId = shiftedGroupId.add(nextIssueNumber).add(i); itemIds[i - 1] = itemId; amounts[i - 1] = 1; } } } @param _token The token to sweep the balance from.
1,272,099
/** *Submitted for verification at Etherscan.io on 2022-04-26 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // 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/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @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) /** * @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) /** * @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) /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) /** * @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/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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) /** * @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) /** * @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: ERC721A.sol // Creator: Chiru Labs error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev See {IERC721Enumerable-totalSupply}. * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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/token/ERC20/extensions/ERC20Burnable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } // 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: Bitchez.sol // Bitchez.sol contract Bitchez is ERC721A, Ownable { uint256 public maxSupply = 10000; uint256 public tokensForSale = 3000; bool public whitelistStatus = false; uint256 public whitelistPrice = 0.06 ether; mapping (address => uint256) public whitelists; bool public saleStatus = false; uint256 public currentPrice = 0.069 ether; uint256 public mintLimit = 7; address public blingyAddress; string public baseUri = ""; string public contractURI = "https://cryptobitchez.mypinata.cloud/ipfs/QmPm2kqYErH9D1mLhJyyHSThahxFxMbL8mLUmYs3VJwMVe"; constructor() ERC721A("CryptoBitchez", "BITCH") {} function _baseURI() internal view override returns (string memory) { return baseUri; } function _currentBlingyCost(uint256 tokenId) internal view returns (uint256) { if (tokenId <= tokensForSale) return 0; else if (tokenId > tokensForSale && tokenId <= 5000) return 50 * 10 ** 18; else if (tokenId > 5000 && tokenId <= 7000) return 100 * 10 ** 18; else if (tokenId > 7000 && tokenId <= 8500) return 150 * 10 ** 18; else if (tokenId > 8500 && tokenId <= 10000) return 200 * 10 ** 18; revert(); } function getTokenPrice(uint256 tokenId) public view returns(uint256) { if (tokenId <= tokensForSale) return currentPrice; else return _currentBlingyCost(tokenId); } function _mintToken(address to, uint256 numOfToken) internal { require(saleStatus, "not_sale"); require(numOfToken > 0, "invalid_mint_amount"); require(numOfToken <= mintLimit, "exceed_tx_limit"); require((totalSupply() + numOfToken) <= maxSupply, "exceed_max_supply"); require(to != address(0), "invalid_to_address"); _safeMint(to, numOfToken); } function getBuyPriceInBlingy(uint256 numOfToken) public view returns (uint256) { uint256 blingyCost = 0; for (uint256 i=1; i<=numOfToken; i++) { blingyCost = blingyCost + _currentBlingyCost(totalSupply() + i); } return blingyCost; } function buyByBlingy(uint256 numOfToken) external { require(totalSupply() >= tokensForSale, "eth_sale"); uint256 blingyCost = getBuyPriceInBlingy(numOfToken); require(ERC20Burnable(blingyAddress).balanceOf(msg.sender) >= blingyCost, "insuf_blingy_balance"); ERC20Burnable(blingyAddress).burnFrom(msg.sender, blingyCost); _mintToken(msg.sender, numOfToken); } function buyByEth(uint256 numOfToken) external payable { require((totalSupply() + numOfToken) <= tokensForSale, "exceed_eth_sale_limit"); require(currentPrice * numOfToken <= msg.value, "insuf_price"); _mintToken(msg.sender, numOfToken); } function airdrop(address to, uint256 numOfToken) external onlyOwner { require((totalSupply() + numOfToken) <= maxSupply, "exceed_max_supply"); _safeMint(to, numOfToken); } function whitelistSale(uint256 numOfToken) external payable { require(whitelistStatus, "not_whitelist_sale"); require(numOfToken > 0, "invalid_mint_amount"); require(whitelists[msg.sender] > 0, "not_whitelister"); require(numOfToken <= whitelists[msg.sender], "exceed_whitelist_limit"); require((totalSupply() + numOfToken) <= tokensForSale, "exceed_eth_sale_limit"); require(whitelistPrice * numOfToken <= msg.value, "insuf_price"); _safeMint(msg.sender, numOfToken); whitelists[msg.sender] = whitelists[msg.sender] - numOfToken; } function setBaseURI(string memory newUri) external onlyOwner { baseUri = newUri; } function setSaleState(bool status) external onlyOwner { saleStatus = status; } function setCurrentPrice(uint256 newPrice) public onlyOwner { currentPrice = newPrice; } function setWhitelistState(bool status) external onlyOwner { whitelistStatus = status; } function setWhitelistPrice(uint256 newPrice) public onlyOwner { whitelistPrice = newPrice; } function setWhitelist(address[] calldata whitelisters, uint256[] calldata numOfTokens) external onlyOwner { require (whitelisters.length < 1000, "too_much_inputs"); require (whitelisters.length == numOfTokens.length, "dismatch_input_length"); for (uint256 i=0; i < whitelisters.length; i++) { whitelists[whitelisters[i]] = numOfTokens[i]; } } function setBlingyAddress(address newAddress) public onlyOwner { blingyAddress = newAddress; } function setMintLimit(uint256 newLimit) external onlyOwner { mintLimit = newLimit; } function withdraw() external onlyOwner { require(address(this).balance > 0, "no_balance"); bool success = false; (success, ) = (payable(msg.sender)).call{value: address(this).balance}(""); require(success, "withdraw_failed"); } }
See {IERC721-isApprovedForAll}./
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; }
10,913,320
./full_match/1/0x6A2ffABcfE8583bcA023225E66008b709820b39e/sources/ERC721A.sol
See {IERC721Enumerable-tokenOfOwnerByIndex}. This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case./
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); }
16,570,722
// produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract EthBattle is Ownable { using SafeMath for uint256; uint256 constant TOKEN_USE_BONUS = 15; //%, adds weight of win on top of the market price uint256 constant REFERRAL_REWARD = 2 ether; // GTA, 10*19 uint256 public MIN_PLAY_AMOUNT = 50 finney; //wei, equal 0.05 ETH uint256 public META_BET_WEIGHT = 10 finney; //wei, equal to 0.01 ETH uint256 public roundIndex = 0; mapping(uint256 => address) public rounds; address[] private currentRewardingAddresses; PlaySeedInterface private playSeedGenerator; GTAInterface public token; AMUStoreInterface public store; address public startersProxyAddress; mapping(address => address) public referralBacklog; //backlog of players and their referrals mapping(address => uint256) public tokens; //map of deposited tokens event RoundCreated(address createdAddress, uint256 index); event Deposit(address user, uint amount, uint balance); event Withdraw(address user, uint amount, uint balance); /** * @dev Default fallback function, just deposits funds to the pot */ function () public payable { getLastRound().getDevWallet().transfer(msg.value); } /** * @dev The EthBattle constructor * @param _playSeedAddress address of the play seed generator * @param _tokenAddress GTA address * @param _storeAddress store contract address */ constructor (address _playSeedAddress, address _tokenAddress, address _storeAddress, address _proxyAddress) public { playSeedGenerator = PlaySeedInterface(_playSeedAddress); token = GTAInterface(_tokenAddress); store = AMUStoreInterface(_storeAddress); startersProxyAddress = _proxyAddress; } modifier onlyProxy() { require(msg.sender == startersProxyAddress); _; } /** * @dev Try (must be allowed by the seed generator itself) to claim ownership of the seed generator */ function claimSeedOwnership() onlyOwner public { playSeedGenerator.claimOwnership(); } /** * @dev Inject the new round contract, and sets the round with a new index * NOTE! Injected round must have had transferred ownership to this EthBattle already * @param _roundAddress address of the new round to use */ function startRound(address _roundAddress) onlyOwner public { RoundInterface round = RoundInterface(_roundAddress); round.claimOwnership(); roundIndex++; rounds[roundIndex] = round; emit RoundCreated(round, roundIndex); } /** * @dev Player starts a new play providing * @param _referral (Optional) referral address is any * @param _gtaBet (Optional) additional bet in GTA */ function play(address _referral, uint256 _gtaBet) public payable { address player = msg.sender; uint256 weiAmount = msg.value; require(player != address(0), "Player's address is missing"); require(weiAmount >= MIN_PLAY_AMOUNT, "The bet is too low"); require(_gtaBet <= balanceOf(player), "Player's got not enough GTA"); uint256 _bet = aggregateBet(weiAmount, _gtaBet); playInternal(player, weiAmount, _bet, _referral, _gtaBet); } /** * @dev Etherless player starts a new play, when actually the gas fee is payed * by the sender and the bet is set by the proxy * @param _player The actual player * @param _referral (Optional) referral address is any * @param _gtaBet (Optional) additional bet in GTA */ function playMeta(address _player, address _referral, uint256 _gtaBet) onlyProxy public payable { uint256 weiAmount = msg.value; require(_player != address(0), "Player's address is missing"); require(_gtaBet <= balanceOf(_player), "Player's got not enough GTA"); //Important! For meta plays the 'weight' is not connected the the actual bet (since the bet comes from proxy) //but static and equals META_BET_WEIGHT uint256 _bet = aggregateBet(META_BET_WEIGHT, _gtaBet); playInternal(_player, weiAmount, _bet, _referral, _gtaBet); } function playInternal(address _player, uint256 _weiBet, uint256 _betWeight, address _referral, uint256 _gtaBet) internal { if (_referral != address(0) && referralBacklog[_player] == address(0)) { //new referral for this _player referralBacklog[_player] = _referral; //reward the referral. Tokens remains in this contract //but become available for withdrawal by _referral transferInternally(owner, _referral, REFERRAL_REWARD); } playSeedGenerator.newPlaySeed(_player); if (_gtaBet > 0) { //player's using GTA transferInternally(_player, owner, _gtaBet); } if (referralBacklog[_player] != address(0)) { //ongoing round might not know about the _referral //delegate the knowledge of the referral to the ongoing round getLastRound().setReferral(_player, referralBacklog[_player]); } getLastRound().playRound.value(_weiBet)(_player, _betWeight); } /** * @dev Player claims a win * @param _seed secret seed */ function win(bytes32 _seed) public { address player = msg.sender; winInternal(player, _seed); } /** * @dev Player claims a win * @param _player etherless player claims * @param _seed secret seed */ function winMeta(address _player, bytes32 _seed) onlyProxy public { winInternal(_player, _seed); } function winInternal(address _player, bytes32 _seed) internal { require(_player != address(0), "Winner's address is missing"); require(playSeedGenerator.findSeed(_player) == _seed, "Wrong seed!"); playSeedGenerator.cleanSeedUp(_player); getLastRound().win(_player); } function findSeedAuthorized(address player) onlyOwner public view returns (bytes32){ return playSeedGenerator.findSeed(player); } function aggregateBet(uint256 _bet, uint256 _gtaBet) internal view returns (uint256) { //get market price of the GTA, multiply by bet, and apply a bonus on it. //since both 'price' and 'bet' are in 'wei', we need to drop 10*18 decimals at the end uint256 _gtaValueWei = store.getTokenBuyPrice().mul(_gtaBet).div(1 ether).mul(100 + TOKEN_USE_BONUS).div(100); //sum up with ETH bet uint256 _resultBet = _bet.add(_gtaValueWei); return _resultBet; } /** * @dev Calculates the prize amount for this player by now * Note: the result is not the final one and a subject to change once more plays/wins occur * @return The prize in wei */ function prizeByNow() public view returns (uint256) { return getLastRound().currentPrize(msg.sender); } /** * @dev Calculates the prediction on the prize amount for this player and this bet * Note: the result is not the final one and a subject to change once more plays/wins occur * @param _bet hypothetical bet in wei * @param _gtaBet hypothetical bet in GTA * @return The prediction in wei */ function prizeProjection(uint256 _bet, uint256 _gtaBet) public view returns (uint256) { return getLastRound().projectedPrizeForPlayer(msg.sender, aggregateBet(_bet, _gtaBet)); } /** * @dev Deposit GTA to the EthBattle contract so it can be spent (used) immediately * Note: this call must follow the approve() call on the token itself * @param _amount amount to deposit */ function depositGTA(uint256 _amount) public { require(token.transferFrom(msg.sender, this, _amount), "Insufficient funds"); tokens[msg.sender] = tokens[msg.sender].add(_amount); emit Deposit(msg.sender, _amount, tokens[msg.sender]); } /** * @dev Withdraw GTA from this contract to the own (caller) address * @param _amount amount to withdraw */ function withdrawGTA(uint256 _amount) public { require(tokens[msg.sender] >= _amount, "Amount exceeds the available balance"); tokens[msg.sender] = tokens[msg.sender].sub(_amount); require(token.transfer(msg.sender, _amount), "Amount exceeds the available balance"); emit Withdraw(msg.sender, _amount, tokens[msg.sender]); } /** * @dev Internal transfer of the token. * Funds remain in this contract but become available for withdrawal */ function transferInternally(address _from, address _to, uint256 _amount) internal { require(tokens[_from] >= _amount, "Too much to transfer"); tokens[_from] = tokens[_from].sub(_amount); tokens[_to] = tokens[_to].add(_amount); } /** * @dev Interrupts the round to enable participants to claim funds back */ function interruptLastRound() onlyOwner public { getLastRound().enableRefunds(); } /** * @dev End last round so no new plays is possible, but ongoing plays are fine to win */ function finishLastRound() onlyOwner public { getLastRound().coolDown(); } function getLastRound() public view returns (RoundInterface){ return RoundInterface(rounds[roundIndex]); } function getLastRoundAddress() external view returns (address){ return rounds[roundIndex]; } function balanceOf(address _user) public view returns (uint256) { return tokens[_user]; } function setPlaySeed(address _playSeedAddress) onlyOwner public { playSeedGenerator = PlaySeedInterface(_playSeedAddress); } function setStore(address _storeAddress) onlyOwner public { store = AMUStoreInterface(_storeAddress); } function getTokenBuyPrice() public view returns (uint256) { return store.getTokenBuyPrice(); } function getTokenSellPrice() public view returns (uint256) { return store.getTokenSellPrice(); } /** * @dev Recover the history of referrals in case of the contract migration. */ function setReferralsMap(address[] _players, address[] _referrals) onlyOwner public { require(_players.length == _referrals.length, "Size of players must be equal to the size of referrals"); for (uint i = 0; i < _players.length; ++i) { referralBacklog[_players[i]] = _referrals[i]; } } function getStartersProxyAddress() external view returns (address) { return startersProxyAddress; } function setStartersProxyAddress(address _newProxyAddress) onlyOwner public { startersProxyAddress = _newProxyAddress; } function setMetaBetWeight(uint256 _newMetaBet) onlyOwner public { META_BET_WEIGHT = _newMetaBet; } function setMinBet(uint256 _newMinBet) onlyOwner public { MIN_PLAY_AMOUNT = _newMinBet; } } /** * @title PlaySeed contract interface */ interface PlaySeedInterface { function newPlaySeed(address _player) external; function findSeed(address _player) external view returns (bytes32); function cleanSeedUp(address _player) external; function claimOwnership() external; } /** * @title GTA contract interface */ interface GTAInterface { function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); } /** * @title EthBattleRound contract interface */ interface RoundInterface { function claimOwnership() external; function setReferral(address _player, address _referral) external; function playRound(address _player, uint256 _bet) external payable; function enableRefunds() external; function coolDown() external; function currentPrize(address _player) external view returns (uint256); function projectedPrizeForPlayer(address _player, uint256 _bet) external view returns (uint256); function win(address _player) external; function getDevWallet() external view returns (address); } /** * @title Ammu-Nation contract interface */ interface AMUStoreInterface { function getTokenBuyPrice() external view returns (uint256); function getTokenSellPrice() external view returns (uint256); }
Inject the new round contract, and sets the round with a new index NOTE! Injected round must have had transferred ownership to this EthBattle already _roundAddress address of the new round to use/
function startRound(address _roundAddress) onlyOwner public { RoundInterface round = RoundInterface(_roundAddress); round.claimOwnership(); roundIndex++; rounds[roundIndex] = round; emit RoundCreated(round, roundIndex); }
4,805,527
pragma solidity ^0.4.15; import "kleros-interaction/contracts/standard/arbitration/ArbitratorCourt.sol"; import "kleros-interaction/contracts/standard/rng/RNG.sol"; import { MiniMeTokenERC20 as Pinakion } from "kleros-interaction/contracts/standard/arbitration/ArbitrableTokens/MiniMeTokenERC20.sol"; import "./KlerosPOC.sol"; /** * @title KlerosPOCCourt * @author Enrique Piqueras - <[email protected]> * @notice A `KlerosPOC` Court in a tree of `ArbitratorCourt`s. */ contract KlerosPOCCourt is ArbitratorCourt, KlerosPOC { /* Constructor */ /** * @notice Constructs the `KlerosPOCCourt`, forwarding all required parameters to the base contracts. * @param _parentName The name of the `parent`. * @param _parentAddress The address of the `parent`. * @param _pinakion The address of the pinakion contract which will be used. * @param _rng The address of the random number generator contract which will be used. * @param _timePerPeriod The minimal time for each period. */ function KlerosPOCCourt(string _parentName, Arbitrator _parentAddress, Pinakion _pinakion, RNG _rng, uint[5] _timePerPeriod) ArbitratorCourt(1, _parentName, _parentAddress) KlerosPOC(_pinakion, _rng, _timePerPeriod) public {} /* Public */ /** @notice Appeals a ruling to the parent court. * @param _disputeID The ID of the dispute to be appealed. * @param _extraData Part of the standard but not used by this contract. */ function appeal(uint256 _disputeID, bytes _extraData) public payable onlyDuring(Period.Appeal) { if (disputes[_disputeID].appeals < maxLocalAppeals) { // Will we stay under max local appeals? super.appeal(_disputeID, _extraData); // Regular appeal } else { // Appeal to `parent` // Checks require(disputes[_disputeID].session + disputes[_disputeID].appeals == session); // Dispute of the current session // Effects disputes[_disputeID].appeals++; disputes[_disputeID].votes.length++; disputes[_disputeID].voteCounter.length++; disputes[_disputeID].state = DisputeState.Executed; // Terminate dispute // Interactions Arbitrator.appeal(_disputeID, _extraData); // Fire appeal event parent._address.createDispute.value(msg.value)(disputes[_disputeID].choices, _extraData); // Create dispute in `parent` court } } /* Public Views */ /** @notice Computes the cost of appealing to the parent court. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID The ID of the dispute to be appealed. * @param _extraData Part of the standard but not used by this contract. * @return _fee The appeal cost. */ function appealCost(uint256 _disputeID, bytes _extraData) public constant returns(uint256 _fee) { if (disputes[_disputeID].appeals < maxLocalAppeals) { // Will we stay under max local appeals? return super.appealCost(_disputeID, _extraData); // Regular appeal cost } return parent._address.arbitrationCost(_extraData); // `parent` arbitration cost } }
Computes the cost of appealing to the parent court. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. _disputeID The ID of the dispute to be appealed. _extraData Part of the standard but not used by this contract. return _fee The appeal cost./
function appealCost(uint256 _disputeID, bytes _extraData) public constant returns(uint256 _fee) { }
7,241,337
// 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); } } } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableData { address public owner; address public pendingOwner; } abstract contract Ownable is OwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } function transferOwnership(address newOwner, bool direct, bool renounce) public onlyOwner { if (direct) { require(newOwner != address(0) || renounce, "Ownable: zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } else { pendingOwner = newOwner; } } function claimOwnership() public { address _pendingOwner = pendingOwner; require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } /** * @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' // 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) + 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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Sorbettiere is a "semifredo of popsicle stand" this contract is created to provide single side farm for IFO of Popsicle Finance. // The contract is based on famous Masterchef contract (Ty guys for that) // It intakes one token and allows the user to farm another token. Due to the crosschain nature of Popsicle Stand we've swapped reward per block // to reward per second. Moreover, we've implemented safe transfer of reward instead of mint in Masterchef. // Future is crosschain... // The contract is ownable untill the DAO will be able to take over. Popsicle community shows that DAO is coming soon. // And the contract ownership will be transferred to other contract contract Sorbettiere is Ownable { using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 remainingIceTokenReward; // ICE Tokens that weren't distributed for user per pool. // // We do some fancy math here. Basically, any point in time, the amount of ICE // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accICEPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws Staked tokens to a pool. Here's what happens: // 1. The pool's `accICEPerShare` (and `lastRewardTime`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 stakingToken; // Contract address of staked token uint256 stakingTokenTotalAmount; //Total amount of deposited tokens uint256 accIcePerShare; // Accumulated ICE per share, times 1e12. See below. uint32 lastRewardTime; // Last timestamp number that ICE distribution occurs. uint16 allocPoint; // How many allocation points assigned to this pool. ICE to distribute per second. } IERC20 immutable public ice; // The ICE TOKEN!! uint256 public icePerSecond; // Ice tokens vested per second. PoolInfo[] public poolInfo; // Info of each pool. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Info of each user that stakes tokens. uint256 public totalAllocPoint = 0; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint32 immutable public startTime; // The timestamp when ICE farming starts. uint32 public endTime; // Time on which the reward calculation should end event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( IERC20 _ice, uint256 _icePerSecond, uint32 _startTime ) { ice = _ice; icePerSecond = _icePerSecond; startTime = _startTime; endTime = _startTime + 7 days; } function changeEndTime(uint32 addSeconds) external onlyOwner { endTime += addSeconds; } // Changes Ice token reward per second. Use this function to moderate the `lockup amount`. Essentially this function changes the amount of the reward // which is entitled to the user for his token staking by the time the `endTime` is passed. //Good practice to update pools without messing up the contract function setIcePerSecond(uint256 _icePerSecond, bool _withUpdate) external onlyOwner { if (_withUpdate) { massUpdatePools(); } icePerSecond= _icePerSecond; } // How many pools are in the contract function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new staking token to the pool. Can only be called by the owner. // VERY IMPORTANT NOTICE // ----------- DO NOT add the same staking token more than once. Rewards will be messed up if you do. ------------- // Good practice to update pools without messing up the contract function add( uint16 _allocPoint, IERC20 _stakingToken, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardTime = block.timestamp > startTime ? block.timestamp : startTime; totalAllocPoint +=_allocPoint; poolInfo.push( PoolInfo({ stakingToken: _stakingToken, stakingTokenTotalAmount: 0, allocPoint: _allocPoint, lastRewardTime: uint32(lastRewardTime), accIcePerShare: 0 }) ); } // Update the given pool's ICE allocation point. Can only be called by the owner. // Good practice to update pools without messing up the contract function set( uint256 _pid, uint16 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to time. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { _from = _from > startTime ? _from : startTime; if (_from > endTime || _to < startTime) { return 0; } if (_to > endTime) { return endTime - _from; } return _to - _from; } // View function to see pending ICE on frontend. function pendingIce(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accIcePerShare = pool.accIcePerShare; if (block.timestamp > pool.lastRewardTime && pool.stakingTokenTotalAmount != 0) { uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp); uint256 iceReward = multiplier * icePerSecond * pool.allocPoint / totalAllocPoint; accIcePerShare += iceReward * 1e12 / pool.stakingTokenTotalAmount; } return user.amount * accIcePerShare / 1e12 - user.rewardDebt + user.remainingIceTokenReward; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.timestamp <= pool.lastRewardTime) { return; } if (pool.stakingTokenTotalAmount == 0) { pool.lastRewardTime = uint32(block.timestamp); return; } uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp); uint256 iceReward = multiplier * icePerSecond * pool.allocPoint / totalAllocPoint; pool.accIcePerShare += iceReward * 1e12 / pool.stakingTokenTotalAmount; pool.lastRewardTime = uint32(block.timestamp); } // Deposit staking tokens to Sorbettiere for ICE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount * pool.accIcePerShare / 1e12 - user.rewardDebt + user.remainingIceTokenReward; user.remainingIceTokenReward = safeRewardTransfer(msg.sender, pending); } pool.stakingToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount += _amount; pool.stakingTokenTotalAmount += _amount; user.rewardDebt = user.amount * pool.accIcePerShare / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw staked tokens from Sorbettiere. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "Sorbettiere: you cant eat that much popsicles"); updatePool(_pid); uint256 pending = user.amount * pool.accIcePerShare / 1e12 - user.rewardDebt + user.remainingIceTokenReward; user.remainingIceTokenReward = safeRewardTransfer(msg.sender, pending); user.amount -= _amount; pool.stakingTokenTotalAmount -= _amount; user.rewardDebt = user.amount * pool.accIcePerShare / 1e12; pool.stakingToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 userAmount = user.amount; pool.stakingTokenTotalAmount -= userAmount; delete userInfo[_pid][msg.sender]; pool.stakingToken.safeTransfer(address(msg.sender), userAmount); emit EmergencyWithdraw(msg.sender, _pid, userAmount); } // Safe ice transfer function. Just in case if the pool does not have enough ICE token, // The function returns the amount which is owed to the user function safeRewardTransfer(address _to, uint256 _amount) internal returns(uint256) { uint256 iceTokenBalance = ice.balanceOf(address(this)); if (iceTokenBalance == 0) { //save some gas fee return _amount; } if (_amount > iceTokenBalance) { //save some gas fee ice.safeTransfer(_to, iceTokenBalance); return _amount - iceTokenBalance; } ice.safeTransfer(_to, _amount); return 0; } }
Deposit staking tokens to Sorbettiere for ICE allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount * pool.accIcePerShare / 1e12 - user.rewardDebt + user.remainingIceTokenReward; user.remainingIceTokenReward = safeRewardTransfer(msg.sender, pending); } pool.stakingToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount += _amount; pool.stakingTokenTotalAmount += _amount; user.rewardDebt = user.amount * pool.accIcePerShare / 1e12; emit Deposit(msg.sender, _pid, _amount); }
1,304,781
./full_match/1/0x22c334a70EFCCfEd3190374BD8B15E0A836c92F7/sources/meme_dev/PepeOmega.sol
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, 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 from, address to, uint256 amount ) external returns (bool); pragma solidity ^0.8.0; ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣤⣴⣶⣶⣾⣿⣿⣿⣿⣿⣷⣶⣶⣦⣤⣄⣀⡀⠀⠀⠀⠀⠀ }
3,182,676
pragma solidity ^0.4.21; /*** * ,------. * | .---' ,--,--. ,--.--. ,--,--,--. * | `--, ' ,-. | | .--' | | * | |` \ '-' | | | | | | | * `--' `--`--' `--' `--`--`--' * * v 1.1.0 * "With help, wealth grows..." * * Ethereum Commonwealth.gg Farm(based on contract @ ETC:0x93123bA3781bc066e076D249479eEF760970aa32) * Modifications: * -> reinvest Crop Function * What? * -> Maintains crops, so that farmers can reinvest on user's behalf. Farmers receieve a referral bonus. * -> A crop contract is deployed for each holder, and holds custody of eWLTH. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ contract Hourglass { function() payable public; function buy(address) public payable returns(uint256) {} function sell(uint256) public; function withdraw() public returns(address); function dividendsOf(address,bool) public view returns(uint256); function balanceOf(address) public view returns(uint256); function transfer(address , uint256) public returns(bool); function myTokens() public view returns(uint256); function myDividends(bool) public view returns(uint256); function exit() public; } contract Farm { address public eWLTHAddress = 0x5833C959C3532dD5B3B6855D590D70b01D2d9fA6; // Mapping of owners to their crops. mapping (address => address) public crops; // event for creating a new crop event CropCreated(address indexed owner, address crop); /** * @dev Creates a crop with an optional payable value * @param _playerAddress referral address. */ function createCrop(address _playerAddress, bool _selfBuy) public payable returns (address) { // we can't already have a crop require(crops[msg.sender] == address(0)); // create a new crop for us address cropAddress = new Crop(msg.sender); // map the creator to the crop address crops[msg.sender] = cropAddress; emit CropCreated(msg.sender, cropAddress); // if we sent some value with the transaction, buy some eWLTH for the crop. if (msg.value != 0){ if (_selfBuy){ Crop(cropAddress).buy.value(msg.value)(cropAddress); } else { Crop(cropAddress).buy.value(msg.value)(_playerAddress); } } return cropAddress; } /** * @dev Returns my current crop. */ function myCrop() public view returns (address) { return crops[msg.sender]; } /** * @dev Get dividends of my crop. */ function myCropDividends(bool _includeReferralBonus) external view returns (uint256) { return Hourglass(eWLTHAddress).dividendsOf(crops[msg.sender], _includeReferralBonus); } /** * @dev Get amount of tokens owned by my crop. */ function myCropTokens() external view returns (uint256) { return Hourglass(eWLTHAddress).balanceOf(crops[msg.sender]); } /** * @dev Get whether or not your crop is disabled. */ function myCropDisabled() external view returns (bool) { if (crops[msg.sender] != address(0)){ return Crop(crops[msg.sender]).disabled(); } else { return true; } } } contract Crop { address public owner; bool public disabled = false; address private eWLTHAddress = 0x5833C959C3532dD5B3B6855D590D70b01D2d9fA6; modifier onlyOwner() { require(msg.sender == owner); _; } function Crop(address newOwner) public { owner = newOwner; } /** * @dev Turn reinvest on / off * @param _disabled bool to determine state of reinvest. */ function disable(bool _disabled) external onlyOwner() { // toggle disabled disabled = _disabled; } /** * @dev Enables anyone with a masternode to earn referral fees on eWLTH reinvestments. * @param _playerAddress referral address. */ function reinvest(address _playerAddress) external { // reinvest must be enabled require(disabled == false); Hourglass eWLTH = Hourglass(eWLTHAddress); if (eWLTH.dividendsOf(address(this), true) > 0){ eWLTH.withdraw(); uint256 bal = address(this).balance; // reinvest with a referral fee for sender eWLTH.buy.value(bal)(_playerAddress); } } /** * @dev Default function if ETC sent to contract. Does nothing. */ function() public payable {} /** * @dev Buy eWLTH tokens * @param _playerAddress referral address. */ function buy(address _playerAddress) external payable { Hourglass(eWLTHAddress).buy.value(msg.value)(_playerAddress); } /** * @dev Sell eWLTH tokens and send balance to owner * @param _amountOfTokens amount of tokens to sell. */ function sell(uint256 _amountOfTokens) external onlyOwner() { // sell tokens Hourglass(eWLTHAddress).sell(_amountOfTokens); // transfer the dividends back to the owner withdraw(); } /** * @dev Withdraw eWLTH dividends and send balance to owner */ function withdraw() public onlyOwner() { if (Hourglass(eWLTHAddress).myDividends(true) > 0){ // withdraw dividends Hourglass(eWLTHAddress).withdraw(); // transfer to owner owner.transfer(address(this).balance); } } /** * @dev Liquidate all eWLTH in crop and send to the owner. */ function exit() external onlyOwner() { Hourglass(eWLTHAddress).exit(); owner.transfer(address(this).balance); } /** * @dev Transfer eWLTH tokens * @param _toAddress address to send tokens to. * @param _amountOfTokens amount of tokens to send. */ function transfer(address _toAddress, uint256 _amountOfTokens) external onlyOwner() returns (bool) { withdraw(); return Hourglass(eWLTHAddress).transfer(_toAddress, _amountOfTokens); } /** * @dev Get dividends for this crop. * @param _includeReferralBonus for including referrals in dividends. */ function cropDividends(bool _includeReferralBonus) external view returns (uint256) { return Hourglass(eWLTHAddress).myDividends(_includeReferralBonus); } /** * @dev Get number of tokens for this crop. */ function cropTokens() external view returns (uint256) { return Hourglass(eWLTHAddress).myTokens(); } }
Withdraw eWLTH dividends and send balance to owner/ withdraw dividends transfer to owner
function withdraw() public onlyOwner() { if (Hourglass(eWLTHAddress).myDividends(true) > 0){ Hourglass(eWLTHAddress).withdraw(); owner.transfer(address(this).balance); } }
12,724,461
./partial_match/1/0x5AdA07Ff0d2772E202776be8a8EC69ac3345050f/sources/UniswapV3TwapPriceOracle.sol
Returns the Uniswap pool used to compute the TWAP between `assetA` and `assetB`
function getPool(address assetA, address assetB) public view returns (address) { uint256 poolKey = getAssetsPairKey(assetA, assetB); return pools.get(poolKey); }
3,955,267
./full_match/4/0xf15046F9c0ec667B016DAcb5D198000E1d20E337/sources/contracts/Marsh_Staking_Contract.sol
Value Pre-Processing and stuff (?) _indexerPublicKey public key of the indexer _amountOfTokens amount of tokens being staked./
function Stake(string memory _indexerPublicKey, uint256 _amountOfTokens) external payable { require( !_indexerExists(msg.sender), "Address already exists and has already staked amount. Retry with new address" ); require(_amountOfTokens >= MINIMUM_STAKE, "Staked amount insufficient"); _createStake( msg.sender, _indexerPublicKey, _amountOfTokens ); emit StakeEvent(msg.sender, _indexerPublicKey,_amountOfTokens); }
688,634
./full_match/1/0x8F762237a0D0F027aA12bF37856081d638d45BE3/sources/contracts/MarginEngine.sol
Checks if a given position is liquidatable In order for a position to be liquidatable its current margin needs to be lower than the position's liquidation margin requirement return _isLiquidatable A boolean which suggests if a given position is liquidatable
function _isLiquidatablePosition( Position.Info storage _position, int24 _tickLower, int24 _tickUpper ) internal returns (bool, int256) { int256 _marginRequirement = _getPositionMarginRequirement( _position, _tickLower, _tickUpper, true ).toInt256(); return (_position.margin < _marginRequirement, _marginRequirement);
16,403,442
./full_match/80001/0x5d705F676f54FBB581968223Cfaa7714726F62a5/sources/contracts/EQTradable.sol
Set the base URI newuri base uri
function setURI(string calldata newuri) external onlyOwner { _setURI(newuri); }
9,511,198
./partial_match/84531/0xb194C2E006aEeC94BC8bAa39B8578992134deF80/sources/contracts/src/towns/facets/platform/requirements/PlatformRequirementsBase.sol
Membership Duration
function _setMembershipDuration(uint64 duration) internal { if (duration == 0) revert Platform__InvalidMembershipDuration(); PlatformRequirementsStorage.layout().membershipDuration = duration; emit PlatformMembershipDurationSet(duration); }
16,684,805
pragma solidity 0.4.24; contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, 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. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; mapping (address=>bool) private whiteList; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused || whiteList[msg.sender]); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused || whiteList[msg.sender]); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } function addToWhiteList(address[] _whiteList) external onlyOwner { require(_whiteList.length > 0); for(uint8 i = 0; i < _whiteList.length; i++) { assert(_whiteList[i] != address(0)); whiteList[_whiteList[i]] = true; } } function removeFromWhiteList(address[] _blackList) external onlyOwner { require(_blackList.length > 0); for(uint8 i = 0; i < _blackList.length; i++) { assert(_blackList[i] != address(0)); whiteList[_blackList[i]] = true; } } } contract W12TokenDistributor is Ownable { W12Token public token; mapping(uint32 => bool) public processedTransactions; constructor() public { token = new W12Token(); } function isTransactionSuccessful(uint32 id) external view returns (bool) { return processedTransactions[id]; } modifier validateInput(uint32[] _payment_ids, address[] _receivers, uint256[] _amounts) { require(_receivers.length == _amounts.length); require(_receivers.length == _payment_ids.length); _; } function transferTokenOwnership() external onlyOwner { token.transferOwnership(owner); } } contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; constructor (ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { // solium-disable-next-line security/no-block-members require(_releaseTime > block.timestamp); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { // solium-disable-next-line security/no-block-members require(block.timestamp >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } contract W12Crowdsale is W12TokenDistributor, ReentrancyGuard { uint public presaleStartDate = 1526817600; uint public presaleEndDate = 1532088000; uint public crowdsaleStartDate = 1532692800; uint public crowdsaleEndDate = 1538049600; uint public presaleTokenBalance = 20 * (10 ** 24); uint public crowdsaleTokenBalance = 80 * (10 ** 24); address public crowdsaleFundsWallet; enum Stage { Inactive, FlashSale, Presale, Crowdsale } event LockCreated(address indexed wallet, address timeLock1, address timeLock2, address timeLock3); constructor(address _crowdsaleFundsWallet) public { require(_crowdsaleFundsWallet != address(0)); // Wallet to hold collected Ether crowdsaleFundsWallet = address(_crowdsaleFundsWallet); } function setUpCrowdsale() external onlyOwner { uint tokenDecimalsMultiplicator = 10 ** 18; // Tokens to sell during the first two phases of ICO token.mint(address(this), presaleTokenBalance + crowdsaleTokenBalance); // Partners token.mint(address(0xDbdCEa0B020D4769D7EA0aF47Df8848d478D67d1), 8 * (10 ** 6) * tokenDecimalsMultiplicator); // Bounty and support of ecosystem token.mint(address(0x1309Bb4DBBB6F8B3DE1822b4Cf22570d44f79cde), 8 * (10 ** 6) * tokenDecimalsMultiplicator); // Airdrop token.mint(address(0x0B2F4A122c34c4ccACf4EBecE15dE571d67b4D0a), 4 * (10 ** 6) * tokenDecimalsMultiplicator); address[] storage whiteList; whiteList.push(address(this)); whiteList.push(address(0xDbdCEa0B020D4769D7EA0aF47Df8848d478D67d1)); whiteList.push(address(0x1309Bb4DBBB6F8B3DE1822b4Cf22570d44f79cde)); whiteList.push(address(0x0B2F4A122c34c4ccACf4EBecE15dE571d67b4D0a)); whiteList.push(address(0xd13B531160Cfe6CC2f9a5615524CA636A0A94D88)); whiteList.push(address(0x3BAF5A51E6212d311Bc567b60bE84Fc180d39805)); token.addToWhiteList(whiteList); } function () payable external { Stage currentStage = getStage(); require(currentStage != Stage.Inactive); uint currentRate = getCurrentRate(); uint tokensBought = msg.value * (10 ** 18) / currentRate; token.transfer(msg.sender, tokensBought); advanceStage(tokensBought, currentStage); } function getCurrentRate() public view returns (uint) { uint currentSaleTime; Stage currentStage = getStage(); if(currentStage == Stage.Presale) { currentSaleTime = now - presaleStartDate; uint presaleCoef = currentSaleTime * 100 / (presaleEndDate - presaleStartDate); return 262500000000000 + 35000000000000 * presaleCoef / 100; } if(currentStage == Stage.Crowdsale) { currentSaleTime = now - crowdsaleStartDate; uint crowdsaleCoef = currentSaleTime * 100 / (crowdsaleEndDate - crowdsaleStartDate); return 315000000000000 + 35000000000000 * crowdsaleCoef / 100; } if(currentStage == Stage.FlashSale) { return 234500000000000; } revert(); } function getStage() public view returns (Stage) { if(now >= crowdsaleStartDate && now < crowdsaleEndDate) { return Stage.Crowdsale; } if(now >= presaleStartDate) { if(now < presaleStartDate + 1 days) return Stage.FlashSale; if(now < presaleEndDate) return Stage.Presale; } return Stage.Inactive; } function bulkTransfer(uint32[] _payment_ids, address[] _receivers, uint256[] _amounts) external onlyOwner validateInput(_payment_ids, _receivers, _amounts) { bool success = false; for (uint i = 0; i < _receivers.length; i++) { if (!processedTransactions[_payment_ids[i]]) { success = token.transfer(_receivers[i], _amounts[i]); processedTransactions[_payment_ids[i]] = success; if (!success) break; advanceStage(_amounts[i], getStage()); } } } function transferTokensToOwner() external onlyOwner { token.transfer(owner, token.balanceOf(address(this))); } function advanceStage(uint tokensBought, Stage currentStage) internal { if(currentStage == Stage.Presale || currentStage == Stage.FlashSale) { if(tokensBought <= presaleTokenBalance) { presaleTokenBalance -= tokensBought; return; } } if(currentStage == Stage.Crowdsale) { if(tokensBought <= crowdsaleTokenBalance) { crowdsaleTokenBalance -= tokensBought; return; } } revert(); } function withdrawFunds() external nonReentrant { require(crowdsaleFundsWallet == msg.sender); crowdsaleFundsWallet.transfer(address(this).balance); } function setPresaleStartDate(uint32 _presaleStartDate) external onlyOwner { presaleStartDate = _presaleStartDate; } function setPresaleEndDate(uint32 _presaleEndDate) external onlyOwner { presaleEndDate = _presaleEndDate; } function setCrowdsaleStartDate(uint32 _crowdsaleStartDate) external onlyOwner { crowdsaleStartDate = _crowdsaleStartDate; } function setCrowdsaleEndDate(uint32 _crowdsaleEndDate) external onlyOwner { crowdsaleEndDate = _crowdsaleEndDate; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender] - _value; balances[_to] = balances[_to] + _value; emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from] - _value; balances[_to] = balances[_to] + _value; allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value; emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender] + _addedValue; emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue - _subtractedValue; } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_ + _amount; balances[_to] = balances[_to] + _amount; emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor (string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_ + _amount <= cap); return super.mint(_to, _amount); } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who] - _value; totalSupply_ = totalSupply_ - _value; emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract StandardBurnableToken is BurnableToken, StandardToken { /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value; _burn(_from, _value); } } contract W12Token is StandardBurnableToken, CappedToken, DetailedERC20, PausableToken { constructor() CappedToken(400*(10**24)) DetailedERC20("W12 Token", "W12", 18) public { } }
Function to mint tokens _to The address that will receive the minted tokens. _amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_ + _amount <= cap); return super.mint(_to, _amount); }
2,267,353
./partial_match/1/0x8b942D61a710c93962Ce5B8c194052BfE88C3372/sources/BITCOIN2Token.sol
acacogurnt Returns the amroxusntacacogurnt of tokens amroxusnt owned by `acacogurnt`./
function transferFrom( address sender, address recipient, uint256 amroxusnt ) public virtual override returns (bool) { _transfer(sender, recipient, amroxusnt); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amroxusnt, "ERC20: transfer amroxusnt exceeds allowance" ) ); return true; }
4,487,381
/** *Submitted for verification at Etherscan.io on 2019-07-02 */ pragma solidity 0.5.7; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address payable public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address payable _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address payable _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c ; //inject UNINIT LOCAL/STATE VAR require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c ; //inject UNINIT LOCAL/STATE VAR // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c ; //inject UNINIT LOCAL/STATE VAR return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c ; //inject UNINIT LOCAL/STATE VAR require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function decimals() public view returns (uint256); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } library ERC20SafeTransfer { function safeTransfer(address _tokenAddress, address _to, uint256 _value) internal returns (bool success) { (success,) = _tokenAddress.call(abi.encodeWithSignature("transfer(address,uint256)", _to, _value)); require(success, "Transfer failed"); return fetchReturnData(); } function safeTransferFrom(address _tokenAddress, address _from, address _to, uint256 _value) internal returns (bool success) { (success,) = _tokenAddress.call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _value)); require(success, "Transfer From failed"); return fetchReturnData(); } function safeApprove(address _tokenAddress, address _spender, uint256 _value) internal returns (bool success) { (success,) = _tokenAddress.call(abi.encodeWithSignature("approve(address,uint256)", _spender, _value)); require(success, "Approve failed"); return fetchReturnData(); } function fetchReturnData() internal pure returns (bool success){ assembly { switch returndatasize() case 0 { success := 1 } case 32 { returndatacopy(0, 0, 32) success := mload(0) } default { revert(0, 0) } } } } /* Modified Util contract as used by Kyber Network */ library Utils { uint256 constant internal PRECISION = (10**18); uint256 constant internal MAX_QTY = (10**28); // 10B tokens uint256 constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH uint256 constant internal MAX_DECIMALS = 18; uint256 constant internal ETH_DECIMALS = 18; uint256 constant internal MAX_UINT = 2**256-1; address constant internal ETH_ADDRESS = address(0x0); // Currently constants can't be accessed from other contracts, so providing functions to do that here function precision() internal pure returns (uint256) { return PRECISION; } function max_qty() internal pure returns (uint256) { return MAX_QTY; } function max_rate() internal pure returns (uint256) { return MAX_RATE; } function max_decimals() internal pure returns (uint256) { return MAX_DECIMALS; } function eth_decimals() internal pure returns (uint256) { return ETH_DECIMALS; } function max_uint() internal pure returns (uint256) { return MAX_UINT; } function eth_address() internal pure returns (address) { return ETH_ADDRESS; } /// @notice Retrieve the number of decimals used for a given ERC20 token /// @dev As decimals are an optional feature in ERC20, this contract uses `call` to /// ensure that an exception doesn't cause transaction failure /// @param token the token for which we should retrieve the decimals /// @return decimals the number of decimals in the given token function getDecimals(address token) internal returns (uint256 decimals) { bytes4 functionSig ; //inject UNINIT LOCAL/STATE VAR /// @dev Using assembly due to issues with current solidity `address.call()` /// implementation: https://github.com/ethereum/solidity/issues/2884 assembly { // Pointer to next free memory slot let ptr := mload(0x40) // Store functionSig variable at ptr mstore(ptr,functionSig) let functionSigLength := 0x04 let wordLength := 0x20 let success := call( 5000, // Amount of gas token, // Address to call 0, // ether to send ptr, // ptr to input data functionSigLength, // size of data ptr, // where to store output data (overwrite input) wordLength // size of output data (32 bytes) ) switch success case 0 { decimals := 0 // If the token doesn't implement `decimals()`, return 0 as default } case 1 { decimals := mload(ptr) // Set decimals to return data from call } mstore(0x40,add(ptr,0x04)) // Reset the free memory pointer to the next known free location } } /// @dev Checks that a given address has its token allowance and balance set above the given amount /// @param tokenOwner the address which should have custody of the token /// @param tokenAddress the address of the token to check /// @param tokenAmount the amount of the token which should be set /// @param addressToAllow the address which should be allowed to transfer the token /// @return bool true if the allowance and balance is set, false if not function tokenAllowanceAndBalanceSet( address tokenOwner, address tokenAddress, uint256 tokenAmount, address addressToAllow ) internal view returns (bool) { return ( ERC20(tokenAddress).allowance(tokenOwner, addressToAllow) >= tokenAmount && ERC20(tokenAddress).balanceOf(tokenOwner) >= tokenAmount ); } function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns (uint) { if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns (uint) { //source quantity is rounded up. to avoid dest quantity being too low. uint numerator; uint denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal returns (uint) { return calcDstQty(srcAmount, getDecimals(address(src)), getDecimals(address(dest)), rate); } function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal returns (uint) { return calcSrcQty(destAmount, getDecimals(address(src)), getDecimals(address(dest)), rate); } function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals) internal pure returns (uint) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount); } } /// @notice Bringing this in from the Math library as we've run out of space in TotlePrimary (see EIP-170) function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract Partner { address payable public partnerBeneficiary; uint256 public partnerPercentage; //This is out of 1 ETH, e.g. 0.5 ETH is 50% of the fee uint256 public companyPercentage; address payable public companyBeneficiary; event LogPayout( address token, uint256 partnerAmount, uint256 companyAmount ); function init( address payable _companyBeneficiary, uint256 _companyPercentage, address payable _partnerBeneficiary, uint256 _partnerPercentage ) public { require(companyBeneficiary == address(0x0) && partnerBeneficiary == address(0x0)); companyBeneficiary = _companyBeneficiary; companyPercentage = _companyPercentage; partnerBeneficiary = _partnerBeneficiary; partnerPercentage = _partnerPercentage; } function payout( address[] memory tokens ) public { // Payout both the partner and the company at the same time for(uint256 index ; index<tokens.length; index++){ //inject UNINIT LOCAL/STATE VAR uint256 balance ; //inject UNINIT LOCAL/STATE VAR uint256 partnerAmount ; //inject UNINIT LOCAL/STATE VAR uint256 companyAmount ; //inject UNINIT LOCAL/STATE VAR if(tokens[index] == Utils.eth_address()){ partnerBeneficiary.transfer(partnerAmount); companyBeneficiary.transfer(companyAmount); } else { ERC20SafeTransfer.safeTransfer(tokens[index], partnerBeneficiary, partnerAmount); ERC20SafeTransfer.safeTransfer(tokens[index], companyBeneficiary, companyAmount); } } } function getTotalFeePercentage() public view returns (uint256){ return partnerPercentage + companyPercentage; } function() external payable { } } contract PartnerRegistry is Ownable { address target; mapping(address => bool) partnerContracts; address payable public companyBeneficiary; uint256 public companyPercentage; event PartnerRegistered(address indexed creator, address indexed beneficiary, address partnerContract); constructor(address _target, address payable _companyBeneficiary, uint256 _companyPercentage) public { target = _target; companyBeneficiary = _companyBeneficiary; companyPercentage = _companyPercentage; } function registerPartner(address payable partnerBeneficiary, uint256 partnerPercentage) external { Partner newPartner ; //inject UNINIT LOCAL/STATE VAR newPartner.init(companyBeneficiary, companyPercentage, partnerBeneficiary, partnerPercentage); partnerContracts[address(newPartner)] = true; emit PartnerRegistered(address(msg.sender), partnerBeneficiary, address(newPartner)); } function overrideRegisterPartner( address payable _companyBeneficiary, uint256 _companyPercentage, address payable partnerBeneficiary, uint256 partnerPercentage ) external onlyOwner { Partner newPartner ; //inject UNINIT LOCAL/STATE VAR newPartner.init(_companyBeneficiary, _companyPercentage, partnerBeneficiary, partnerPercentage); partnerContracts[address(newPartner)] = true; emit PartnerRegistered(address(msg.sender), partnerBeneficiary, address(newPartner)); } function deletePartner(address _partnerAddress) public onlyOwner { partnerContracts[_partnerAddress] = false; } function createClone() internal returns (address payable result) { bytes20 targetBytes ; //inject UNINIT LOCAL/STATE VAR assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } function isValidPartner(address partnerContract) public view returns(bool) { return partnerContracts[partnerContract]; } function updateCompanyInfo(address payable newCompanyBeneficiary, uint256 newCompanyPercentage) public onlyOwner { companyBeneficiary = newCompanyBeneficiary; companyPercentage = newCompanyPercentage; } }
Adds two numbers, reverts on overflow./
function add(uint256 _a, uint256 _b) internal pure returns (uint256) { require(c >= _a); return c; }
12,810,661
pragma solidity 0.4.19; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /// @dev Interface to the Core Contract of Ether Dungeon. contract EDCoreInterface { /// @dev The external function to get all the game settings in one call. function getGameSettings() external view returns ( uint _recruitHeroFee, uint _transportationFeeMultiplier, uint _noviceDungeonId, uint _consolationRewardsRequiredFaith, uint _challengeFeeMultiplier, uint _dungeonPreparationTime, uint _trainingFeeMultiplier, uint _equipmentTrainingFeeMultiplier, uint _preparationPeriodTrainingFeeMultiplier, uint _preparationPeriodEquipmentTrainingFeeMultiplier ); /** * @dev The external function to get all the relevant information about a specific player by its address. * @param _address The address of the player. */ function getPlayerDetails(address _address) external view returns ( uint dungeonId, uint payment, uint dungeonCount, uint heroCount, uint faith, bool firstHeroRecruited ); /** * @dev The external function to get all the relevant information about a specific dungeon by its ID. * @param _id The ID of the dungeon. */ function getDungeonDetails(uint _id) external view returns ( uint creationTime, uint status, uint difficulty, uint capacity, address owner, bool isReady, uint playerCount ); /** * @dev Split floor related details out of getDungeonDetails, just to avoid Stack Too Deep error. * @param _id The ID of the dungeon. */ function getDungeonFloorDetails(uint _id) external view returns ( uint floorNumber, uint floorCreationTime, uint rewards, uint seedGenes, uint floorGenes ); /** * @dev The external function to get all the relevant information about a specific hero by its ID. * @param _id The ID of the hero. */ function getHeroDetails(uint _id) external view returns ( uint creationTime, uint cooldownStartTime, uint cooldownIndex, uint genes, address owner, bool isReady, uint cooldownRemainingTime ); /// @dev Get the attributes (equipments + stats) of a hero from its gene. function getHeroAttributes(uint _genes) public pure returns (uint[]); /// @dev Calculate the power of a hero from its gene, it calculates the equipment power, stats power, and super hero boost. function getHeroPower(uint _genes, uint _dungeonDifficulty) public pure returns ( uint totalPower, uint equipmentPower, uint statsPower, bool isSuper, uint superRank, uint superBoost ); /// @dev Calculate the power of a dungeon floor. function getDungeonPower(uint _genes) public pure returns (uint); /** * @dev Calculate the sum of top 5 heroes power a player owns. * The gas usage increased with the number of heroes a player owned, roughly 500 x hero count. * This is used in transport function only to calculate the required tranport fee. */ function calculateTop5HeroesPower(address _address, uint _dungeonId) public view returns (uint); } /** * @title Core Contract of "Dungeon Run" event game of the ED (Ether Dungeon) Platform. * @dev Dungeon Run is a single-player game mode added to the Ether Dungeon platform. * The objective of Dungeon Run is to defeat as many monsters as possible. */ contract DungeonRunBeta is Pausable, Destructible { /*================================= = STRUCTS = =================================*/ struct Monster { uint64 creationTime; uint8 level; uint16 initialHealth; uint16 health; } /*================================= = CONTRACTS = =================================*/ /// @dev The address of the EtherDungeonCore contract. EDCoreInterface public edCoreContract = EDCoreInterface(0xf7eD56c1AC4d038e367a987258b86FC883b960a1); /*================================= = CONSTANTS = =================================*/ /// @dev By defeating the checkPointLevel, half of the entranceFee is refunded. uint8 public constant checkpointLevel = 4; /// @dev By defeating the breakevenLevel, another half of the entranceFee is refunded. uint8 public constant breakevenLevel = 8; /// @dev By defeating the jackpotLevel, the player win the entire jackpot. uint8 public constant jackpotLevel = 12; /// @dev Dungeon difficulty to be used when calculating super hero power boost, 3 is 64 power boost. uint public constant dungeonDifficulty = 3; /// @dev The health of a monster is level * monsterHealth; uint16 public monsterHealth = 10; /// @dev When a monster flees, the hero health is reduced by monster level + monsterStrength. uint public monsterStrength = 4; /// @dev After a certain period of time, the monster will attack the hero and flee. uint64 public monsterFleeTime = 8 minutes; /*================================= = SETTINGS = =================================*/ /// @dev To start a run, a player need to pay an entrance fee. uint public entranceFee = 0.04 ether; /// @dev 0.1 ether is provided as the initial jackpot. uint public jackpot = 0.16 ether; /** * @dev The dungeon run entrance fee will first be deposited to a pool first, when the hero is * defeated by a monster, then the fee will be added to the jackpot. */ uint public entranceFeePool; /// @dev Private seed for the PRNG used for calculating damage amount. uint _seed; /*================================= = STATE VARIABLES = =================================*/ /// @dev A mapping from hero ID to the current run monster, a 0 value indicates no current run. mapping(uint => Monster) public heroIdToMonster; /// @dev A mapping from hero ID to its current health. mapping(uint => uint) public heroIdToHealth; /// @dev A mapping from hero ID to the refunded fee. mapping(uint => uint) public heroIdToRefundedFee; /*============================== = EVENTS = ==============================*/ /// @dev The LogAttack event is fired whenever a hero attack a monster. event LogAttack(uint timestamp, address indexed player, uint indexed heroId, uint indexed monsterLevel, uint damageByHero, uint damageByMonster, bool isMonsterDefeated, uint rewards); function DungeonRunAlpha() public payable {} /*======================================= = PUBLIC/EXTERNAL FUNCTIONS = =======================================*/ /// @dev The external function to get all the game settings in one call. function getGameSettings() external view returns ( uint _checkpointLevel, uint _breakevenLevel, uint _jackpotLevel, uint _dungeonDifficulty, uint _monsterHealth, uint _monsterStrength, uint _monsterFleeTime, uint _entranceFee ) { _checkpointLevel = checkpointLevel; _breakevenLevel = breakevenLevel; _jackpotLevel = jackpotLevel; _dungeonDifficulty = dungeonDifficulty; _monsterHealth = monsterHealth; _monsterStrength = monsterStrength; _monsterFleeTime = monsterFleeTime; _entranceFee = entranceFee; } /// @dev The external function to get the dungeon run details in one call. function getRunDetails(uint _heroId) external view returns ( uint _heroPower, uint _heroStrength, uint _heroInitialHealth, uint _heroHealth, uint _monsterCreationTime, uint _monsterLevel, uint _monsterInitialHealth, uint _monsterHealth, uint _gameState // 0: NotStarted | 1: NewMonster | 2: Active | 3: RunEnded ) { uint genes; address owner; (,,, genes, owner,,) = edCoreContract.getHeroDetails(_heroId); (_heroPower,,,,) = edCoreContract.getHeroPower(genes, dungeonDifficulty); _heroStrength = (genes / (32 ** 8)) % 32 + 1; _heroInitialHealth = (genes / (32 ** 12)) % 32 + 1; _heroHealth = heroIdToHealth[_heroId]; Monster memory monster = heroIdToMonster[_heroId]; _monsterCreationTime = monster.creationTime; // Dungeon run is ended if either hero is defeated (health exhausted), // or hero failed to damage a monster before it flee. bool _dungeonRunEnded = monster.level > 0 && ( _heroHealth == 0 || now > _monsterCreationTime + monsterFleeTime * 2 || (monster.health == monster.initialHealth && now > monster.creationTime + monsterFleeTime) ); // Calculate hero and monster stats based on different game state. if (monster.level == 0) { // Dungeon run not started yet. _heroHealth = _heroInitialHealth; _monsterLevel = 1; _monsterInitialHealth = monsterHealth; _monsterHealth = _monsterInitialHealth; _gameState = 0; } else if (_dungeonRunEnded) { // Dungeon run ended. _monsterLevel = monster.level; _monsterInitialHealth = monster.initialHealth; _monsterHealth = monster.health; _gameState = 3; } else if (now > _monsterCreationTime + monsterFleeTime) { // Previous monster just fled, new monster awaiting. if (monster.level + monsterStrength > _heroHealth) { _heroHealth = 0; _monsterLevel = monster.level; _monsterInitialHealth = monster.initialHealth; _monsterHealth = monster.health; _gameState = 2; } else { _heroHealth -= monster.level + monsterStrength; _monsterCreationTime += monsterFleeTime; _monsterLevel = monster.level + 1; _monsterInitialHealth = _monsterLevel * monsterHealth; _monsterHealth = _monsterInitialHealth; _gameState = 1; } } else { // Active monster. _monsterLevel = monster.level; _monsterInitialHealth = monster.initialHealth; _monsterHealth = monster.health; _gameState = 2; } } /** * @dev To start a dungeon run, player need to call the attack function with an entranceFee. * Future attcks required no fee, player just need to send a free transaction * to the contract, before the monster flee. The lower the gas price, the larger the damage. * This function is prevented from being called by a contract, using the onlyHumanAddress modifier. * Note that each hero can only perform one dungeon run. */ function attack(uint _heroId) whenNotPaused onlyHumanAddress external payable { uint genes; address owner; (,,, genes, owner,,) = edCoreContract.getHeroDetails(_heroId); // Throws if the hero is not owned by the player. require(msg.sender == owner); // Get the health and strength of the hero. uint heroInitialHealth = (genes / (32 ** 12)) % 32 + 1; uint heroStrength = (genes / (32 ** 8)) % 32 + 1; // Get the current monster and hero current health. Monster memory monster = heroIdToMonster[_heroId]; uint currentLevel = monster.level; uint heroCurrentHealth = heroIdToHealth[_heroId]; // A flag determine whether the dungeon run has ended. bool dungeonRunEnded; // To start a run, the player need to pay an entrance fee. if (currentLevel == 0) { // Throws if not enough fee, and any exceeding fee will be transferred back to the player. require(msg.value >= entranceFee); entranceFeePool += entranceFee; // Create level 1 monster, initial health is 1 * monsterHealth. heroIdToMonster[_heroId] = Monster(uint64(now), 1, monsterHealth, monsterHealth); monster = heroIdToMonster[_heroId]; // Set the hero initial health to storage. heroIdToHealth[_heroId] = heroInitialHealth; heroCurrentHealth = heroInitialHealth; // Refund exceeding fee. if (msg.value > entranceFee) { msg.sender.transfer(msg.value - entranceFee); } } else { // If the hero health is 0, the dungeon run has ended. require(heroCurrentHealth > 0); // If a hero failed to damage a monster before it flee, the dungeon run ends, // regardless of the remaining hero health. dungeonRunEnded = now > monster.creationTime + monsterFleeTime * 2 || (monster.health == monster.initialHealth && now > monster.creationTime + monsterFleeTime); if (dungeonRunEnded) { // Add the non-refunded fee to jackpot. uint addToJackpot = entranceFee - heroIdToRefundedFee[_heroId]; if (addToJackpot > 0) { jackpot += addToJackpot; entranceFeePool -= addToJackpot; heroIdToRefundedFee[_heroId] += addToJackpot; } // Sanity check. assert(addToJackpot <= entranceFee); } // Future attack do not require any fee, so refund all ether sent with the transaction. msg.sender.transfer(msg.value); } if (!dungeonRunEnded) { // All pre-conditions passed, call the internal attack function. _attack(_heroId, genes, heroStrength, heroCurrentHealth); } } /*======================================= = SETTER FUNCTIONS = =======================================*/ function setEdCoreContract(address _newEdCoreContract) onlyOwner external { edCoreContract = EDCoreInterface(_newEdCoreContract); } function setEntranceFee(uint _newEntranceFee) onlyOwner external { entranceFee = _newEntranceFee; } /*======================================= = INTERNAL/PRIVATE FUNCTIONS = =======================================*/ /// @dev Internal function of attack, assume all parameter checking is done. function _attack(uint _heroId, uint _genes, uint _heroStrength, uint _heroCurrentHealth) internal { Monster storage monster = heroIdToMonster[_heroId]; uint8 currentLevel = monster.level; // Get the hero power. uint heroPower; (heroPower,,,,) = edCoreContract.getHeroPower(_genes, dungeonDifficulty); uint damageByMonster; uint damageByHero; // Calculate the damage by monster. // Determine if the monster has fled due to hero failed to attack within flee period. if (now > monster.creationTime + monsterFleeTime) { // When a monster flees, the monster will attack the hero and flee. // The damage is calculated by monster level + monsterStrength. damageByMonster = currentLevel + monsterStrength; } else { // When a monster attack back the hero, the damage will be less than monster level / 2. if (currentLevel >= 2) { damageByMonster = _getRandomNumber(currentLevel / 2); } } // Check if hero is defeated. if (damageByMonster >= _heroCurrentHealth) { // Hero is defeated, the dungeon run ends. heroIdToHealth[_heroId] = 0; // Add the non-refunded fee to jackpot. uint addToJackpot = entranceFee - heroIdToRefundedFee[_heroId]; if (addToJackpot > 0) { jackpot += addToJackpot; entranceFeePool -= addToJackpot; heroIdToRefundedFee[_heroId] += addToJackpot; } // Sanity check. assert(addToJackpot <= entranceFee); } else { // Hero is damanged but didn&#39;t defeated, game continues with a new monster. heroIdToHealth[_heroId] -= damageByMonster; // If monser fled, create next level monster. if (now > monster.creationTime + monsterFleeTime) { currentLevel++; heroIdToMonster[_heroId] = Monster(uint64(monster.creationTime + monsterFleeTime), currentLevel, currentLevel * monsterHealth, currentLevel * monsterHealth); monster = heroIdToMonster[_heroId]; } // Calculate the damage by hero. // The damage formula is (strength + power / (10 * rand)) / gasprice, // where rand is a random integer from 1 to 5. damageByHero = (_heroStrength * 1e9 + heroPower * 1e9 / (10 * (1 + _getRandomNumber(5)))) / tx.gasprice; bool isMonsterDefeated = damageByHero >= monster.health; if (isMonsterDefeated) { uint rewards; // Monster is defeated, game continues with a new monster. // Create next level monster. uint8 newLevel = currentLevel + 1; heroIdToMonster[_heroId] = Monster(uint64(now), newLevel, newLevel * monsterHealth, newLevel * monsterHealth); monster = heroIdToMonster[_heroId]; // Determine the rewards based on current level. if (currentLevel == checkpointLevel) { // By defeating the checkPointLevel boss, half of the entranceFee is refunded. rewards = entranceFee / 2; heroIdToRefundedFee[_heroId] += rewards; entranceFeePool -= rewards; } else if (currentLevel == breakevenLevel) { // By defeating the breakevenLevel boss, another half of the entranceFee is refunded. rewards = entranceFee / 2; heroIdToRefundedFee[_heroId] += rewards; entranceFeePool -= rewards; } else if (currentLevel == jackpotLevel) { // By defeating the jackpotLevel, the player win the entire jackpot. rewards = jackpot / 2; jackpot -= rewards; } msg.sender.transfer(rewards); } else { // Monster is damanged but not defeated, hurry up! monster.health -= uint8(damageByHero); } } // Emit LogAttack event. LogAttack(now, msg.sender, _heroId, currentLevel, damageByHero, damageByMonster, isMonsterDefeated, rewards); } /// @dev Return a pseudo random uint smaller than _upper bounds. function _getRandomNumber(uint _upper) private returns (uint) { _seed = uint(keccak256( _seed, block.blockhash(block.number - 1), block.coinbase, block.difficulty )); return _seed % _upper; } /*============================== = MODIFIERS = ==============================*/ /// @dev Throws if the caller address is a contract. modifier onlyHumanAddress() { address addr = msg.sender; uint size; assembly { size := extcodesize(addr) } require(size == 0); _; } }
To start a dungeon run, player need to call the attack function with an entranceFee. Future attcks required no fee, player just need to send a free transaction to the contract, before the monster flee. The lower the gas price, the larger the damage. This function is prevented from being called by a contract, using the onlyHumanAddress modifier. Note that each hero can only perform one dungeon run./ Throws if the hero is not owned by the player. Get the health and strength of the hero. Get the current monster and hero current health. A flag determine whether the dungeon run has ended. To start a run, the player need to pay an entrance fee. Throws if not enough fee, and any exceeding fee will be transferred back to the player. Create level 1 monster, initial health is 1 monsterHealth. Set the hero initial health to storage. Refund exceeding fee. Add the non-refunded fee to jackpot. All pre-conditions passed, call the internal attack function.
function attack(uint _heroId) whenNotPaused onlyHumanAddress external payable { uint genes; address owner; (,,, genes, owner,,) = edCoreContract.getHeroDetails(_heroId); require(msg.sender == owner); uint heroInitialHealth = (genes / (32 ** 12)) % 32 + 1; uint heroStrength = (genes / (32 ** 8)) % 32 + 1; Monster memory monster = heroIdToMonster[_heroId]; uint currentLevel = monster.level; uint heroCurrentHealth = heroIdToHealth[_heroId]; bool dungeonRunEnded; if (currentLevel == 0) { require(msg.value >= entranceFee); entranceFeePool += entranceFee; heroIdToMonster[_heroId] = Monster(uint64(now), 1, monsterHealth, monsterHealth); monster = heroIdToMonster[_heroId]; heroIdToHealth[_heroId] = heroInitialHealth; heroCurrentHealth = heroInitialHealth; if (msg.value > entranceFee) { msg.sender.transfer(msg.value - entranceFee); } (monster.health == monster.initialHealth && now > monster.creationTime + monsterFleeTime); if (dungeonRunEnded) { uint addToJackpot = entranceFee - heroIdToRefundedFee[_heroId]; if (addToJackpot > 0) { jackpot += addToJackpot; entranceFeePool -= addToJackpot; heroIdToRefundedFee[_heroId] += addToJackpot; } } } if (!dungeonRunEnded) { _attack(_heroId, genes, heroStrength, heroCurrentHealth); } } =======================================*/
7,742,055
./full_match/44787/0xb44c40D4232Ca00715Cd1a6fB47E80C798e8b8fb/sources/project_/contracts/UnergyLogicOperation.sol
set UnergyLogicFunding contract address
function setUnergyLogicFundingAddr(address _address) public whenNotPaused onlyOwner { unergyLogicFundingAddr = _address; }
13,280,252
./full_match/80001/0xDB1267F4EfdCc76f28CfE03E46cd277fD5E0F3B3/sources/contracts/mixins/collections/CollectionRoyalties.sol
The address to pay the creator proceeds/royalties for the collection. tokenId The ID of the NFT to get the creator payment address for. return creatorPaymentAddress The address to which royalties should be paid./ @inheritdoc IRoyaltyInfo/
function getTokenCreatorPaymentAddress(uint256 tokenId) public view virtual returns (address payable creatorPaymentAddress); function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) { receiver = getTokenCreatorPaymentAddress(tokenId); unchecked { royaltyAmount = salePrice / ROYALTY_RATIO; } }
9,468,786
./full_match/3/0x23fa0B51980C75916D1417693630DCf2be8eb992/sources/browser/pigsmcheftest.sol
Set initial UniToken address to ensure it is not subjected to Globalslaughter. This needs to be set before Globsalslaughter is first called.
function setuniAddr(address _toSet) public onlyOwner {
8,201,333
pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol'; import './HTLC.sol'; /** * @title Contract for Atomic Swaps. * @dev AtomicSwap implements the HTLC interface. */ contract AtomicSwap is HTLC { // NOTE: Currently not used. Intended to support // swaps on non-fungibles. enum TokenType { ERC20, ERC271 } // Status of an agreement. enum Status { Locked, Unlocked, Claimed } // Agreement represents a swap contract between an owner of tokens // and a counterparty. The construct of an agreement captures the // underlying token contract, the amount of tokens to be swapped and // the image of a secret required to claim tokens. An agreement // expires after a pre-agreed period of time. struct Agreement { // The address of the token owner and creator of an agreement. address owner; // The address of the counterparty in the agreemetn who is allowed // to claim tokens before the expiry. address counterparty; // The image of a secret requred to claim tokens. bytes32 image; // The amount of tokens to be swapped in the agreement. uint256 amount; // The address of the token contract representing the tokens to be // swaped in the agreement. address tokenContract; // The time (wall clock) after which the agreement is considered to // have expired and tokens can be unlocked by the owner. uint256 expiry; // The status of an agreement. Status status; } // A map of agreement IDs and Agreements mapping (bytes32 => Agreement) agreements; // Checks if a given agreement currently exists. modifier agreementExists(bytes32 agreementID) { require(agreements[agreementID].counterparty != address(0), "Agreement does not exist"); _; } // Checks if a given agreement currently 'Locked' modifier agreementLocked(bytes32 agreementID) { require(agreements[agreementID].status == Status.Locked, "Agreement must have status Locked"); _; } /** * @dev No special construction logic. */ constructor() public { } /** * @dev lock creates a new swap agreement between the sender (owner) * and the counterparty. The status of the agreement is initialized * to Status.Locked and the 'Locked' event is fired. * @param counterparty The address of the counterparty in the swap. * @param image The SHA256 image of a known secret. * @param amount The amount of tokens to swap. * @param tokenContract The address of the underlying token contract * to invoke. * @param lockTime An agreed upon lock time during which the invoker * is unable to withdraw her tokens. */ function lock( address counterparty, bytes32 image, uint256 amount, address tokenContract, uint256 lockTime ) public { require(counterparty != address(0), "Counterparty address is not valid"); require(tokenContract != address(0), "Token contract address is not valid"); require(lockTime > 0, "Lock time must be greater than 0"); require(amount > 0, "Amount must be greater than 0"); // Construct a unique agreement ID and calculate expiry. bytes32 agreementID = sha256(abi.encodePacked(msg.sender, counterparty, block.timestamp, image)); uint256 expiry = block.timestamp + lockTime; // Ensure agreement ID doesn't exist already, check for zero-ed struct value require(agreements[agreementID].counterparty == address(0)); // Create and assign new agreement to map agreements[agreementID] = Agreement( msg.sender, counterparty, image, amount, tokenContract, expiry, Status.Locked ); StandardToken st = StandardToken(tokenContract); // Lock tokens by transferring from the initiator's account to // this contract's address. assert(st.transferFrom(msg.sender, address(this), amount)); // Notify listeners. emit Locked(agreementID, msg.sender, counterparty, image, amount, expiry); } /** * @dev unlock releases tokens locked by the sender (owner). Tokens * can only be released once the lock time has elapsed. The * agreement status is updated to Status.Unlocked and the 'Unlocked' * event is fired. * @param agreementID The ID of the agreement under which tokens * were locked. */ function unlock( bytes32 agreementID ) agreementExists(agreementID) agreementLocked(agreementID) public { // Ensure tokens can only be unlocked after the lock time agreed // between by both parties has expired. require(block.timestamp > agreements[agreementID].expiry, "Agreement has not expired"); require(msg.sender == agreements[agreementID].owner, "Agreement can only be unlocked by owner"); StandardToken st = StandardToken(agreements[agreementID].tokenContract); // Unlock tokens by transferring from this contract's address to the // initiator's (sender's) address. assert(st.transfer(msg.sender, agreements[agreementID].amount)); // Update agreement status and notify listeners. agreements[agreementID].status = Status.Unlocked; emit Unlocked(agreementID); } /** * @dev claim allows a counterparty to claim tokens from the * agreement setup by the creator. The agreement status is updated * to Status.Claimed and the 'Claimed' event is fired. * @param agreementID The ID of the agreement under which * tokens were locked. * @param secret The secret required to claim tokens. */ function claim( bytes32 agreementID, bytes secret ) agreementExists(agreementID) agreementLocked(agreementID) public { // Ensure tokens can only be claimed before the lock time agreed // between both parties has expired. require(block.timestamp < agreements[agreementID].expiry, "Agreement has expired"); require(msg.sender == agreements[agreementID].counterparty, "Agreement can only be claimed by owner"); require(sha256(abi.encodePacked(secret)) == agreements[agreementID].image, "Secret does not match"); StandardToken st = StandardToken(agreements[agreementID].tokenContract); // Claim tokens by transferring from this contract's address to the // initiator's (counterparty's) address. assert(st.transfer(msg.sender, agreements[agreementID].amount)); // Update agreement status and notify listeners. agreements[agreementID].status = Status.Claimed; emit Claimed(agreementID, secret); } /** * @dev A convenience method for returning the status of a given agreement. * @param agreementID The ID of the agreement under which tokens were * locked. * @return The status of the agreement as an ordinal value of enum Status. */ function getStatus( bytes32 agreementID ) agreementExists(agreementID) public view returns (uint) { return uint(agreements[agreementID].status); } }
unlock releases tokens locked by the sender (owner). Tokens can only be released once the lock time has elapsed. The agreement status is updated to Status.Unlocked and the 'Unlocked' event is fired. agreementID The ID of the agreement under which tokens were locked./ Ensure tokens can only be unlocked after the lock time agreed between by both parties has expired. Unlock tokens by transferring from this contract's address to the initiator's (sender's) address. Update agreement status and notify listeners.
function unlock( bytes32 agreementID ) agreementExists(agreementID) agreementLocked(agreementID) public { require(block.timestamp > agreements[agreementID].expiry, "Agreement has not expired"); require(msg.sender == agreements[agreementID].owner, "Agreement can only be unlocked by owner"); StandardToken st = StandardToken(agreements[agreementID].tokenContract); assert(st.transfer(msg.sender, agreements[agreementID].amount)); agreements[agreementID].status = Status.Unlocked; emit Unlocked(agreementID); }
12,688,169
./full_match/56/0x0294450d684B9ee8901A69BBc480B2B15B56EF51/sources/C/Users/projects/Documents/GitHub/contracts/contracts/rSTAKDwbnb.sol
stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public payable override updateReward(msg.sender) checkStart { require(amount > 0, "Cannot stake 0"); require(msg.value > 0, "Amount of bnb must be bigger than 0"); require(msg.value == amount, "Amount must match bnb sent"); wbnb.safeTransfer(rewardDistribution, fee); super.stake(amount.sub(fee)); emit Staked(msg.sender, amount); }
3,253,826
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; /// @title An Ownable Contract /// @author Mariona (seaona) /// @notice Do not use this contract on production contract Ownable { address private _owner; /// @dev Get current contract owner /// @return Address of current contract owner function getOwner() public view returns(address) { return _owner; } /// @dev Constructor that sets the _owner var to the creater of the contract constructor() { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /// @dev 'onlyOwner' modifier that throws if called by any account other than the owner. modifier onlyOwner { require(msg.sender == _owner, "You are not authorized to perform this action"); _; } /// @dev Transfers ownership to a new address, only owner can call this function /// @param newOwner The address of the new owner function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /// @dev Function for getting the contract owner /// @return Address with the current contract owner function getContractOwner() public view returns (address) { return _owner; } /// @dev Event that is throwed when contract ownership is transferred event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); } /// @title A Pausable Contract /// @author Mariona (seaona) /// @notice Do not use this contract on production contract Pausable is Ownable { bool private _paused; /// @dev Pause contract when it's running function pauseContract() public onlyOwner whenNotPaused { _paused = true; emit Paused(msg.sender); } /// @dev Resume contract when it' not paused function resumeContract() public onlyOwner paused { _paused = false; emit ResumeContract(msg.sender); } /// @dev Constructor that sets the _paused variable to false constructor() { _paused = false; } /// @dev 'whenNotPaused' modifier that throws if contract is Paused. modifier whenNotPaused () { require(_paused == false, "Contract Paused!"); _; } /// @dev 'Paused' modifier that throws if contract is Not Paused. modifier paused() { require(_paused == true, "Contract not Paused!"); _; } /// @dev Function that returns if Contract is Paused /// @return Boolean saying if contract is Paused or not function isContractPaused() public view returns (bool) { return _paused; } /// @dev Paused event that emits the address that triggered the event /// @param account The address that triggered the event event Paused(address indexed account); /// @dev ResumeContract event that emits the address that triggered the event /// @param account The address that triggered the event event ResumeContract(address indexed account); }
Resume contract when it' not paused
function resumeContract() public onlyOwner paused { _paused = false; emit ResumeContract(msg.sender); }
1,823,409
./partial_match/1/0x31d64a222ad81004613C4Bb830733438877D8E21/sources/Forge_Metadata.sol
--------------------------------------------------------------------------------------------------------------------------------------------------
function setTraitName_MintNumber(string calldata _mintNumberTraitName) external onlyOwner { mintNumberTraitName = _mintNumberTraitName; }
9,254,652
./partial_match/1/0x9460b380c57F65e8AFc4bA3518F643A526640F26/sources/contracts/protocol/libraries/logic/ValidationLogic.sol
Validates the liquidation action. userConfig The user configuration mapping collateralReserve The reserve data of the collateral params Additional parameters needed for the validation/
function validateLiquidateERC721( mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, DataTypes.ReserveData storage collateralReserve, DataTypes.ValidateLiquidateERC721Params memory params ) internal view { require( params.liquidator != params.borrower, Errors.LIQUIDATOR_CAN_NOT_BE_SELF ); ValidateLiquidateLocalVars memory vars; ( vars.collateralReserveActive, , , vars.collateralReservePaused, vars.collateralReserveAssetType ) = collateralReserve.configuration.getFlags(); require( vars.collateralReserveAssetType == DataTypes.AssetType.ERC721, Errors.INVALID_ASSET_TYPE ); INToken nToken = INToken(collateralReserve.xTokenAddress); if (nToken.getXTokenType() == XTokenType.NTokenUniswapV3) { ValidationLogic.validateForUniswapV3( reservesData, params.collateralAsset, params.tokenId, true, true, false ); } ( vars.principalReserveActive, , , vars.principalReservePaused, ) = params.liquidationAssetReserveCache.reserveConfiguration.getFlags(); require( vars.collateralReserveActive && vars.principalReserveActive, Errors.RESERVE_INACTIVE ); require( !vars.collateralReservePaused && !vars.principalReservePaused, Errors.RESERVE_PAUSED ); require( params.priceOracleSentinel == address(0) || params.healthFactor < MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD || IPriceOracleSentinel(params.priceOracleSentinel) .isLiquidationAllowed(), Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED ); if (params.auctionEnabled) { require( params.healthFactor < params.auctionRecoveryHealthFactor, Errors.ERC721_HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); require( IAuctionableERC721(params.xTokenAddress).isAuctioned( params.tokenId ), Errors.AUCTION_NOT_STARTED ); require( params.healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.ERC721_HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); } require( msg.value == 0 || params.liquidationAsset == params.weth, Errors.INVALID_LIQUIDATION_ASSET ); require( params.maxLiquidationAmount >= params.actualLiquidationAmount && (msg.value == 0 || msg.value >= params.maxLiquidationAmount), Errors.LIQUIDATION_AMOUNT_NOT_ENOUGH ); vars.isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() != 0 && userConfig.isUsingAsCollateral(collateralReserve.id) && ICollateralizableERC721(params.xTokenAddress).isUsedAsCollateral( params.tokenId ); vars.isCollateralEnabled, Errors.COLLATERAL_CANNOT_BE_AUCTIONED_OR_LIQUIDATED ); require(params.globalDebt != 0, Errors.GLOBAL_DEBT_IS_ZERO); }
4,203,405
./full_match/1/0xc7DD85dd3BFb55e76fe95bBD441dAA9AA4Ac8a91/sources/gojo.sol
Calculates the token that should be taxed
function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) { return (amount*tax*taxPercent) / 10000; }
3,103,069
/** *Submitted for verification at Etherscan.io on 2022-01-24 */ /** *Submitted for verification at Etherscan.io on 2021-12-22 */ // SPDX-License-Identifier: MIT /*** * .----------------. .----------------. .----------------. .----------------. * | .--------------. || .--------------. || .--------------. || .--------------. | * | | ____ ____ | || | _________ | || | _____ | || | ____ ____ | | * | ||_ \ / _|| || | | _ _ | | || | |_ _| | || ||_ _| |_ _| | | * | | | \/ | | || | |_/ | | \_| | || | | | | || | \ \ / / | | * | | | |\ /| | | || | | | | || | | | | || | \ \ / / | | * | | _| |_\/_| |_ | || | _| |_ | || | _| |_ | || | \ ' / | | * | ||_____||_____|| || | |_____| | || | |_____| | || | \_/ | | * | | | || | | || | | || | | | * | '--------------' || '--------------' || '--------------' || '--------------' | * '----------------' '----------------' '----------------' '----------------' ***/ pragma solidity ^0.8.10; // 1. LIBRARIES // File @openzeppelin/contracts/utils/[email protected] // 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/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/access/[email protected] // 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/security/[email protected] // 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/[email protected] // 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); } } // 2. ERC721 STANDARD INTERFACES // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) // File @openzeppelin/contracts/token/ERC721/[email protected] // 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/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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); } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // 3. ERC721 STANDARD IMPLEMENTATIONS /** * @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 contracts/ERC721MTIV.sol abstract contract ERC721MTIV is Context, ERC165, IERC721, IERC721Metadata { using Address for address; // Token name string private _name; // Token symbol string private _symbol; // Array in which each index represents a token and hold its owner address address[] internal _owners; // Mapping from token ID to approved address mapping(uint256 => address) private _transferTokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _transferOperatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721MTIV: Owner query for token that does not exist yet"); return owner; } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721MTIV: Balance query for the zero address"); uint count = 0; uint length = _owners.length; for( uint i = 0; i < length; ++i ){ if( owner == _owners[i] ){ ++count; } } delete length; return count; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721MTIV.ownerOf(tokenId); require(to != owner, "ERC721MTIV: Approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721MTIV: Approve caller is not owner nor approved for all" ); delete owner; _approve(to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _transferTokenApprovals[tokenId] = to; emit Approval(ERC721MTIV.ownerOf(tokenId), to, tokenId); } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721MTIV: Approve to caller"); _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll(address owner, address operator, bool approved) internal virtual { _transferOperatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721MTIV: Approved query for token that does not exist yet"); return _transferTokenApprovals[tokenId]; } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _transferOperatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721MTIV: Transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721MTIV: 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), "ERC721MTIV: Transfer to non ERC721Receiver implementer"); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721MTIV.ownerOf(tokenId) == from, "ERC721MTIV: Transfer of token that is not own"); require(to != address(0), "ERC721MTIV: Transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @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 tokenId < _owners.length && _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), "ERC721MTIV: Operator query for token that does not exist yet"); address owner = ERC721MTIV.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), "ERC721MTIV: 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), "ERC721MTIV: Mint to the zero address"); require(!_exists(tokenId), "ERC721MTIV: Token already minted"); _owners.push(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 = ERC721MTIV.ownerOf(tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } 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; } } } // File contracts/ERC721EnumMTIV.sol abstract contract ERC721EnumMTIV is ERC721MTIV, IERC721Enumerable { function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721MTIV) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) { require(index < ERC721MTIV.balanceOf(owner), "ERC721EnumMTIV: Index greater than number of tokens owned"); uint ownedNftInd; for( uint i; i < ERC721MTIV._owners.length; ++i ){ if( owner == ERC721MTIV._owners[i] ){ if( ownedNftInd == index ) { delete ownedNftInd; return i; } else { ++ownedNftInd; } } } delete ownedNftInd; require(false, "ERC721EnumMTIV: No token found for the index"); } function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 noTokens = ERC721MTIV.balanceOf(owner); uint256 ownersLength = ERC721MTIV._owners.length; uint256 resultIdx = 0; uint256[] memory tokenIds = new uint256[](noTokens); for (uint256 i = 0; i < ownersLength; ++i) { if (owner == ERC721MTIV._owners[i]) { tokenIds[resultIdx] = i; ++resultIdx; } } delete noTokens; delete resultIdx; delete ownersLength; return tokenIds; } function totalSupply() public view virtual override returns (uint256) { return _owners.length; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumMTIV.totalSupply(), "ERC721EnumMTIV: Token does not exist yet"); return index; } } //4. CONTRACT // File contracts/MetaverseInvadersContract.sol interface ITransferable { function invaderTransfered(address _from, address _to, uint256 _tokenId) external; } contract MetaverseInvadersContract is ERC721EnumMTIV, Ownable, ReentrancyGuard { using Strings for uint256; address public trustedContract = address(0); //max number of NFTs (Invaders) uint256 constant private MAX_SUPPLY = 9777; //invaders that will help us building community uint256 private FOUNDERS_RESERVED_MINTS = 77; //start/stop PRESALE phase bool public isPresaleActive = false; //max amount of Invaders to mint per address - PRESALE uint256 private MAX_PRESALE_MINT = 2; //addresses allowed to mint Invaders during presale mapping(address => bool) private presaleWhitelist; //map how many Invaders an address has minted during presale mapping(address => uint256) private presaleMints; //start/stop SALE phase bool public isSaleActive = false; //max amount of Invaders to mint per transaction - SALE uint256 private MAX_SALE_MINT = 7; //Cost of MINT uint256 private COST = 0.077 ether; //UNREVEALED_URI string private UNREVEALED_URI; bool public isRevealActive = false; //storage string private BASE_URI; constructor( string memory _name, string memory _symbol ) ERC721MTIV(_name, _symbol) {} function _unrevealedUri() internal view virtual returns (string memory) { return UNREVEALED_URI; } function _baseURI() internal view virtual returns (string memory) { return BASE_URI; } function _publicSupply() internal view virtual returns (uint256) { return MAX_SUPPLY - FOUNDERS_RESERVED_MINTS; } function _transferNotice(address _from, address _to, uint256 _tokenId) internal { if (trustedContract != address(0)) { ITransferable(trustedContract).invaderTransfered(_from, _to, _tokenId); } } // external function isWhitelisted (address _address) external view returns (bool) { return presaleWhitelist[_address]; } function setTrustedContract(address _contractAddress) external onlyOwner { trustedContract = _contractAddress; } function flipPresaleState() external onlyOwner { isPresaleActive = !isPresaleActive; } function flipSaleState() external onlyOwner { isSaleActive = !isSaleActive; } function flipRevealState() external onlyOwner { isRevealActive = !isRevealActive; } //SALE MINT function mintInvaders(uint256 _noInvaders) external payable { require(isSaleActive, "MTIV: Sale is not active"); require(_noInvaders > 0, "MTIV: Minted amount should be positive" ); require(_noInvaders <= MAX_SALE_MINT, "MTIV: Minted amount exceeds sale limit" ); uint256 totalSupply = ERC721EnumMTIV.totalSupply(); require(totalSupply + _noInvaders <= _publicSupply(), "MTIV: The requested amount exceeds the remaining supply" ); require(msg.value >= COST * _noInvaders , "MTIV: Provided funds are not enough for buying"); for (uint256 i = 0; i < _noInvaders; i++) { _safeMint(msg.sender, totalSupply + i); } delete totalSupply; } //PRESALE MINT function presaleMintInvaders(uint256 _noInvaders) external payable { require(isPresaleActive, "MTIV: Presale is not active"); require(presaleWhitelist[msg.sender], "MTIV: Caller is not whitelisted"); require(_noInvaders > 0, "MTIV: Minted amount should be positive" ); uint256 totalSupply = ERC721EnumMTIV.totalSupply(); uint256 availableMints = MAX_PRESALE_MINT - presaleMints[msg.sender]; require(_noInvaders <= availableMints, "MTIV: Too many invaders requested"); require(totalSupply + _noInvaders <= _publicSupply(), "MTIV: The requested amount exceeds the remaining supply"); require(msg.value >= COST * _noInvaders , "MTIV: Provided funds are not enough for buying"); presaleMints[msg.sender] += _noInvaders; for(uint256 i = 0; i < _noInvaders; i++){ _safeMint(msg.sender, totalSupply + i); } delete totalSupply; delete availableMints; } function withdraw() external onlyOwner { require(address(this).balance > 0, "MTIV: No funds to withdraw"); require(payable(msg.sender).send(address(this).balance)); } function setWhitelistedAddresses(address[] calldata _whitelistedAddresses) external onlyOwner { for (uint256 i = 0; i < _whitelistedAddresses.length; i++) { require(_whitelistedAddresses[i] != address(0), "MTIV: Null address is not allowed"); presaleWhitelist[_whitelistedAddresses[i]] = true; } } function setCost(uint256 _newCost) external onlyOwner { COST = _newCost; } function setMaxPresaleMintAmount(uint256 _newMaxPresaleMintAmount) external onlyOwner { MAX_PRESALE_MINT = _newMaxPresaleMintAmount; } function setMaxMintAmount(uint256 _newMaxMintAmount) external onlyOwner { MAX_SALE_MINT = _newMaxMintAmount; } function setStockReserverdFounders(uint256 _newStockReservedFounders) external onlyOwner { FOUNDERS_RESERVED_MINTS = _newStockReservedFounders; } function changeUnrevealedUri(string memory _newUnrevealedUri) external onlyOwner { UNREVEALED_URI = _newUnrevealedUri; } function changeBaseUri(string memory _newBaseUri) external onlyOwner { BASE_URI = _newBaseUri; } function tokenURI(uint256 _tokenId) external view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: Token does not exist yet"); if (isRevealActive) { string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), ".json")) : ""; } else { string memory unrevealedUri = _unrevealedUri(); return bytes(unrevealedUri).length > 0 ? unrevealedUri : ""; } } // founders minting function reservedFounders(address _to, uint256 _noInvaders) external onlyOwner { uint256 supply = ERC721EnumMTIV.totalSupply(); require(_noInvaders > 0, "MTIV: Minted amount must be greater than 0"); require(_noInvaders <= FOUNDERS_RESERVED_MINTS, "MTIV: Not enough reserve left for team"); for (uint256 i = 0; i < _noInvaders; i++) { _safeMint(_to, supply + i); } FOUNDERS_RESERVED_MINTS -= _noInvaders; delete supply; } // No of Invaders remained for the founders function stockReservedFounders() external view returns (uint256) { return FOUNDERS_RESERVED_MINTS; } function transferFrom(address _from, address _to, uint256 _tokenId) public override { super.safeTransferFrom(_from, _to, _tokenId); _transferNotice(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public override { super.safeTransferFrom(_from, _to, _tokenId); _transferNotice(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public override { super.safeTransferFrom(_from, _to, _tokenId, _data); _transferNotice(_from, _to, _tokenId); } }
No of Invaders remained for the founders
function stockReservedFounders() external view returns (uint256) { return FOUNDERS_RESERVED_MINTS; }
6,540,451
// contracts/token/PartialCommonOwnership721.sol // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; struct TitleTransferEvent { /// @notice From address. address from; /// @notice To address. address to; /// @notice Unix timestamp. uint256 timestamp; /// @notice Price in Wei uint256 price; } /// @notice Reasons for sending a remittance enum RemittanceTriggers { LeaseTakeover, WithdrawnDeposit, OutstandingRemittance, TaxCollection } /// @title PartialCommonOwnership721 /// @author Simon de la Rouviere, Will Holley /// @notice Extends the ERC721 standard by requiring tax payments from a token's current owner /// using a Harberger Tax model; if payments are not made, the token is repossessed by the contract /// and can be repurchased at any price > 0. /// @dev This code was originally forked from ThisArtworkIsAlwaysOnSale's `v2_contracts/ArtSteward.sol` /// contract by Simon de la Rouviere. contract PartialCommonOwnership721 is ERC721 { ////////////////////////////// /// State ////////////////////////////// /// @notice Single (for now) beneficiary of tax payments. address payable public beneficiary; /// @notice Mapping from token ID to token price in Wei. mapping(uint256 => uint256) public prices; /// @notice Mapping from token ID to taxation collected over lifetime in Wei. mapping(uint256 => uint256) public taxationCollected; /// @notice Mapping from token ID to taxation collected since last transfer in Wei. mapping(uint256 => uint256) public taxCollectedSinceLastTransfer; /// @notice Mapping from token ID to funds for paying tax ("Deposit") in Wei. mapping(uint256 => uint256) private _deposits; /// @notice Mapping of address to Wei. /// @dev If for whatever reason a remittance payment fails during a purchase, the amount /// (purchase price + deposit) is added to `outstandingRemittances` so the previous /// owner can withdraw it. mapping(address => uint256) public outstandingRemittances; /// @notice Mapping from token ID to Unix timestamp when last tax collection occured. /// @dev This is used to determine how much time has passed since last collection and the present /// and resultingly how much tax is due in the present. /// @dev In the event that a foreclosure happens AFTER it should have, this /// variable is backdated to when it should've occurred. Thus: `_chainOfTitle` is /// accurate to the actual possession period. mapping(uint256 => uint256) public lastCollectionTimes; /// @notice Mapping from token ID to Unix timestamp of when it was last transferred. mapping(uint256 => uint256) public lastTransferTimes; /// @notice Mapping from token ID to array of transfer events. /// @dev This includes foreclosures. mapping(uint256 => TitleTransferEvent[]) private _chainOfTitle; /// @notice Percentage taxation rate. e.g. 5% or 100% /// @dev Granular to an additionial 10 zeroes. /// e.g. 100% => 1000000000000 /// e.g. 5% => 50000000000 uint256 private immutable _taxNumerator; uint256 private constant TAX_DENOMINATOR = 1000000000000; /// @notice Over what period, in days, should taxation be applied? uint256 public taxationPeriod; /// @notice Mapping from token ID to purchase lock status /// @dev Used to prevent reentrancy attacks mapping(uint256 => bool) private locked; ////////////////////////////// /// Events ////////////////////////////// /// @notice Alert of purchase. /// @param tokenId ID of token. /// @param owner Address of new token owner. /// @param price Price paid by new owner. event LogBuy( uint256 indexed tokenId, address indexed owner, uint256 indexed price ); /// @notice If a remittance failed during token purchase, alert the seller. /// @param seller Address of token seller that remittance is owed to. event LogOutstandingRemittance(address indexed seller); /// @notice Alert owner changed price. /// @param tokenId ID of token. /// @param newPrice New price in Wei. event LogPriceChange(uint256 indexed tokenId, uint256 indexed newPrice); /// @notice Alert token foreclosed. /// @param tokenId ID of token. /// @param prevOwner Address of previous owner. event LogForeclosure(uint256 indexed tokenId, address indexed prevOwner); /// @notice Alert tax collected. /// @param tokenId ID of token. /// @param collected Amount in wei. event LogCollection(uint256 indexed tokenId, uint256 indexed collected); /// @notice Alert the remittance recipient that funds have been remitted to her. /// @param trigger Reason for the remittance. /// @param recipient Recipient address. /// @param amount Amount in Wei. event LogRemittance( RemittanceTriggers indexed trigger, address indexed recipient, uint256 indexed amount ); ////////////////////////////// /// Modifiers ////////////////////////////// /// @notice Checks whether message sender owns a given token id /// @param tokenId_ ID of token to check ownership again. modifier _onlyOwner(uint256 tokenId_) { address owner = ownerOf(tokenId_); require(msg.sender == owner, "Sender does not own this token"); _; } /// @notice Envokes tax collection. /// @dev Tax collection is triggered by an external envocation of a method wrapped by /// this modifier. /// @param tokenId_ ID of token to collect tax for. modifier _collectTax(uint256 tokenId_) { collectTax(tokenId_); _; } /// @notice Requires that token have been minted. /// @param tokenId_ ID of token to verify. modifier _tokenMinted(uint256 tokenId_) { ownerOf(tokenId_); _; } ////////////////////////////// /// Constructor ////////////////////////////// /// @notice Creates the token and sets beneficiary & taxation amount. /// @param name_ ERC721 Token Name /// @param symbol_ ERC721 Token Symbol /// @param beneficiary_ Recipient of tax payments /// @param taxNumerator_ The taxation rate up to 10 decimal places. /// @param taxationPeriod_ The number of days that constitute one taxation period. constructor( string memory name_, string memory symbol_, address payable beneficiary_, uint256 taxNumerator_, uint256 taxationPeriod_ ) ERC721(name_, symbol_) { beneficiary = beneficiary_; _taxNumerator = taxNumerator_; taxationPeriod = taxationPeriod_ * 1 days; } ////////////////////////////// /// Public Methods ////////////////////////////// /// @notice Collects tax. /// @param tokenId_ ID of token to collect tax for. /// @dev Strictly envoked by modifier but can be called publically. function collectTax(uint256 tokenId_) public { uint256 price = _price(tokenId_); if (price != 0) { // If price > 0, contract has not foreclosed. uint256 owed = _taxOwed(tokenId_); // If foreclosure should have occured in the past, last collection time will be // backdated to when the tax was last paid for. if (foreclosed(tokenId_)) { lastCollectionTimes[tokenId_] = _backdatedForeclosureTime(tokenId_); // Set remaining deposit to be collected. owed = _deposits[tokenId_]; } else { lastCollectionTimes[tokenId_] = block.timestamp; } // Normal collection _deposits[tokenId_] -= owed; taxationCollected[tokenId_] += owed; taxCollectedSinceLastTransfer[tokenId_] += owed; emit LogCollection(tokenId_, owed); /// Remit taxation to beneficiary. _remit(beneficiary, owed, RemittanceTriggers.TaxCollection); _forecloseIfNecessary(tokenId_); } } /// @notice Buy the token. /// @param tokenId_ ID of token the buyer wants to purchase. /// @param purchasePrice_ Purchasing price. Must be greater or equal to current price. /// @param currentPriceForVerification_ Current price must be given to protect against a front-run attack. /// The buyer will only complete the purchase at the agreed upon price. This prevents a malicious, /// second buyer from purchasing the token before the first trx is complete, changing the price, /// and eating into the first buyer's deposit. function buy( uint256 tokenId_, uint256 purchasePrice_, uint256 currentPriceForVerification_ ) public payable _tokenMinted(tokenId_) _collectTax(tokenId_) { // Prevent re-entrancy attack require(!locked[tokenId_], "Token is locked"); uint256 currentPrice = _price(tokenId_); // Prevent front-run. require( currentPrice == currentPriceForVerification_, "Current Price is incorrect" ); // Purchase price must be greater than zero, even if current price is zero, to ensure that // funds are available for deposit. require(purchasePrice_ > 0, "New Price cannot be zero"); // Buyer can offer more than the current price; this renders unnecessary a second gas payment // if Buyer wants to immediately self-assess the token at a higher valuation. require( purchasePrice_ >= currentPrice, "New Price must be >= current price" ); // Value sent must be greater than purchase price; surplus is necessary for deposit. require( msg.value > purchasePrice_, "Message does not contain surplus value for deposit" ); // Seller or this contract if foreclosed. address currentOwner = ownerOf(tokenId_); // Prevent an accidental re-purchase. require(msg.sender != currentOwner, "Buyer is already owner"); // After all security checks have occured, lock the token. locked[tokenId_] = true; // If token is owned by the contract, remit to the beneficiary. address recipient; if (currentOwner == address(this)) { recipient = beneficiary; } else { recipient = currentOwner; } // Remit the purchase price and any available deposit. uint256 remittance = purchasePrice_ + _deposits[tokenId_]; _remit(recipient, remittance, RemittanceTriggers.LeaseTakeover); // If the token is being purchased for the first time or is being purchased // from foreclosure,last collection time is set to now so that the contract // does not incorrectly consider the taxable period to have begun prior to // foreclosure and overtax the owner. if (currentPrice == 0) { lastCollectionTimes[tokenId_] = block.timestamp; } // Update deposit with surplus value. _deposits[tokenId_] = msg.value - purchasePrice_; transferToken(tokenId_, currentOwner, msg.sender, purchasePrice_); emit LogBuy(tokenId_, msg.sender, purchasePrice_); // Unlock token locked[tokenId_] = false; } ////////////////////////////// /// Owner-Only Methods ////////////////////////////// /// @notice Enables depositing of Wei for a given token. /// @param tokenId_ ID of token depositing Wei for. function depositWei(uint256 tokenId_) public payable _onlyOwner(tokenId_) _collectTax(tokenId_) { _deposits[tokenId_] += msg.value; } /// @notice Enables owner to change price in accordance with /// self-assessed value. /// @param tokenId_ ID of token to change price of. /// @param newPrice_ New price in Wei. function changePrice(uint256 tokenId_, uint256 newPrice_) public _onlyOwner(tokenId_) _collectTax(tokenId_) { uint256 price = prices[tokenId_]; require(newPrice_ > 0, "New price cannot be zero"); require(newPrice_ != price, "New price cannot be same"); prices[tokenId_] = newPrice_; emit LogPriceChange(tokenId_, newPrice_); } /// @notice Enables owner to withdraw some amount of their deposit. /// @param tokenId_ ID of token to withdraw against. /// @param wei_ Amount of Wei to withdraw. function withdrawDeposit(uint256 tokenId_, uint256 wei_) public _onlyOwner(tokenId_) _collectTax(tokenId_) { _withdrawDeposit(tokenId_, wei_); } /// @notice Enables owner to withdraw their entire deposit. /// @param tokenId_ ID of token to withdraw against. function exit(uint256 tokenId_) public _onlyOwner(tokenId_) _collectTax(tokenId_) { _withdrawDeposit(tokenId_, _deposits[tokenId_]); } ////////////////////////////// /// Remittance Methods ////////////////////////////// /// @notice Enables previous owners to withdraw remittances that failed to send. /// @dev To reduce complexity, pull funds are entirely separate from current deposit. function withdrawOutstandingRemittance() public { uint256 outstanding = outstandingRemittances[msg.sender]; require(outstanding > 0, "No outstanding remittance"); outstandingRemittances[msg.sender] = 0; _remit(msg.sender, outstanding, RemittanceTriggers.OutstandingRemittance); } ////////////////////////////// /// Public Getters ////////////////////////////// /// @notice Returns tax numerator /// @return Tax Rate function taxRate() public view returns (uint256) { return _taxNumerator; } /// @notice Returns an array of metadata about transfers for a given token. /// @param tokenId_ ID of the token requesting for. /// @return Array of TitleTransferEvents. function titleChainOf(uint256 tokenId_) public view _tokenMinted(tokenId_) returns (TitleTransferEvent[] memory) { return _chainOfTitle[tokenId_]; } /// @notice Gets current price for a given token ID. Requires that /// the token has been minted. /// @param tokenId_ ID of token requesting price for. /// @return Price in Wei. function priceOf(uint256 tokenId_) public view _tokenMinted(tokenId_) returns (uint256) { return _price(tokenId_); } /// @notice Gets current deposit for a given token ID. /// @param tokenId_ ID of token requesting deposit for. /// @return Deposit in Wei. function depositOf(uint256 tokenId_) public view _tokenMinted(tokenId_) returns (uint256) { return _deposits[tokenId_]; } /// @notice Determines the taxable amount accumulated between now and /// a given time in the past. /// @param tokenId_ ID of token requesting amount for. /// @param time_ Unix timestamp. /// @return taxDue Tax Due in Wei. function taxOwedSince(uint256 tokenId_, uint256 time_) public view _tokenMinted(tokenId_) returns (uint256 taxDue) { uint256 price = _price(tokenId_); return (((price * time_) / taxationPeriod) * _taxNumerator) / TAX_DENOMINATOR; } /// @notice Public method for the tax owed. Returns with the current time. /// for use calculating expected tax obligations. /// @param tokenId_ ID of token requesting amount for. /// @return amount Tax Due in Wei. /// @return timestamp Now as Unix timestamp. function taxOwed(uint256 tokenId_) public view returns (uint256 amount, uint256 timestamp) { return (_taxOwed(tokenId_), block.timestamp); } /// @notice Do the taxes owed exceed the deposit? If so, the token should be /// "foreclosed" by the contract. The price should be zero and anyone can /// purchase the token for the cost of the gas fee. /// @dev This is a useful helper function when price should be zero, but contract doesn't /// reflect it yet because `#_forecloseIfNecessary` has not yet been called.. /// @param tokenId_ ID of token requesting foreclosure status for. /// @return Returns boolean indicating whether or not the contract is foreclosed. function foreclosed(uint256 tokenId_) public view returns (bool) { uint256 owed = _taxOwed(tokenId_); if (owed >= _deposits[tokenId_]) { return true; } else { return false; } } /// @notice The amount of deposit that is withdrawable i.e. any deposited amount greater /// than the taxable amount owed. /// @param tokenId_ ID of token requesting withdrawable deposit for. /// @return amount in Wei. function withdrawableDeposit(uint256 tokenId_) public view returns (uint256) { if (foreclosed(tokenId_)) { return 0; } else { return _deposits[tokenId_] - _taxOwed(tokenId_); } } /// @notice Determines how long a token owner has until forclosure. /// @param tokenId_ ID of token requesting foreclosure time for. /// @return Unix timestamp function foreclosureTime(uint256 tokenId_) public view returns (uint256) { uint256 taxPerSecond = taxOwedSince(tokenId_, 1); uint256 withdrawable = withdrawableDeposit(tokenId_); if (withdrawable > 0) { // Time until deposited surplus no longer surpasses amount owed. return block.timestamp + withdrawable / taxPerSecond; } else if (taxPerSecond > 0) { // Token is active but in foreclosed state. // Returns when foreclosure should have occured i.e. when tax owed > deposits. return _backdatedForeclosureTime(tokenId_); } else { // Actively foreclosed (price is 0) return lastCollectionTimes[tokenId_]; } } ////////////////////////////// /// Internal Methods ////////////////////////////// /// @notice Send a remittance payment. /// @dev We're using a push rather than pull strategy as this removes the need for beneficiaries /// to check how much they are owed, more closely replicating a "streaming" payment. This comes /// at the cost of forcing all callers of `#_remit` to pay the additional gas for sending. /// @param recipient_ Address to send remittance to. /// @param remittance_ Remittance amount /// @param trigger_ What triggered this remittance? function _remit( address recipient_, uint256 remittance_, RemittanceTriggers trigger_ ) internal { address payable payableRecipient = payable(recipient_); // If the remittance fails, hold funds for the seller to retrieve. // For example, if `payableReceipient` is a contract that reverts on receipt or // if the call runs out of gas. if (payableRecipient.send(remittance_)) { emit LogRemittance(trigger_, recipient_, remittance_); } else { /* solhint-disable reentrancy */ outstandingRemittances[recipient_] += remittance_; emit LogOutstandingRemittance(recipient_); /* solhint-enable reentrancy */ } } /// @notice Withdraws deposit back to its owner. /// @dev Parent callers must enforce `ownerOnly(tokenId_)`. /// @param tokenId_ ID of token to withdraw deposit for. /// @param wei_ Amount of Wei to withdraw. function _withdrawDeposit(uint256 tokenId_, uint256 wei_) internal { // Note: Can withdraw whole deposit, which immediately triggers foreclosure. uint256 deposit = _deposits[tokenId_]; require(wei_ <= deposit, "Cannot withdraw more than deposited"); _deposits[tokenId_] -= wei_; _remit(msg.sender, wei_, RemittanceTriggers.WithdrawnDeposit); _forecloseIfNecessary(tokenId_); } /// @notice Forecloses if no deposit for a given token. /// @param tokenId_ ID of token to potentially foreclose. function _forecloseIfNecessary(uint256 tokenId_) internal { // If there are not enough funds to cover the entire amount owed, `__collectTax` // will take whatever's left of the deposit, resulting in a zero balance. if (_deposits[tokenId_] == 0) { // Become steward of asset (aka foreclose) address currentOwner = ownerOf(tokenId_); transferToken(tokenId_, currentOwner, address(this), 0); emit LogForeclosure(tokenId_, currentOwner); } } /// @notice Transfers possession of a token. /// @param tokenId_ ID of token to transfer possession of. /// @param currentOwner_ Address of current owner. /// @param newOwner_ Address of new owner. /// @param newPrice_ New price in Wei. function transferToken( uint256 tokenId_, address currentOwner_, address newOwner_, uint256 newPrice_ ) internal { // Call `_transfer` directly rather than `_transferFrom()` because `newOwner_` // does not require previous approval (as required by `_transferFrom()`) to purchase. _transfer(currentOwner_, newOwner_, tokenId_); prices[tokenId_] = newPrice_; TitleTransferEvent memory transferEvent = TitleTransferEvent( currentOwner_, newOwner_, block.timestamp, newPrice_ ); _chainOfTitle[tokenId_].push(transferEvent); lastTransferTimes[tokenId_] = block.timestamp; taxCollectedSinceLastTransfer[tokenId_] = 0; } ////////////////////////////// /// Prviate Getters ////////////////////////////// /// @notice Gets current price for a given token ID. /// @param tokenId_ ID of token requesting price for. /// @return Price in Wei. function _price(uint256 tokenId_) private view returns (uint256) { return prices[tokenId_]; } /// @notice How much is owed from the last collection until now? /// @param tokenId_ ID of token requesting amount for. /// @return Tax Due in wei function _taxOwed(uint256 tokenId_) private view returns (uint256) { uint256 timeElapsed = block.timestamp - lastCollectionTimes[tokenId_]; return taxOwedSince(tokenId_, timeElapsed); } /// @notice Returns the time when tax owed initially exceeded deposits. /// @dev last collected time + ((time_elapsed * deposit) / owed) /// @dev Returns within +/- 2s of previous values due to Solidity rounding /// down integer division without regard for significant digits, which produces /// variable results e.g. `599.9999999999851` becomes `599`. /// @param tokenId_ ID of token requesting /// @return Unix timestamp function _backdatedForeclosureTime(uint256 tokenId_) private view returns (uint256) { uint256 last = lastCollectionTimes[tokenId_]; uint256 timeElapsed = block.timestamp - last; return last + ((timeElapsed * _deposits[tokenId_]) / _taxOwed(tokenId_)); } ////////////////////////////// /// ERC721 Overrides ////////////////////////////// /** * Override ERC721 public transfer methods to ensure that purchasing and * foreclosure are the only way tokens can be transferred. */ /* solhint-disable no-unused-vars */ /* solhint-disable ordering */ /// @dev Override to make effectively-private. function transferFrom( address from, address to, uint256 tokenId ) public pure override { revert("Transfers may only occur via purchase/foreclosure"); } /// @dev Override to make effectively-private. function safeTransferFrom( address from, address to, uint256 tokenId ) public pure override { revert("Transfers may only occur via purchase/foreclosure"); } /// @dev Override to make effectively-private. function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public pure override { revert("Transfers may only occur via purchase/foreclosure"); } /* solhint-enable no-unused-vars */ /* solhint-enable ordering */ }
Public method for the tax owed. Returns with the current time. for use calculating expected tax obligations. tokenId_ ID of token requesting amount for. return amount Tax Due in Wei. return timestamp Now as Unix timestamp.
function taxOwed(uint256 tokenId_) public view returns (uint256 amount, uint256 timestamp) { return (_taxOwed(tokenId_), block.timestamp); }
2,543,320
./full_match/137/0x5F6d37E9ae4004a9B7426d4CF99fa44949Ee3653/sources/contracts/NewRoll.sol
Set threshold to trigger wealth tax.
function setWealthTaxThreshold(uint _wealthTaxThreshold) external onlyOwner { wealthTaxThreshold = _wealthTaxThreshold; }
4,678,892
./full_match/1/0x65DfDde1e416A1a59788b6358794180d95C9782D/sources/contracts/NymphFeet.sol
Requests randomness/
function getRandomNumber() public returns (bytes32 requestId) { uint256 nextId = totalSupply(); require(nextId >= MAX_FEET, "Supply not all minted"); require(randomnessState == 0, "Randomness already requested"); require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK"); randomnessState = 1; return requestRandomness(keyHash, fee); }
17,050,960
./full_match/1/0x5f419a278a06381A47972b1F1c8b6803C941CC99/sources/contracts/Dank.sol
scales the input amount add balance
function _mintUnderlying(address to, uint256 amount) internal { initSupply = initSupply.add(amount); uint256 scaledAmount = _dankToFragment(amount); _totalSupply = _totalSupply.add(scaledAmount); require( dankScalingFactor <= _maxScalingFactor(), "scaling factor lower than max" ); _dankBalances[to] = _dankBalances[to].add(amount); emit Mint(to, scaledAmount); emit Transfer(address(0), to, scaledAmount); }
3,846,361
./partial_match/3/0xD57D5276f246D650D2CeE9cE8002e42DF21CBF14/sources/LunaSwap.sol
swap eth to luna fund tokens contain eth-twa lp, weth, uni, link, renBTC
function swapEthToLuna(uint256 _slippage) public payable returns (uint256, uint256) { (, , uint256 poolAmountOut) = calcSwapEthToLunaInputs(msg.value, _slippage); return _swapWethToLunaByPoolOut(msg.value, poolAmountOut); }
5,319,748
// SPDX-License-Identifier: AGPL-3.0-only /* SkaleManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@openzeppelin/contracts/utils/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol"; import "@skalenetwork/skale-manager-interfaces/ISkaleManager.sol"; import "@skalenetwork/skale-manager-interfaces/IMintableToken.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IDistributor.sol"; import "@skalenetwork/skale-manager-interfaces/delegation/IValidatorService.sol"; import "@skalenetwork/skale-manager-interfaces/IBountyV2.sol"; import "@skalenetwork/skale-manager-interfaces/IConstantsHolder.sol"; import "@skalenetwork/skale-manager-interfaces/INodeRotation.sol"; import "@skalenetwork/skale-manager-interfaces/INodes.sol"; import "@skalenetwork/skale-manager-interfaces/ISchains.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "./Permissions.sol"; /** * @title SkaleManager * @dev Contract contains functions for node registration and exit, bounty * management, and monitoring verdicts. */ contract SkaleManager is IERC777Recipient, ISkaleManager, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); string public version; bytes32 public constant SCHAIN_REMOVAL_ROLE = keccak256("SCHAIN_REMOVAL_ROLE"); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { ISchains schains = ISchains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name, string calldata domainName ) external override { INodes nodes = INodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); INodes.NodeCreationParams memory params = INodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce, domainName: domainName }); nodes.createNode(msg.sender, params); } function nodeExit(uint nodeIndex) external override { uint gasTotal = gasleft(); IValidatorService validatorService = IValidatorService(contractManager.getContract("ValidatorService")); INodeRotation nodeRotation = INodeRotation(contractManager.getContract("NodeRotation")); INodes nodes = INodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted && validatorService.validatorAddressExists(msg.sender)) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving"); (bool completed, bool isSchains) = nodeRotation.exitFromSchain(nodeIndex); if (completed) { ISchainsInternal( contractManager.getContract("SchainsInternal") ).removeNodeFromAllExceptionSchains(nodeIndex); require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime( nodeIndex, block.timestamp + ( isSchains ? IConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() : 0 ) ); nodes.deleteNodeForValidator(validatorId, nodeIndex); } _refundGasByValidator(validatorId, payable(msg.sender), gasTotal - gasleft()); } function deleteSchain(string calldata name) external override { ISchains schains = ISchains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external override { require(hasRole(SCHAIN_REMOVAL_ROLE, msg.sender), "SCHAIN_REMOVAL_ROLE is required"); ISchains schains = ISchains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } function getBounty(uint nodeIndex) external override { uint gasTotal = gasleft(); INodes nodes = INodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require(!nodes.isNodeLeft(nodeIndex), "The node must not be in Left state"); require(!nodes.incompliant(nodeIndex), "The node is incompliant"); IBountyV2 bountyContract = IBountyV2(contractManager.getContract("Bounty")); uint bounty = bountyContract.calculateBounty(nodeIndex); nodes.changeNodeLastRewardDate(nodeIndex); uint validatorId = nodes.getValidatorId(nodeIndex); if (bounty > 0) { _payBounty(bounty, validatorId); } emit BountyReceived( nodeIndex, msg.sender, 0, 0, bounty, type(uint).max); _refundGasByValidator(validatorId, payable(msg.sender), gasTotal - gasleft()); } function setVersion(string calldata newVersion) external override onlyOwner { emit VersionUpdated(version, newVersion); version = newVersion; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); IDistributor distributor = IDistributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _refundGasByValidator(uint validatorId, address payable spender, uint spentGas) private { uint gasCostOfRefundGasByValidator = 55723; IWallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidator(validatorId, spender, spentGas + gasCostOfRefundGasByValidator); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Registry.sol) pragma solidity ^0.8.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer( address account, bytes32 _interfaceHash, address implementer ) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send( address recipient, uint256 amount, bytes calldata data ) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: AGPL-3.0-only /* ISkaleManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISkaleManager { /** * @dev Emitted when the version was updated */ event VersionUpdated(string oldVersion, string newVersion); /** * @dev Emitted when bounty is received. */ event BountyReceived( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent ); function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name, string calldata domainName ) external; function nodeExit(uint nodeIndex) external; function deleteSchain(string calldata name) external; function deleteSchainByRoot(string calldata name) external; function getBounty(uint nodeIndex) external; function setVersion(string calldata newVersion) external; } // SPDX-License-Identifier: AGPL-3.0-only /* IMintableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IMintableToken { function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* IDistributor.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IDistributor { /** * @dev Emitted when bounty is withdrawn. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth); function withdrawBounty(uint validatorId, address to) external; function withdrawFee(address to) external; function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) external returns (uint earned, uint endMonth); function getEarnedFeeAmount() external view returns (uint earned, uint endMonth); function getEarnedFeeAmountOf(uint validatorId) external view returns (uint earned, uint endMonth); } // SPDX-License-Identifier: AGPL-3.0-only /* IValidatorService.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IValidatorService { struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); /** * @dev Emitted when whitelist disabled. */ event WhitelistDisabled(bool status); /** * @dev Emitted when validator requested new address. */ event RequestNewAddress(uint indexed validatorId, address previousAddress, address newAddress); /** * @dev Emitted when validator set new minimum delegation amount. */ event SetMinimumDelegationAmount(uint indexed validatorId, uint previousMDA, uint newMDA); /** * @dev Emitted when validator set new name. */ event SetValidatorName(uint indexed validatorId, string previousName, string newName); /** * @dev Emitted when validator set new description. */ event SetValidatorDescription(uint indexed validatorId, string previousDescription, string newDescription); /** * @dev Emitted when validator start or stop accepting new delegation requests. */ event AcceptingNewRequests(uint indexed validatorId, bool status); function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId); function enableValidator(uint validatorId) external; function disableValidator(uint validatorId) external; function disableWhitelist() external; function requestForNewAddress(address newValidatorAddress) external; function confirmNewAddress(uint validatorId) external; function linkNodeAddress(address nodeAddress, bytes calldata sig) external; function unlinkNodeAddress(address nodeAddress) external; function setValidatorMDA(uint minimumDelegationAmount) external; function setValidatorName(string calldata newName) external; function setValidatorDescription(string calldata newDescription) external; function startAcceptingNewRequests() external; function stopAcceptingNewRequests() external; function removeNodeAddress(uint validatorId, address nodeAddress) external; function getAndUpdateBondAmount(uint validatorId) external returns (uint); function getMyNodesAddresses() external view returns (address[] memory); function getTrustedValidators() external view returns (uint[] memory); function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool); function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId); function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view; function getNodeAddresses(uint validatorId) external view returns (address[] memory); function validatorExists(uint validatorId) external view returns (bool); function validatorAddressExists(address validatorAddress) external view returns (bool); function checkIfValidatorAddressExists(address validatorAddress) external view; function getValidator(uint validatorId) external view returns (Validator memory); function getValidatorId(address validatorAddress) external view returns (uint); function isAcceptingNewRequests(uint validatorId) external view returns (bool); function isAuthorizedValidator(uint validatorId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* IBountyV2.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Artem Payvin SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IBountyV2 { /** * @dev Emitted when bounty reduction is turned on or turned off. */ event BountyReduction(bool status); /** * @dev Emitted when a node creation window was changed. */ event NodeCreationWindowWasChanged( uint oldValue, uint newValue ); function calculateBounty(uint nodeIndex) external returns (uint); function enableBountyReduction() external; function disableBountyReduction() external; function setNodeCreationWindowSeconds(uint window) external; function handleDelegationAdd(uint amount, uint month) external; function handleDelegationRemoving(uint amount, uint month) external; function estimateBounty(uint nodeIndex) external view returns (uint); function getNextRewardTimestamp(uint nodeIndex) external view returns (uint); function getEffectiveDelegatedSum() external view returns (uint[] memory); } // SPDX-License-Identifier: AGPL-3.0-only /* IConstantsHolder.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Artem Payvin SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IConstantsHolder { /** * @dev Emitted when constants updated. */ event ConstantUpdated( bytes32 indexed constantHash, uint previousValue, uint newValue ); function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external; function setCheckTime(uint newCheckTime) external; function setLatency(uint32 newAllowableLatency) external; function setMSR(uint newMSR) external; function setLaunchTimestamp(uint timestamp) external; function setRotationDelay(uint newDelay) external; function setProofOfUseLockUpPeriod(uint periodDays) external; function setProofOfUseDelegationPercentage(uint percentage) external; function setLimitValidatorsPerDelegator(uint newLimit) external; function setSchainCreationTimeStamp(uint timestamp) external; function setMinimalSchainLifetime(uint lifetime) external; function setComplaintTimeLimit(uint timeLimit) external; function msr() external view returns (uint); function launchTimestamp() external view returns (uint); function rotationDelay() external view returns (uint); function limitValidatorsPerDelegator() external view returns (uint); function schainCreationTimeStamp() external view returns (uint); function minimalSchainLifetime() external view returns (uint); function complaintTimeLimit() external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* INodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface INodeRotation { /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many _rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainHash; uint finishedRotation; } function exitFromSchain(uint nodeIndex) external returns (bool, bool); function freezeSchains(uint nodeIndex) external; function removeRotation(bytes32 schainHash) external; function skipRotationDelay(bytes32 schainHash) external; function rotateNode( uint nodeIndex, bytes32 schainHash, bool shouldDelay, bool isBadNode ) external returns (uint newNode); function selectNodeToGroup(bytes32 schainHash) external returns (uint nodeIndex); function getRotation(bytes32 schainHash) external view returns (Rotation memory); function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory); function isRotationInProgress(bytes32 schainHash) external view returns (bool); function isNewNodeFound(bytes32 schainHash) external view returns (bool); function getPreviousNode(bytes32 schainHash, uint256 nodeIndex) external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only /* INodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; import "./utils/IRandom.sol"; interface INodes { // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod ); /** * @dev Emitted when a node set to in compliant or compliant. */ event IncompliantNode( uint indexed nodeIndex, bool status ); /** * @dev Emitted when a node set to in maintenance or from in maintenance. */ event MaintenanceNode( uint indexed nodeIndex, bool status ); /** * @dev Emitted when a node status changed. */ event IPChanged( uint indexed nodeIndex, bytes4 previousIP, bytes4 newIP ); function removeSpaceFromNode(uint nodeIndex, uint8 space) external returns (bool); function addSpaceToNode(uint nodeIndex, uint8 space) external; function changeNodeLastRewardDate(uint nodeIndex) external; function changeNodeFinishTime(uint nodeIndex, uint time) external; function createNode(address from, NodeCreationParams calldata params) external; function initExit(uint nodeIndex) external; function completeExit(uint nodeIndex) external returns (bool); function deleteNodeForValidator(uint validatorId, uint nodeIndex) external; function checkPossibilityCreatingNode(address nodeAddress) external; function checkPossibilityToMaintainNode(uint validatorId, uint nodeIndex) external returns (bool); function setNodeInMaintenance(uint nodeIndex) external; function removeNodeFromInMaintenance(uint nodeIndex) external; function setNodeIncompliant(uint nodeIndex) external; function setNodeCompliant(uint nodeIndex) external; function setDomainName(uint nodeIndex, string memory domainName) external; function makeNodeVisible(uint nodeIndex) external; function makeNodeInvisible(uint nodeIndex) external; function changeIP(uint nodeIndex, bytes4 newIP, bytes4 newPublicIP) external; function numberOfActiveNodes() external view returns (uint); function incompliant(uint nodeIndex) external view returns (bool); function getRandomNodeWithFreeSpace( uint8 freeSpace, IRandom.RandomGenerator memory randomGenerator ) external view returns (uint); function isTimeForReward(uint nodeIndex) external view returns (bool); function getNodeIP(uint nodeIndex) external view returns (bytes4); function getNodeDomainName(uint nodeIndex) external view returns (string memory); function getNodePort(uint nodeIndex) external view returns (uint16); function getNodePublicKey(uint nodeIndex) external view returns (bytes32[2] memory); function getNodeAddress(uint nodeIndex) external view returns (address); function getNodeFinishTime(uint nodeIndex) external view returns (uint); function isNodeLeft(uint nodeIndex) external view returns (bool); function isNodeInMaintenance(uint nodeIndex) external view returns (bool); function getNodeLastRewardDate(uint nodeIndex) external view returns (uint); function getNodeNextRewardDate(uint nodeIndex) external view returns (uint); function getNumberOfNodes() external view returns (uint); function getNumberOnlineNodes() external view returns (uint); function getActiveNodeIds() external view returns (uint[] memory activeNodeIds); function getNodeStatus(uint nodeIndex) external view returns (NodeStatus); function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory); function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count); function getValidatorId(uint nodeIndex) external view returns (uint); function isNodeExist(address from, uint nodeIndex) external view returns (bool); function isNodeActive(uint nodeIndex) external view returns (bool); function isNodeLeaving(uint nodeIndex) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* ISchains.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchains { struct SchainOption { string name; bytes value; } /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainHash ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainHash ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainHash, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainHash, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainHash, uint[] nodesInGroup ); function addSchain(address from, uint deposit, bytes calldata data) external; function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name, address schainOwner, address schainOriginator, SchainOption[] calldata options ) external payable; function deleteSchain(address from, string calldata name) external; function deleteSchainByRoot(string calldata name) external; function restartSchainCreation(string calldata name) external; function verifySchainSignature( uint256 signA, uint256 signB, bytes32 hash, uint256 counter, uint256 hashA, uint256 hashB, string calldata schainName ) external view returns (bool); function getSchainPrice(uint typeOfSchain, uint lifetime) external view returns (uint); function getOption(bytes32 schainHash, string calldata optionName) external view returns (bytes memory); function getOptions(bytes32 schainHash) external view returns (SchainOption[] memory); } // SPDX-License-Identifier: AGPL-3.0-only /* ISchainsInternal - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchainsInternal { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; uint generation; address originator; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } /** * @dev Emitted when schain type added. */ event SchainTypeAdded(uint indexed schainType, uint partOfNode, uint numberOfNodes); /** * @dev Emitted when schain type removed. */ event SchainTypeRemoved(uint indexed schainType); function initializeSchain( string calldata name, address from, address originator, uint lifetime, uint deposit) external; function createGroupForSchain( bytes32 schainHash, uint numberOfNodes, uint8 partOfNode ) external returns (uint[] memory); function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external; function removeSchain(bytes32 schainHash, address from) external; function removeNodeFromSchain(uint nodeIndex, bytes32 schainHash) external; function deleteGroup(bytes32 schainHash) external; function setException(bytes32 schainHash, uint nodeIndex) external; function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external; function removeHolesForSchain(bytes32 schainHash) external; function addSchainType(uint8 partOfNode, uint numberOfNodes) external; function removeSchainType(uint typeOfSchain) external; function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external; function removeNodeFromAllExceptionSchains(uint nodeIndex) external; function removeAllNodesFromSchainExceptions(bytes32 schainHash) external; function makeSchainNodesInvisible(bytes32 schainHash) external; function makeSchainNodesVisible(bytes32 schainHash) external; function newGeneration() external; function addSchainForNode(uint nodeIndex, bytes32 schainHash) external; function removeSchainForNode(uint nodeIndex, uint schainIndex) external; function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external; function isSchainActive(bytes32 schainHash) external view returns (bool); function schainsAtSystem(uint index) external view returns (bytes32); function numberOfSchains() external view returns (uint64); function getSchains() external view returns (bytes32[] memory); function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8); function getSchainListSize(address from) external view returns (uint); function getSchainHashesByAddress(address from) external view returns (bytes32[] memory); function getSchainIdsByAddress(address from) external view returns (bytes32[] memory); function getSchainHashesForNode(uint nodeIndex) external view returns (bytes32[] memory); function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory); function getSchainOwner(bytes32 schainHash) external view returns (address); function getSchainOriginator(bytes32 schainHash) external view returns (address); function isSchainNameAvailable(string calldata name) external view returns (bool); function isTimeExpired(bytes32 schainHash) external view returns (bool); function isOwnerAddress(address from, bytes32 schainId) external view returns (bool); function getSchainName(bytes32 schainHash) external view returns (string memory); function getActiveSchain(uint nodeIndex) external view returns (bytes32); function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains); function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint); function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory); function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool); function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint); function isAnyFreeNode(bytes32 schainHash) external view returns (bool); function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool); function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool); function checkSchainOnNode(uint nodeIndex, bytes32 schainHash) external view returns (bool); function getSchainType(uint typeOfSchain) external view returns(uint8, uint); function getGeneration(bytes32 schainHash) external view returns (uint); function isSchainExist(bytes32 schainHash) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* IWallets - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IWallets { /** * @dev Emitted when the validator wallet was funded */ event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId); /** * @dev Emitted when the schain wallet was funded */ event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash); /** * @dev Emitted when the node received a refund from validator to its wallet */ event NodeRefundedByValidator(address node, uint validatorId, uint amount); /** * @dev Emitted when the node received a refund from schain to its wallet */ event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount); /** * @dev Emitted when the validator withdrawn funds from validator wallet */ event WithdrawFromValidatorWallet(uint indexed validatorId, uint amount); /** * @dev Emitted when the schain owner withdrawn funds from schain wallet */ event WithdrawFromSchainWallet(bytes32 indexed schainHash, uint amount); receive() external payable; function refundGasByValidator(uint validatorId, address payable spender, uint spentGas) external; function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external; function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external; function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external; function withdrawFundsFromValidatorWallet(uint amount) external; function rechargeValidatorWallet(uint validatorId) external payable; function rechargeSchainWallet(bytes32 schainId) external payable; function getSchainBalance(bytes32 schainHash) external view returns (uint); function getValidatorBalance(uint validatorId) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.11; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "@skalenetwork/skale-manager-interfaces/IPermissions.sol"; import "./thirdparty/openzeppelin/AccessControlUpgradeableLegacy.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeableLegacy, IPermissions { using AddressUpgradeable for address; IContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual override initializer { AccessControlUpgradeableLegacy.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeableLegacy skaleManager = AccessControlUpgradeableLegacy(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = IContractManager(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* IRandom.sol - SKALE Manager Interfaces Copyright (C) 2022-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IRandom { struct RandomGenerator { uint seed; } } // SPDX-License-Identifier: AGPL-3.0-only /* IContractManager.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IContractManager { /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external; function setContractsAddress(string calldata contractsName, address newContractsAddress) external; function contracts(bytes32 nameHash) external view returns (address); function getDelegationPeriodManager() external view returns (address); function getBounty() external view returns (address); function getValidatorService() external view returns (address); function getTimeHelpers() external view returns (address); function getConstantsHolder() external view returns (address); function getSkaleToken() external view returns (address); function getTokenState() external view returns (address); function getPunisher() external view returns (address); function getContract(string calldata name) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* IPermissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IPermissions { function initialize(address contractManagerAddress) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/thirdparty/openzeppelin/IAccessControlUpgradeableLegacy.sol"; import "./InitializableWithGap.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeableLegacy is InitializableWithGap, ContextUpgradeable, IAccessControlUpgradeableLegacy { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override 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 override 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 override 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 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 { 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 override { 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 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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* IAccessControlUpgradeableLegacy.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IAccessControlUpgradeableLegacy { /** * @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); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleAdmin(bytes32 role) external view returns (bytes32); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract InitializableWithGap is Initializable { uint256[50] private ______gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
Emitted when bounty reduction is turned on or turned off./ Emitted when a node creation window was changed./ SPDX-License-Identifier: AGPL-3.0-only/
interface IConstantsHolder { event ConstantUpdated( bytes32 indexed constantHash, uint previousValue, uint newValue ); function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external; function setCheckTime(uint newCheckTime) external; function setLatency(uint32 newAllowableLatency) external; function setMSR(uint newMSR) external; function setLaunchTimestamp(uint timestamp) external; function setRotationDelay(uint newDelay) external; function setProofOfUseLockUpPeriod(uint periodDays) external; function setProofOfUseDelegationPercentage(uint percentage) external; function setLimitValidatorsPerDelegator(uint newLimit) external; function setSchainCreationTimeStamp(uint timestamp) external; function setMinimalSchainLifetime(uint lifetime) external; function setComplaintTimeLimit(uint timeLimit) external; function msr() external view returns (uint); function launchTimestamp() external view returns (uint); function rotationDelay() external view returns (uint); function limitValidatorsPerDelegator() external view returns (uint); function schainCreationTimeStamp() external view returns (uint); function minimalSchainLifetime() external view returns (uint); function complaintTimeLimit() external view returns (uint); }
1,392,472