file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "../../Vault/Utils/Address.sol"; import "../../Vault/Utils/SafeBEP20.sol"; import "../../Vault/Utils/IBEP20.sol"; import "../../Vault/Utils/ReentrancyGuard.sol"; import "./XVSVaultStrategyProxy.sol"; import "./XVSVaultStrategyStorage.sol"; // This contract acts as a wrapper for user wallet interaction with the XVS Vault contract XVSVault is XVSVaultItemStorage, ReentrancyGuard { using SafeMath for uint256; using SafeBEP20 for IBEP20; using Address for address; modifier onlyAdminVault() { require(msg.sender == adminVault, "only admin vault can"); _; } modifier onlyAdmin() { require(msg.sender == admin, "only admin can"); _; } function deposit(uint256 amount) external nonReentrant onlyAdminVault { IBEP20(xvs).approve(xvsVault, 2**256 - 1); IXVSVault(xvsVault).deposit(xvs, pid, amount); } function requestWithdrawal(uint256 amount) external nonReentrant onlyAdminVault { IXVSVault(xvsVault).requestWithdrawal(xvs, pid, amount); } function claimRewards(address _userAddress) external nonReentrant onlyAdminVault { IXVSVault(xvsVault).deposit(xvs, pid, 0); // Transfer claimed XVS to the user wallet IBEP20(xvs).safeTransferFrom(address(this), _userAddress, IBEP20(xvs).balanceOf(address(this))); } function compoundRewards() external nonReentrant onlyAdminVault { // claim the pending rewards IXVSVault(xvsVault).deposit(xvs, pid, 0); // deposit the claimed rewards back to the XVS Vault IXVSVault(xvsVault).deposit(xvs, pid, IBEP20(xvs).balanceOf(address(this))); } function executeWithdrawal(address _userAddress) external nonReentrant onlyAdminVault { IXVSVault(xvsVault).executeWithdrawal(xvs, pid); // Transfer XVS to user wallet IBEP20(xvs).safeTransferFrom(address(this), _userAddress, IBEP20(xvs).balanceOf(address(this))); } /*** Admin Functions ***/ function _become(XVSVaultStrategyProxy xvsVaultStrategyProxy) public { require(msg.sender == xvsVaultStrategyProxy.admin(), "only proxy admin can change brains"); xvsVaultStrategyProxy._acceptImplementation(); } // Only allow to set the admin vault once. function setAdminVault(address _adminVault) external nonReentrant { require(_adminVault != address(0), "Zero address"); require(_adminVault.isContract(), "call to non-XVSVaultStrategy contract"); require(adminVault == address(0), "Admin vault is already set"); adminVault = _adminVault; } function emergencyWithdraw() external nonReentrant onlyAdmin { uint256 eligibleWithdrawalAmount = IXVSVault(xvsVault).getEligibleWithdrawalAmount(xvs, pid, address(this)); if (eligibleWithdrawalAmount > 0) { // Transfer the staked XVS from user vault contract to the user wallet IXVSVault(xvsVault).executeWithdrawal(xvs, pid); } // calculate the current available amount which is not yet requested to be withdrawn (uint256 amount, , uint256 pendingWithdrawals) = IXVSVault(xvsVault).getUserInfo(xvs, pid, address(this)); uint256 stakeAmount = amount.sub(pendingWithdrawals); if (stakeAmount > 0) { IXVSVault(xvsVault).requestWithdrawal(xvs, pid, stakeAmount); } // Transfer XVS to admin wallet IBEP20(xvs).safeTransferFrom(address(this), admin, IBEP20(xvs).balanceOf(address(this))); } }
Transfer claimed XVS to the user wallet
function claimRewards(address _userAddress) external nonReentrant onlyAdminVault { IXVSVault(xvsVault).deposit(xvs, pid, 0); IBEP20(xvs).safeTransferFrom(address(this), _userAddress, IBEP20(xvs).balanceOf(address(this))); }
2,492,533
// SPDX-License-Identifier: MIT pragma solidity >= 0.8.4; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; contract SparkLink is Ownable, ERC165, IERC721, IERC721Metadata{ using Address for address; using Counters for Counters.Counter; using SafeERC20 for IERC20; Counters.Counter private _issueIds; /* Abstract struct Issue { uint32 total_amount; bool is_free bool is_ND; bool is_NC; uint16 shill_times; uint8 royalty_fee; } This structure records some common attributes of a series of NFTs: - `royalty_fee`: the proportion of royaltyes - `shill_times`: the number of times a single NFT can been shared - `total_amount`: the total number of NFTs in the series To reduce gas cost, this structure is actually stored in the `father_id` attibute of root NFT - 0~31 `total_amount` - 37 `is_free` - 38 `is_NC` - 39 `is_ND` - 40~55 `shill_times` - 56~63 `royalty_fee` */ struct Edition { // This structure stores NFT related information: // - `father_id`: For root NFT it stores issue abstract sturcture // For other NFTs its stores the NFT Id of which NFT it `acceptShill` from // - `shill_price`: The price should be paid when others `accpetShill` from this NFT // - remaining_shill_times: The initial value is the shilltimes of the issue it belongs to // When others `acceptShill` from this NFT, it will subtract one until its value is 0 // - `owner`: record the owner of this NFT // - `ipfs_hash`: IPFS hash value of the URI where this NTF's metadata stores // - `transfer_price`: The initial value is zero // Set by `determinePrice` or `determinePriceAndApprove` before `transferFrom` // It will be checked wether equal to msg.value when `transferFrom` is called // After `transferFrom` this value will be set to zero // - `profit`: record the profit owner can claim (include royalty fee it should conduct to its father NFT) uint64 father_id; uint128 shill_price; uint16 remaining_shill_times; address owner; bytes32 ipfs_hash; uint128 transfer_price; uint128 profit; } // Emit when `determinePrice` success event DeterminePrice( uint64 indexed NFT_id, uint128 transfer_price ); // Emit when `determinePriceAndApprove` success event DeterminePriceAndApprove( uint64 indexed NFT_id, uint128 transfer_price, address indexed to ); // Emit when `publish` success // - `rootNFTId`: Record the Id of root NFT given to publisher event Publish( address indexed publisher, uint64 indexed rootNFTId, address token_addr ); // Emit when claimProfit success //- `amount`: Record the actual amount owner of this NFT received (profit - profit*royalty_fee/100) event Claim( uint64 indexed NFT_id, address indexed receiver, uint128 amount ); // Emit when setURI success event SetURI( uint64 indexed NFT_id, bytes32 old_URI, bytes32 new_URI ); event Label( uint64 indexed NFT_id, string content ); event SetDAOFee( uint8 old_DAO_fee, uint8 new_DAO_fee ); event SetLoosRatio( uint8 old_loss_ratio, uint8 new_loss_ratio ); event SetDAORouter01( address old_router_address, address new_router_address ); event SetDAORouter02( address old_router_address, address new_router_address ); //---------------------------------------------------------------------------------------------------- /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(address DAO_router_address01,address DAO_router_address02, address uniswapRouterAddress, address factoryAddress) { uniswapV2Router = IUniswapV2Router02(uniswapRouterAddress); uniswapV2Factory = IUniswapV2Factory(factoryAddress); DAO_router01 = DAO_router_address01; DAO_router02 = DAO_router_address02; _name = "SparkLink"; _symbol = "SPL"; } /** * @dev Create a issue and mint a root NFT for buyer acceptShill from * * Requirements: * * - `_first_sell_price`: The price should be paid when others `accpetShill` from this NFT * - `_royalty_fee`: The proportion of royaltyes, it represents the ratio of the father NFT's profit from the child NFT * Its value should <= 100 * - `_shill_times`: the number of times a single NFT can been shared * Its value should <= 65536 * - `_ipfs_hash`: IPFS hash value of the URI where this NTF's metadata stores * * - `token_address`: list of tokens(address) can be accepted for payment. * `A token address` can be ERC-20 token contract address or `address(0)`(ETH). * * - `_is_free`: * - `_is_NC`: * * - `_is_ND`: * Emits a {Publish} event. * - Emitted {Publish} event contains root NFT id. */ function publish( uint128 _first_sell_price, uint8 _royalty_fee, uint16 _shill_times, bytes32 _ipfs_hash, address _token_addr, bool _is_free, bool _is_NC, bool _is_ND ) external { require(_royalty_fee <= 100, "SparkLink: Royalty fee should be <= 100%."); _issueIds.increment(); require(_issueIds.current() <= type(uint32).max, "SparkLink: Value doesn't fit in 32 bits."); if (_token_addr != address(0)) require(IERC20(_token_addr).totalSupply() > 0, "Not a valid ERC20 token address"); uint32 new_issue_id = uint32(_issueIds.current()); uint64 rootNFTId = getNftIdByEditionIdAndIssueId(new_issue_id, 1); require( _checkOnERC721Received(address(0), msg.sender, rootNFTId, ""), "SparkLink: Transfer to non ERC721Receiver implementer" ); Edition storage new_NFT = editions_by_id[rootNFTId]; uint64 information; information = reWriteUint8InUint64(56, _royalty_fee, information); information = reWriteUint16InUint64(40, _shill_times, information); information = reWriteBoolInUint64(37, _is_free, information); information = reWriteBoolInUint64(38, _is_NC, information); information = reWriteBoolInUint64(39, _is_ND, information); information += 1; token_addresses[new_issue_id] = _token_addr; new_NFT.father_id = information; new_NFT.remaining_shill_times = _shill_times; new_NFT.shill_price = _first_sell_price; new_NFT.owner = msg.sender; new_NFT.ipfs_hash = _ipfs_hash; _balances[msg.sender] += 1; emit Transfer(address(0), msg.sender, rootNFTId); emit Publish( msg.sender, rootNFTId, _token_addr ); } /** * @dev Buy a child NFT from the _NFT_id buyer input * * Requirements: * * - `_NFT_id`: _NFT_id the father NFT id buyer mint NFT from * remain shill times of the NFT_id you input should greater than 0 * Emits a {Ttansfer} event. * - Emitted {Transfer} event from 0x0 address to msg.sender, contain new NFT id. * - New NFT id will be generater by edition id and issue id * 0~31 edition id * 32~63 issue id */ function acceptShill( uint64 _NFT_id ) external payable { require(isEditionExisting(_NFT_id), "SparkLink: This NFT does not exist"); require(editions_by_id[_NFT_id].remaining_shill_times > 0, "SparkLink: There is no remaining shill time for this NFT"); if (!isRootNFT(_NFT_id)||!getIsFreeByNFTId(_NFT_id)){ address token_addr = getTokenAddrByNFTId(_NFT_id); if (token_addr == address(0)){ require(msg.value == editions_by_id[_NFT_id].shill_price, "SparkLink: Wrong price"); _addProfit( _NFT_id, editions_by_id[_NFT_id].shill_price); } else { uint256 before_balance = IERC20(token_addr).balanceOf(address(this)); IERC20(token_addr).safeTransferFrom(msg.sender, address(this), editions_by_id[_NFT_id].shill_price); _addProfit( _NFT_id, uint256toUint128(IERC20(token_addr).balanceOf(address(this))-before_balance)); } } editions_by_id[_NFT_id].remaining_shill_times -= 1; _mintNFT(_NFT_id, msg.sender); if (editions_by_id[_NFT_id].remaining_shill_times == 0) _mintNFT(_NFT_id, ownerOf(_NFT_id)); } /** * @dev Transfers `tokenId` token from `from` to `to`. * * 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}. * - If `transfer_price` has been set, caller should give same value in msg.sender. * - Will call `claimProfit` before transfer and `transfer_price` will be set to zero after transfer. * Emits a {TransferAsset} events */ function transferFrom(address from, address to, uint256 tokenId) external payable override { _transfer(from, to, uint256toUint64(tokenId)); } function safeTransferFrom(address from, address to, uint256 tokenId) external payable override{ _safeTransfer(from, to, uint256toUint64(tokenId), ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata _data) external payable override { _safeTransfer(from, to, uint256toUint64(tokenId), _data); } /** * @dev Claim profit from reward pool of NFT. * * Requirements: * * - `_NFT_id`: The NFT id of NFT caller claim, the profit will give to its owner. * - If its profit is zero the event {Claim} will not be emited. * Emits a {Claim} events */ function claimProfit(uint64 _NFT_id) public { require(isEditionExisting(_NFT_id), "SparkLink: This edition does not exist"); if (editions_by_id[_NFT_id].profit != 0) { uint128 amount = editions_by_id[_NFT_id].profit; address token_addr = getTokenAddrByNFTId(_NFT_id); if (DAO_fee != 0) { uint128 DAO_amount = calculateFee(amount, DAO_fee); amount -= DAO_amount; if (token_addr == address(0)) { payable(DAO_router01).transfer(DAO_amount); } else if (uniswapV2Factory.getPair(token_addr, uniswapV2Router.WETH()) == address(0)) { IERC20(token_addr).safeTransfer(DAO_router02,DAO_amount); } else { _swapTokensForEth(token_addr, DAO_amount); } } editions_by_id[_NFT_id].profit = 0; if (!isRootNFT(_NFT_id)) { uint128 _royalty_fee = calculateFee(amount, getRoyaltyFeeByNFTId(_NFT_id)); _addProfit(getFatherByNFTId(_NFT_id), _royalty_fee); amount -= _royalty_fee; } if (token_addr == address(0)){ payable(ownerOf(_NFT_id)).transfer(amount); } else { IERC20(token_addr).safeTransfer(ownerOf(_NFT_id), amount); } emit Claim( _NFT_id, ownerOf(_NFT_id), amount ); } } /** * @dev Set token URI. * * Requirements: * * - `_NFT_id`: transferred token id. * - `ipfs_hash`: ipfs hash value of the URI will be set. * Emits a {SetURI} events */ function setURI(uint64 _NFT_id, bytes32 ipfs_hash) public { if (getIsNDByNFTId(_NFT_id)) { require(_NFT_id == getRootNFTIdByNFTId(_NFT_id), "SparkLink: NFT follows the ND protocol, only the root NFT's URI can be set."); } require(ownerOf(_NFT_id) == msg.sender, "SparkLink: Only owner can set the token URI"); _setTokenURI(_NFT_id, ipfs_hash); } /** * @dev update token URI. * * Requirements: * * - `_NFT_id`: transferred token id. */ function updateURI(uint64 _NFT_id) public{ require(ownerOf(_NFT_id) == msg.sender, "SparkLink: Only owner can update the token URI"); editions_by_id[_NFT_id].ipfs_hash = editions_by_id[getRootNFTIdByNFTId(_NFT_id)].ipfs_hash; } function label(uint64 _NFT_id, string memory content) public { require(ownerOf(_NFT_id) == msg.sender, "SparkLink: Only owner can label this NFT"); emit Label(_NFT_id, content); } /** * @dev Determine NFT price before transfer. * * Requirements: * * - `_NFT_id`: transferred token id. * - `_price`: The amount of ETH should be payed for `_NFT_id` * Emits a {DeterminePrice} events */ function determinePrice( uint64 _NFT_id, uint128 _price ) public { require(isEditionExisting(_NFT_id), "SparkLink: This NFT does not exist"); require(msg.sender == ownerOf(_NFT_id), "SparkLink: Only owner can set the price"); editions_by_id[_NFT_id].transfer_price = _price; emit DeterminePrice(_NFT_id, _price); } /** * @dev Determine NFT price before transfer. * * Requirements: * * - `_NFT_id`: transferred token id. * - `_price`: The amount of ETH should be payed for `_NFT_id` * - `_to`: The account address `approve` to. * Emits a {DeterminePriceAndApprove} events */ function determinePriceAndApprove( uint64 _NFT_id, uint128 _price, address _to ) public { determinePrice(_NFT_id, _price); approve(_to, _NFT_id); emit DeterminePriceAndApprove(_NFT_id, _price, _to); } function setDAOFee(uint8 _DAO_fee) public onlyOwner { require(_DAO_fee <= MAX_DAO_FEE, "SparkLink: DAO fee can not exceed 5%"); emit SetDAOFee(DAO_fee, _DAO_fee); DAO_fee = _DAO_fee; } function setDAORouter01(address _DAO_router01) public onlyOwner { emit SetDAORouter01(DAO_router01, _DAO_router01); DAO_router01 = _DAO_router01; } function setDAORouter02(address _DAO_router02) public onlyOwner { emit SetDAORouter01(DAO_router02, _DAO_router02); DAO_router02 = _DAO_router02; } function setUniswapV2Router(address _uniswapV2Router) public onlyOwner { uniswapV2Router = IUniswapV2Router02(_uniswapV2Router); } function setUniswapV2Factory(address _uniswapV2Factory) public onlyOwner { uniswapV2Factory = IUniswapV2Factory(_uniswapV2Factory); } function setLoosRatio(uint8 _loss_ratio) public onlyOwner { require(_loss_ratio <= MAX_LOSS_RATIO, "SparkLink: Loss ratio can not below 50%"); emit SetLoosRatio(loss_ratio, _loss_ratio); loss_ratio = _loss_ratio; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "SparkLink: Approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "SparkLink: Approve caller is not owner nor approved for all" ); _approve(to, uint256toUint64(tokenId)); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "SparkLink: Approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @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), "SparkLink: 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 = editions_by_id[uint256toUint64(tokenId)].owner; require(owner != address(0), "SparkLink: 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 Query NFT information set. * * Requirements: * - `_NFT_id`: The id of the edition queryed. * Return : * - `issue_information`: For root NFT it stores issue abstract sturcture * - 0~31 `total_amount` * - 37 `is_free` * - 38 `is_NC` * - 39 `is_ND` * - 40~55 `shill_times` * - 56~63 `royalty_fee` * - `father_id`: For root NFT it stores issue abstract sturcture * For other NFTs its stores the NFT Id of which NFT it `acceptShill` from * - `shill_price`: The price should be paid when others `accpetShill` from this NFT * - `remaining_shill_times`: The initial value is the shilltimes of the issue it belongs to * When others `acceptShill` from this NFT, it will subtract one until its value is 0 * - `owner`: record the owner of this NFT * - `transfer_price`: The initial value is zero * Set by `determinePrice` or `determinePriceAndApprove` before `transferFrom` * It will be checked wether equal to msg.value when `transferFrom` is called * After `transferFrom` this value will be set to zero * - `profit`: record the profit owner can claim (include royalty fee it should conduct to its father NFT) * - `metadata`: IPFS hash value of the URI where this NTF's metadata stores */ function getNFTInfoByNFTID(uint64 _NFT_id) public view returns ( uint64 issue_information, uint64 father_id, uint128 shill_price, uint16 remain_shill_times, uint128 profit, string memory metadata ) { require(isEditionExisting(_NFT_id), "SparkLink: Approved query for nonexistent token"); return( editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id, getFatherByNFTId(_NFT_id), editions_by_id[_NFT_id].shill_price, getRemainShillTimesByNFTId(_NFT_id), getProfitByNFTId(_NFT_id), tokenURI(_NFT_id) ); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(isEditionExisting(uint256toUint64(tokenId)), "SparkLink: Approved query for nonexistent token"); return _tokenApprovals[uint256toUint64(tokenId)]; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(isEditionExisting(uint256toUint64(tokenId)), "SparkLink: URI query for nonexistent token"); bytes32 _ipfs_hash = editions_by_id[uint256toUint64(tokenId)].ipfs_hash; string memory encoded_hash = _toBase58String(_ipfs_hash); string memory base = _baseURI(); return string(abi.encodePacked(base, encoded_hash)); } /** * @dev Query is issue free for first lever buyer. * * Requirements: * - `_NFT_id`: The id of the edition queryed. * Return a bool value. */ function getIsFreeByNFTId(uint64 _NFT_id) public view returns (bool) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); return getBoolFromUint64(37, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id); } /** * @dev Query is issue follows the NC protocol by any NFT belongs to this issue. * * Requirements: * - `_NFT_id`: The id of the edition queryed. * Return a bool value. */ function getIsNCByNFTId(uint64 _NFT_id) public view returns (bool) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); return getBoolFromUint64(38, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id); } /** * @dev Query is issue follows the ND protocol by any NFT belongs to this issue. * * Requirements: * - `_NFT_id`: The id of the edition queryed. * Return a bool value. */ function getIsNDByNFTId(uint64 _NFT_id) public view returns (bool) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); return getBoolFromUint64(39, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id); } /** * @dev Query is edition exist. * * Requirements: * - `_NFT_id`: The id of the edition queryed. * Return a bool value. */ function isEditionExisting(uint64 _NFT_id) public view returns (bool) { return (editions_by_id[_NFT_id].owner != address(0)); } /** * @dev Query the amount of ETH a NFT can be claimed. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * Return the value this NFT can be claimed. * If the NFT is not root NFT, this value will subtract royalty fee percent. */ function getProfitByNFTId(uint64 _NFT_id) public view returns (uint128){ require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); uint128 amount = editions_by_id[_NFT_id].profit; if (DAO_fee != 0) { uint128 DAO_amount = calculateFee(amount, DAO_fee); amount -= DAO_amount; } if (!isRootNFT(_NFT_id)) { uint128 _total_fee = calculateFee(amount, getRoyaltyFeeByNFTId(_NFT_id)); amount -= _total_fee; } return amount; } /** * @dev Query royalty fee percent of an issue by any NFT belongs to this issue. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * Return royalty fee percent of this issue. */ function getRoyaltyFeeByNFTId(uint64 _NFT_id) public view returns (uint8) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); return getUint8FromUint64(56, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id); } /** * @dev Query max shill times of an issue by any NFT belongs to this issue. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * Return max shill times of this issue. */ function getShillTimesByNFTId(uint64 _NFT_id) public view returns (uint16) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); return getUint16FromUint64(40, editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id); } /** * @dev Query total NFT number of a issue by any NFT belongs to this issue. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * Return total NFT number of this issue. */ function getTotalAmountByNFTId(uint64 _NFT_id) public view returns (uint32) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); return getBottomUint32FromUint64(editions_by_id[getRootNFTIdByNFTId(_NFT_id)].father_id); } /** * @dev Query supported token address of a issue by any NFT belongs to this issue. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * Return supported token address of this NFT. * Address 0 represent ETH. */ function getTokenAddrByNFTId(uint64 _NFT_id) public view returns (address) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); return token_addresses[uint32(_NFT_id>>32)]; } /** * @dev Query the id of this NFT's father NFT. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * - This NFT should exist and not be root NFT. * Return the father NFT id of this NFT. */ function getFatherByNFTId(uint64 _NFT_id) public view returns (uint64) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); if (isRootNFT(_NFT_id)) { return 0; } return editions_by_id[_NFT_id].father_id; } /** * @dev Query transfer_price of this NFT. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * Return transfer_price of this NFT. */ function getTransferPriceByNFTId(uint64 _NFT_id) public view returns (uint128) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); return editions_by_id[_NFT_id].transfer_price; } /** * @dev Query shill_price of this NFT. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * Return shill_price of this NFT. */ function getShillPriceByNFTId(uint64 _NFT_id) public view returns (uint128) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); if (getIsFreeByNFTId(_NFT_id)&&isRootNFT(_NFT_id)) return 0; else return editions_by_id[_NFT_id].shill_price; } /** * @dev Query remaining_shill_times of this NFT. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * Return remaining_shill_times of this NFT. */ function getRemainShillTimesByNFTId(uint64 _NFT_id) public view returns (uint16) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); return editions_by_id[_NFT_id].remaining_shill_times; } /** * @dev Query depth of this NFT. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * Return depth of this NFT. */ function getDepthByNFTId(uint64 _NFT_id) public view returns (uint64) { require(isEditionExisting(_NFT_id), "SparkLink: Edition is not exist."); uint64 depth = 0; for (depth = 0; !isRootNFT(_NFT_id); _NFT_id = getFatherByNFTId(_NFT_id)) { depth += 1; } return depth; } /** * @dev Query is this NFT is root NFT by check is its edition id is 1. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * Return a bool value to indicate wether this NFT is root NFT. */ function isRootNFT(uint64 _NFT_id) public pure returns (bool) { return getBottomUint32FromUint64(_NFT_id) == uint32(1); } /** * @dev Query root NFT id by NFT id. * * Requirements: * - `_NFT_id`: The id of the NFT queryed. * Return a bool value to indicate wether this NFT is root NFT. */ function getRootNFTIdByNFTId(uint64 _NFT_id) public pure returns (uint64) { return ((_NFT_id>>32)<<32 | uint64(1)); } /** * @dev Query loss ratio of this contract. * * Return loss ratio of this contract. */ function getLossRatio() public view returns (uint8) { return loss_ratio; } /** * @dev Calculate edition id by NFT id. * * Requirements: * - `_NFT_id`: The NFT id of the NFT caller want to get. * Return edition id. */ function getEditionIdByNFTId(uint64 _NFT_id) public pure returns (uint32) { return getBottomUint32FromUint64(_NFT_id); } // Token name string private _name; // Token symbol string private _symbol; uint8 public loss_ratio = 62; uint8 public DAO_fee = 2; uint8 public constant MAX_DAO_FEE = 2; uint8 public constant MAX_LOSS_RATIO = 50; address public DAO_router01; address public DAO_router02; IUniswapV2Router02 public uniswapV2Router; IUniswapV2Factory public uniswapV2Factory; // Mapping owner address to token count mapping(address => uint64) private _balances; // Mapping from token ID to approved address mapping(uint64 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; mapping (uint64 => Edition) private editions_by_id; // mapping from issue ID to support ERC20 token address mapping(uint32 => address) private token_addresses; bytes constant private sha256MultiHash = hex"1220"; bytes constant private ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; function _swapTokensForEth(address token_addr, uint128 token_amount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = token_addr; path[1] = uniswapV2Router.WETH(); IERC20(token_addr).approve(address(uniswapV2Router), token_amount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( token_amount, 0, // accept any amount of ETH path, DAO_router01, block.timestamp ); } /** * @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, uint64 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("SparkLink: Transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint64 tokenId, bytes32 ipfs_hash) internal virtual { bytes32 old_URI = editions_by_id[tokenId].ipfs_hash; editions_by_id[tokenId].ipfs_hash = ipfs_hash; emit SetURI(tokenId, old_URI, ipfs_hash); } /** * @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 _NFT_id NFT id of father NFT * @param _owner indicate the address new NFT transfer to * @return a uint64 store new NFT id **/ function _mintNFT( uint64 _NFT_id, address _owner ) internal returns (uint64) { _addTotalAmount(_NFT_id); uint32 new_edition_id = getTotalAmountByNFTId(_NFT_id); uint64 new_NFT_id = getNftIdByEditionIdAndIssueId(uint32(_NFT_id>>32), new_edition_id); require( _checkOnERC721Received(address(0), _owner, new_NFT_id, ""), "SparkLink: Transfer to non ERC721Receiver implementer" ); Edition storage new_NFT = editions_by_id[new_NFT_id]; new_NFT.remaining_shill_times = getShillTimesByNFTId(_NFT_id); new_NFT.father_id = _NFT_id; if (getIsFreeByNFTId(_NFT_id)&&isRootNFT(_NFT_id)) new_NFT.shill_price = editions_by_id[_NFT_id].shill_price; else new_NFT.shill_price = calculateFee(editions_by_id[_NFT_id].shill_price, loss_ratio); if (new_NFT.shill_price == 0) { new_NFT.shill_price = editions_by_id[_NFT_id].shill_price; } new_NFT.owner = _owner; new_NFT.ipfs_hash = editions_by_id[_NFT_id].ipfs_hash; _balances[_owner] += 1; emit Transfer(address(0), _owner, new_NFT_id); return new_NFT_id; } /** * @dev Internal function to clear approve and transfer_price * * @param _NFT_id NFT id of father NFT **/ function _afterTokenTransfer (uint64 _NFT_id) internal { // Clear approvals from the previous owner _approve(address(0), _NFT_id); editions_by_id[_NFT_id].transfer_price = 0; } /** * @dev Internal function to support transfer `tokenId` from `from` to `to`. * * @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 * Emits a {Transfer} event. */ function _transfer( address from, address to, uint64 tokenId ) internal virtual { require(ownerOf(tokenId) == from, "SparkLink: Transfer of token that is not own"); require(_isApprovedOrOwner(_msgSender(), tokenId), "SparkLink: Transfer caller is not owner nor approved"); require(to != address(0), "SparkLink: Transfer to the zero address"); if (msg.sender != ownerOf(tokenId)) { address token_addr = getTokenAddrByNFTId(tokenId); uint128 transfer_price = editions_by_id[tokenId].transfer_price; if (token_addr == address(0)){ require(msg.value == transfer_price, "SparkLink: Price not met"); _addProfit(tokenId, transfer_price); } else { uint256 before_balance = IERC20(token_addr).balanceOf(address(this)); IERC20(token_addr).safeTransferFrom(msg.sender, address(this), transfer_price); _addProfit(tokenId, uint256toUint128(IERC20(token_addr).balanceOf(address(this))-before_balance)); } claimProfit(tokenId); } else { claimProfit(tokenId); } _afterTokenTransfer(tokenId); _balances[from] -= 1; _balances[to] += 1; editions_by_id[tokenId].owner = to; emit Transfer(from, to, tokenId); } /** * @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, uint64 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "SparkLink: Transfer to non ERC721Receiver implementer"); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint64 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } function _addProfit(uint64 _NFT_id, uint128 _increase) internal { editions_by_id[_NFT_id].profit = editions_by_id[_NFT_id].profit+_increase; } function _addTotalAmount(uint64 _NFT_Id) internal { require(getTotalAmountByNFTId(_NFT_Id) < type(uint32).max, "SparkLink: There is no left in this issue."); editions_by_id[getRootNFTIdByNFTId(_NFT_Id)].father_id += 1; } function _isApprovedOrOwner(address spender, uint64 tokenId) internal view virtual returns (bool) { require(isEditionExisting(tokenId), "SparkLink: Operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _baseURI() internal pure returns (string memory) { return "https://ipfs.io/ipfs/"; } /** * @dev Calculate NFT id by issue id and edition id. * * Requirements: * - `_issue_id`: The issue id of the NFT caller want to get. * - `_edition_id`: The edition id of the NFT caller want to get. * Return NFT id. */ function getNftIdByEditionIdAndIssueId(uint32 _issue_id, uint32 _edition_id) internal pure returns (uint64) { return (uint64(_issue_id)<<32)|uint64(_edition_id); } function getBoolFromUint64(uint8 position, uint64 data64) internal pure returns (bool flag) { // (((1 << size) - 1) & base >> position) assembly { flag := and(1, shr(position, data64)) } } function getUint8FromUint64(uint8 position, uint64 data64) internal pure returns (uint8 data8) { // (((1 << size) - 1) & base >> position) assembly { data8 := and(sub(shl(8, 1), 1), shr(position, data64)) } } function getUint16FromUint64(uint8 position, uint64 data64) internal pure returns (uint16 data16) { // (((1 << size) - 1) & base >> position) assembly { data16 := and(sub(shl(16, 1), 1), shr(position, data64)) } } function getBottomUint32FromUint64(uint64 data64) internal pure returns (uint32 data32) { // (((1 << size) - 1) & base >> position) assembly { data32 := and(sub(shl(32, 1), 1), data64) } } function reWriteBoolInUint64(uint8 position, bool flag, uint64 data64) internal pure returns (uint64 boxed) { assembly { // mask = ~((1 << 8 - 1) << position) // _box = (mask & _box) | ()data << position) boxed := or( and(data64, not(shl(position, 1))), shl(position, flag)) } } function reWriteUint8InUint64(uint8 position, uint8 flag, uint64 data64) internal pure returns (uint64 boxed) { assembly { // mask = ~((1 << 8 - 1) << position) // _box = (mask & _box) | ()data << position) boxed := or(and(data64, not(shl(position, 1))), shl(position, flag)) } } function reWriteUint16InUint64(uint8 position, uint16 data16, uint64 data64) internal pure returns (uint64 boxed) { assembly { // mask = ~((1 << 16 - 1) << position) // _box = (mask & _box) | ()data << position) boxed := or( and(data64, not(shl(position, sub(shl(16, 1), 1)))), shl(position, data16)) } } function uint256toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SparkLink: Value doesn't fit in 64 bits"); return uint64(value); } function uint256toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SparkLink: Value doesn't fit in 128 bits"); return uint128(value); } function calculateFee(uint128 _amount, uint8 _fee_percent) internal pure returns (uint128) { return _amount*_fee_percent/10**2; } function _toBase58String(bytes32 con) internal pure returns (string memory) { bytes memory source = bytes.concat(sha256MultiHash,con); uint8[] memory digits = new uint8[](64); //TODO: figure out exactly how much is needed digits[0] = 0; uint8 digitlength = 1; for (uint256 i = 0; i<source.length; ++i) { uint carry = uint8(source[i]); for (uint256 j = 0; j<digitlength; ++j) { carry += uint(digits[j]) * 256; digits[j] = uint8(carry % 58); carry = carry / 58; } while (carry > 0) { digits[digitlength] = uint8(carry % 58); digitlength++; carry = carry / 58; } } //return digits; return string(toAlphabet(reverse(truncate(digits, digitlength)))); } function toAlphabet(uint8[] memory indices) internal pure returns (bytes memory) { bytes memory output = new bytes(indices.length); for (uint256 i = 0; i<indices.length; i++) { output[i] = ALPHABET[indices[i]]; } return output; } function truncate(uint8[] memory array, uint8 length) internal pure returns (uint8[] memory) { uint8[] memory output = new uint8[](length); for (uint256 i = 0; i<length; i++) { output[i] = array[i]; } return output; } function reverse(uint8[] memory input) internal pure returns (uint8[] memory) { uint8[] memory output = new uint8[](input.length); for (uint256 i = 0; i<input.length; i++) { output[i] = input[input.length-1-i]; } return output; } }
Sets `_tokenURI` as the tokenURI of `tokenId`. Requirements: - `tokenId` must exist./
function _setTokenURI(uint64 tokenId, bytes32 ipfs_hash) internal virtual { bytes32 old_URI = editions_by_id[tokenId].ipfs_hash; editions_by_id[tokenId].ipfs_hash = ipfs_hash; emit SetURI(tokenId, old_URI, ipfs_hash); }
1,067,875
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_525(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,454,238
./full_match/5/0xB23F0796e592A91467E5D42F3368Cd722E7f0251/sources/contracts/medrecords.sol
Retrieve permission granted count
function getAppointmentPerPatient(address _address) public view returns(uint256) { return AppointmentPerPatient[_address]; }
11,630,167
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./owner/Operator.sol"; // Note: This pool has no minter key of CHIPs (rewards). Instead, the governance will call // CHIPs distributeReward method and send reward to this pool at the beginning. contract ChipRewardPool is Operator, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public DAO = 0x1C3dF661182c1f9cc8afE226915e5f91E93d1A6f; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CHIPs to distribute per block. uint256 lastRewardBlock; // Last block number that CHIPs distribution occurs. uint256 accChipsPerShare; // Accumulated CHIPs per share, times 1e18. bool isStarted; // Has lastRewardBlock passed? } IERC20 public CHIPS; PoolInfo[] public poolInfo; mapping(uint256 => mapping(address => UserInfo)) public userInfo; uint256 public totalAllocPoint = 0; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public startBlock; // The block number when CHIPS minting starts. uint256 public endBlock; // The block number when CHIPS minting ends. uint256 public timeLockBlock; uint256 public constant BLOCKS_PER_DAY = 28800; // 86400 / 3; uint256 public rewardDuration = 10; // Days. uint256 public totalRewards = 50 ether; uint256 public rewardPerBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event RewardPaid(address indexed user, uint256 amount); constructor(address _CHIPS, uint256 _startBlock) { require(block.number < _startBlock, "ChipRewardPool.constructor(): The current block is after the specified start block."); if (_CHIPS != address(0)) CHIPS = IERC20(_CHIPS); startBlock = _startBlock; endBlock = startBlock.add(BLOCKS_PER_DAY.mul(rewardDuration)); rewardPerBlock = totalRewards.div(endBlock.sub(startBlock)); timeLockBlock = startBlock.add(BLOCKS_PER_DAY.mul(rewardDuration.add(1))); } function checkPoolDuplicate(IERC20 _lpToken) internal view { uint256 length = poolInfo.length; require(length < 6, "ChipRewardPool.checkPoolDuplicate(): Pool size exceeded."); for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].lpToken != _lpToken, "ChipRewardPool.checkPoolDuplicate(): Found duplicate token in pool."); } } // Add a new lp token to the pool. Can only be called by the owner. can add only 5 lp token. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) external onlyOperator { require(poolInfo.length < 5, "ChipRewardPool: can't add pool anymore"); checkPoolDuplicate(_lpToken); if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { // The chef is sleeping. if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; } else { if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } } else { // The chef is cooking. if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (_lastRewardBlock <= startBlock) || (_lastRewardBlock <= block.number); poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : _lastRewardBlock, accChipsPerShare : 0, isStarted : _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's CHIPs allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) public onlyOperator { require(block.number > timeLockBlock, "ChipRewardPool: Locked"); massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); } pool.allocPoint = _allocPoint; } // Return accumulate rewards over the given _from to _to block. function getGeneratedReward(uint256 _from, uint256 _to) public view returns (uint256) { if (_from >= _to) return 0; if (_to <= startBlock) { return 0; } else if (_to >= endBlock) { if (_from >= endBlock) { return 0; } else if (_from <= startBlock) { return rewardPerBlock.mul(endBlock.sub(startBlock)); } else { return rewardPerBlock.mul(endBlock.sub(_from)); } } else { if (_from <= startBlock) { return rewardPerBlock.mul(_to.sub(startBlock)); } else { return rewardPerBlock.mul(_to.sub(_from)); } } } // View function to see pending CHIPs. function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChipsPerShare = pool.accChipsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number); uint256 _CHIPSReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); accChipsPerShare = accChipsPerShare.add(_CHIPSReward.mul(1e18).div(lpSupply)); } return user.amount.mul(accChipsPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() internal { uint256 length = poolInfo.length; require(length < 6, "ChipRewardPool.massUpdatePools(): Pool size exceeded."); 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) internal { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } if (totalAllocPoint > 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number); uint256 _CHIPSReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); pool.accChipsPerShare = pool.accChipsPerShare.add(_CHIPSReward.mul(1e18).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit tokens. function deposit(uint256 _pid, uint256 _amount) external nonReentrant { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accChipsPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeChipsTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { uint256 FeeToDAO = 0; if(_pid != 4){ // In case of BNB, BUSD, BTD, BTS pool, users have to pay 1% fee when they deposit. FeeToDAO = _amount.div(100); } if(FeeToDAO > 0) pool.lpToken.safeTransferFrom(_sender, DAO, FeeToDAO); pool.lpToken.safeTransferFrom(_sender, address(this), _amount.sub(FeeToDAO)); user.amount = user.amount.add(_amount.sub(FeeToDAO)); } user.rewardDebt = user.amount.mul(pool.accChipsPerShare).div(1e18); emit Deposit(_sender, _pid, _amount); } // Withdraw tokens. function withdraw(uint256 _pid, uint256 _amount) external nonReentrant { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "ChipRewardPool.withdraw(): User amount less than withdrawal amount."); updatePool(_pid); uint256 _pending = user.amount.mul(pool.accChipsPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeChipsTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } if (_amount > 0) { uint256 FeeToDAO = 0; if(_pid == 4){ // In case of CHIP/BNB pool, users have to pay 3% fee when they withdraw. FeeToDAO = _amount.mul(3).div(100); } if(FeeToDAO > 0) pool.lpToken.safeTransfer(DAO, FeeToDAO); pool.lpToken.safeTransfer(_sender, _amount.sub(FeeToDAO)); user.amount = user.amount.sub(_amount); } user.rewardDebt = user.amount.mul(pool.accChipsPerShare).div(1e18); emit Withdraw(_sender, _pid, _amount); } // Withdraw without caring about rewards. Emergency only. function emergencyWithdraw(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 _amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(msg.sender, _amount); emit EmergencyWithdraw(msg.sender, _pid, _amount); } // Safe CHIPs transfer function, just in case if rounding error causes pool to not have enough CHIPs. function safeChipsTransfer(address _to, uint256 _amount) internal { uint256 _CHIPSBal = CHIPS.balanceOf(address(this)); if (_CHIPSBal > 0) { if (_amount > _CHIPSBal) { CHIPS.safeTransfer(_to, _CHIPSBal); } else { CHIPS.safeTransfer(_to, _amount); } } } function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator { require(block.number > timeLockBlock, "ChipRewardPool: locked"); if (block.number < endBlock + BLOCKS_PER_DAY * 180) { // Do not allow to drain lpToken if less than 180 days after farming. require(_token != CHIPS, "ChipRewardPool.governanceRecoverUnsupported(): Not a chip token."); uint256 length = poolInfo.length; require(length < 6, "ChipRewardPool.governanceRecoverUnsupported(): Pool size exceeded."); for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; require(_token != pool.lpToken, "ChipRewardPool.governanceRecoverUnsupported(): Skipping liquidity provider token."); } } _token.safeTransfer(to, amount); } function getPoolStatus() external view returns(uint256) { uint256 status; if(block.number <= startBlock) status = 0; else if(block.number > endBlock) status = 2; else status = 1; return status; } }
Do not allow to drain lpToken if less than 180 days after farming.
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator { require(block.number > timeLockBlock, "ChipRewardPool: locked"); if (block.number < endBlock + BLOCKS_PER_DAY * 180) { require(_token != CHIPS, "ChipRewardPool.governanceRecoverUnsupported(): Not a chip token."); uint256 length = poolInfo.length; require(length < 6, "ChipRewardPool.governanceRecoverUnsupported(): Pool size exceeded."); for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; require(_token != pool.lpToken, "ChipRewardPool.governanceRecoverUnsupported(): Skipping liquidity provider token."); } } _token.safeTransfer(to, amount); }
1,773,209
pragma solidity ^0.5.0; // Copyright 2019 OpenST 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. // // ---------------------------------------------------------------------------- // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- import "./EIP20Interface.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title EIP20Token contract. * * @notice EIP20Token implements EIP20Interface. */ contract EIP20Token is EIP20Interface { /* Usings */ using SafeMath for uint256; /** Name of the token. */ string private tokenName; /** Symbol of the token. */ string private tokenSymbol; /** Decimals used by the token. */ uint8 private tokenDecimals; /** Total supply of the token. */ uint256 internal totalTokenSupply; /** Stores the token balance of the accounts. */ mapping(address => uint256) balances; /** Stores the authorization information. */ mapping(address => mapping (address => uint256)) allowed; /* Constructor */ /** * @notice Contract constructor. * * @param _symbol Symbol of the token. * @param _name Name of the token. * @param _decimals Decimal places of the token. */ constructor( string memory _symbol, string memory _name, uint8 _decimals ) public { tokenSymbol = _symbol; tokenName = _name; tokenDecimals = _decimals; totalTokenSupply = 0; } /* Public functions. */ /** * @notice Public function to get the name of the token. * * @return tokenName_ Name of the token. */ function name() public view returns (string memory tokenName_) { tokenName_ = tokenName; } /** * @notice Public function to get the symbol of the token. * * @return tokenSymbol_ Symbol of the token. */ function symbol() public view returns (string memory tokenSymbol_) { tokenSymbol_ = tokenSymbol; } /** * @notice Public function to get the decimals of the token. * * @return tokenDecimals Decimals of the token. */ function decimals() public view returns (uint8 tokenDecimals_) { tokenDecimals_ = tokenDecimals; } /** * @notice Get the balance of an account. * * @param _owner Address of the owner account. * * @return balance_ Account balance of the owner account. */ function balanceOf(address _owner) public view returns (uint256 balance_) { balance_ = balances[_owner]; } /** * @notice Public function to get the total supply of the tokens. * * @dev Get totalTokenSupply as view so that child cannot edit. * * @return totalTokenSupply_ Total token supply. */ function totalSupply() public view returns (uint256 totalTokenSupply_) { totalTokenSupply_ = totalTokenSupply; } /** * @notice Public function to get the allowance. * * @param _owner Address of the owner account. * @param _spender Address of the spender account. * * @return allowance_ Remaining allowance for the spender to spend from * owner's account. */ function allowance( address _owner, address _spender ) public view returns (uint256 allowance_) { allowance_ = allowed[_owner][_spender]; } /** * @notice Public function to transfer the token. * * @dev Fires the transfer event, throws if, _from account does not have * enough tokens to spend. * * @param _to Address to which tokens are transferred. * @param _value Amount of tokens to be transferred. * * @return success_ `true` for a successful transfer, `false` otherwise. */ function transfer( address _to, uint256 _value ) public returns (bool success_) { success_ = transferBalance(msg.sender, _to, _value); } /** * @notice Public function transferFrom. * * @dev Allows a contract to transfer tokens on behalf of _from address * to _to address, the function caller has to be pre-authorized for * multiple transfers up to the total of _value amount by the _from * address. * * @param _from Address from which tokens are transferred. * @param _to Address to which tokens are transferred. * @param _value Amount of tokens transferred. * * @return success_ `true` for a successful transfer, `false` otherwise. */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success_) { allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); success_ = transferBalance(_from, _to, _value); } /** * @notice Public function to approve an account for transfer. * * @dev Allows _spender address to withdraw from function caller's account, * multiple times up to the _value amount, if this function is called * again it overwrites the current allowance with _value. * * @param _spender Address authorized to spend from the function caller's * address. * @param _value Amount up to which spender is authorized to spend. * * @return bool `true` for a successful approval, `false` otherwise. */ function approve( address _spender, uint256 _value ) public returns (bool success_) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); success_ = true; } /* Internal functions. */ /** * @notice Internal function to transfer the tokens. * * @dev This is an internal functions that transfers the token. This * function is called from transfer and transferFrom functions. * * @param _from Address from which tokens are transferred. * @param _to Address to which tokens are transferred. * @param _value Amount of tokens transferred. * * @return success_ `true` for a successful transfer, `false` otherwise. */ function transferBalance( address _from, address _to, uint256 _value ) internal returns (bool success_) { /** * According to the EIP20 spec, "transfers of 0 values MUST be treated * as normal transfers and fire the Transfer event". * Also, should throw if not enough balance. This is taken care of by * SafeMath. */ balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); success_ = true; } }
Internal function to transfer the tokens. This is an internal functions that transfers the token. This function is called from transfer and transferFrom functions. _from Address from which tokens are transferred. _to Address to which tokens are transferred. _value Amount of tokens transferred. return success_ `true` for a successful transfer, `false` otherwise./
function transferBalance( address _from, address _to, uint256 _value ) internal returns (bool success_) { balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); success_ = true;
12,879,443
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.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 IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { 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: 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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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] = valueIndex; // Replace lastvalue's index to valueIndex // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol'; import './Factories/FactoryStorage.sol'; import './Factories/IFactoryConsumer.sol'; contract BeyondFactories is OwnableUpgradeable, PausableUpgradeable, FactoryStorage { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; // emitted when a factory is created event FactoryCreated(uint256 indexed id, address indexed creator, string metadata); // emitted when factories are updated (active, paused, price, metadata...) event FactoriesUpdate(uint256[] factoryIds); // emitted when a factory has reached its max supply event FactoryOut(uint256 indexed id); // emitted when a donation recipient is created or modified event DonationRecipientsUpdate(uint256[] ids); // emitted when configuration changed event ConfigurationUpdate(); // emitted when a tokenId is minted from a factory event MintFromFactory( uint256 indexed factoryId, address indexed minter, uint256 createdIndex, // index in factory address registry, uint256 tokenId, bytes32 data, string seed, uint256 price ); /** * @dev initialize function */ function initialize( address payable platformBeneficiary, uint16 platformFee, uint16 donationMinimum, bool restricted, bool defaultActive, bool canEditPlatformFees, address ownedBy ) public initializer { __Ownable_init(); __Pausable_init(); contractConfiguration.platformBeneficiary = platformBeneficiary; contractConfiguration.platformFee = platformFee; contractConfiguration.donationMinimum = donationMinimum; contractConfiguration.canEditPlatformFees = canEditPlatformFees; // defines if factory are active by defualt or not contractConfiguration.defaultFactoryActivation = defaultActive; // if the factory is restricted contractConfiguration.restricted = restricted; if (address(0) != ownedBy) { transferOwnership(ownedBy); } } /** * @dev called by creators or admin to register a new factory * * @param factoryType - if unique (erc721) or edition (erc1155) * @param creator - the factory creator, is used when contract is restricted * @param paused - if the factory starts paused * @param price - factory price, in wei * @param maxSupply - times this factory can be used; 0 = inifinity * @param withSeed - if the factory needs a seed when creating * @param metadata - factory metadata uri - ipfs uri most of the time */ function registerFactory( FactoryType factoryType, // if erc721 or erc1155 address creator, bool paused, // if the factory start paused uint256 price, // factory price, in wei uint256 maxSupply, // max times this factory can be used; 0 = inifinity bool withSeed, // if the factory needs a seed when creating string memory metadata, uint256 royaltyValue, address consumer ) external { require(bytes(metadata).length > 0, 'Need metadata URI'); ContractConfiguration memory _configuration = contractConfiguration; require(!_configuration.restricted || owner() == _msgSender(), 'Restricted.'); // Restricted contracts only allow OPERATORS to mint if (creator == address(0)) { creator = msg.sender; } // if no consumer given, take one of the default if (consumer == address(0)) { if (factoryType == FactoryType.Unique) { consumer = _configuration.uniqueConsumer; } else { consumer = _configuration.editionsConsumer; } } uint256 factoryId = factoriesCount + 1; factories[factoryId] = Factory({ factoryType: factoryType, creator: creator, active: _configuration.defaultFactoryActivation, paused: paused, price: price, maxSupply: maxSupply, withSeed: withSeed, royaltyValue: royaltyValue, metadata: metadata, created: 0, consumer: consumer, donationId: 0, donationAmount: _configuration.donationMinimum }); factoriesCount = factoryId; emit FactoryCreated(factoryId, creator, metadata); } /** * @dev Function to mint a token without any seed * * @param factoryId id of the factory to mint from * @param amount - amount to mint; only for Editions factories * @param to - address to mint to, if address(0), msg.sender * @param swapContract - address of the contract if this is a swap * @param swapTokenId - id of the token if it's a swap */ function mintFrom( uint256 factoryId, uint256 amount, address to, address swapContract, uint256 swapTokenId ) external payable { _mintFromFactory(factoryId, '', '', amount, to, swapContract, swapTokenId); } /** * @dev Function to mint a token from a factory with a 32 bytes hex string as has * * @param factoryId id of the factory to mint from * @param seed The hash used to create the seed * @param amount - amount to mint; only for Editions factories * @param to - address to mint to, if address(0), msg.sender * @param swapContract - address of the contract if this is a swap * @param swapTokenId - id of the token if it's a swap * * Seed will be used to create, off-chain, the token unique seed with the function: * tokenSeed = sha3(blockHash, factoryId, createdIndex, minter, registry, tokenId, seed) * * There is as much chance of collision than there is on creating a duplicate * of an ethereum private key, which is low enough to not go to crazy length in * order to try to stop the "almost impossible" * * I thought about using a commit/reveal (revealed at the time of nft metadata creation) * But this could break the token generation if, for example, the reveal was lost (db problem) * between the function call and the reveal. * * * All in all, using the blockhash in the seed makes this as secure as "on-chain pseudo rng". * * Also with this method, all informations to recreate the token can always be retrieved from the events. */ function mintWithHash( uint256 factoryId, bytes32 seed, uint256 amount, address to, address swapContract, uint256 swapTokenId ) external payable { require(seed != 0x0, 'Invalid seed'); _mintFromFactory(factoryId, seed, '', amount, to, swapContract, swapTokenId); } /** * @dev Function to mint a token from a factory with a known seed * * This known seed can either be: * - a user inputed seed * - the JSON string of the factory properties. Allowing for future reconstruction of nft metadata if needed * * @param factoryId id of the factory to mint from * @param seed The seed used to mint * @param amount - amount to mint; only for Editions factories * @param to - address to mint to, if address(0), msg.sender * @param swapContract - address of the contract if this is a swap * @param swapTokenId - id of the token if it's a swap */ function mintWithOpenSeed( uint256 factoryId, string memory seed, uint256 amount, address to, address swapContract, uint256 swapTokenId ) external payable { require(bytes(seed).length > 0, 'Invalid seed'); _mintFromFactory( factoryId, keccak256(abi.encodePacked(seed)), seed, amount, to, swapContract, swapTokenId ); } /** * @dev allows a creator to pause / unpause the use of their Factory */ function setFactoryPause(uint256 factoryId, bool isPaused) external { Factory storage factory = factories[factoryId]; require(msg.sender == factory.creator, 'Not factory creator'); factory.paused = isPaused; emit FactoriesUpdate(_asSingletonArray(factoryId)); } /** * @dev allows a creator to update the price of their factory */ function setFactoryPrice(uint256 factoryId, uint256 price) external { Factory storage factory = factories[factoryId]; require(msg.sender == factory.creator, 'Not factory creator'); factory.price = price; emit FactoriesUpdate(_asSingletonArray(factoryId)); } /** * @dev allows a creator to define a swappable factory */ function setFactorySwap( uint256 factoryId, address swapContract, uint256 swapTokenId, bool fixedId ) external { Factory storage factory = factories[factoryId]; require(msg.sender == factory.creator, 'Not factory creator'); if (swapContract == address(0)) { delete factorySwap[factoryId]; } else { factorySwap[factoryId] = TokenSwap({ is1155: IERC1155Upgradeable(swapContract).supportsInterface(0xd9b67a26), fixedId: fixedId, swapContract: swapContract, swapTokenId: swapTokenId }); } emit FactoriesUpdate(_asSingletonArray(factoryId)); } /** * @dev allows a creator to define to which orga they want to donate if not automatic * and how much (minimum 2.50, taken from the BeyondNFT 10%) * * Be careful when using this: * - if donationId is 0, then the donation will be automatic * if you want to set a specific donation id, always use id + 1 */ function setFactoryDonation( uint256 factoryId, uint256 donationId, uint16 donationAmount ) external { Factory storage factory = factories[factoryId]; require(msg.sender == factory.creator, 'Not factory creator'); // if 0, set automatic; factory.donationId = donationId; // 2.50 is the minimum that can be set // those 2.50 are taken from BeyondNFT share of 10% if (donationAmount >= contractConfiguration.donationMinimum) { factory.donationAmount = donationAmount; } emit FactoriesUpdate(_asSingletonArray(factoryId)); } /** * @dev allows to activate and deactivate factories * * Because BeyondNFT is an open platform with no curation prior factory creation * This can only be called by BeyondNFT administrators, if there is any abuse with a factory */ function setFactoryActiveBatch(uint256[] memory factoryIds, bool[] memory areActive) external onlyOwner { for (uint256 i; i < factoryIds.length; i++) { Factory storage factory = factories[factoryIds[i]]; require(address(0) != factory.creator, 'Factory not found'); factory.active = areActive[i]; } emit FactoriesUpdate(factoryIds); } /** * @dev allows to set a factory consumer */ function setFactoryConsumerBatch(uint256[] memory factoryIds, address[] memory consumers) external onlyOwner { for (uint256 i; i < factoryIds.length; i++) { Factory storage factory = factories[factoryIds[i]]; require(address(0) != factory.creator, 'Factory not found'); factory.consumer = consumers[i]; } emit FactoriesUpdate(factoryIds); } /** * @dev adds Donation recipients */ function addDonationRecipientsBatch( address[] memory recipients, string[] memory names, bool[] memory autos ) external onlyOwner { DonationRecipient[] storage donationRecipients_ = donationRecipients; EnumerableSetUpgradeable.UintSet storage autoDonations_ = autoDonations; uint256[] memory ids = new uint256[](recipients.length); for (uint256 i; i < recipients.length; i++) { require(bytes(names[i]).length > 0, 'Invalid name'); donationRecipients_.push( DonationRecipient({ autoDonation: autos[i], recipient: recipients[i], name: names[i] }) ); ids[i] = donationRecipients_.length - 1; if (autos[i]) { autoDonations_.add(ids[i]); } } emit DonationRecipientsUpdate(ids); } /** * @dev modify Donation recipients */ function setDonationRecipientBatch( uint256[] memory ids, address[] memory recipients, string[] memory names, bool[] memory autos ) external onlyOwner { DonationRecipient[] storage donationRecipients_ = donationRecipients; EnumerableSetUpgradeable.UintSet storage autoDonations_ = autoDonations; for (uint256 i; i < recipients.length; i++) { if (address(0) != recipients[i]) { donationRecipients_[ids[i]].recipient = recipients[i]; } if (bytes(names[i]).length > 0) { donationRecipients_[ids[i]].name = names[i]; } donationRecipients_[ids[i]].autoDonation = autos[i]; if (autos[i]) { autoDonations_.add(ids[i]); } else { autoDonations_.remove(ids[i]); } } emit DonationRecipientsUpdate(ids); } /** * @dev allows to update a factory metadata * * This can only be used by admins in very specific cases when a critical bug is found */ function setFactoryMetadata(uint256 factoryId, string memory metadata) external onlyOwner { Factory storage factory = factories[factoryId]; require(address(0) != factory.creator, 'Factory not found'); factory.metadata = metadata; emit FactoriesUpdate(_asSingletonArray(factoryId)); } function setPlatformFee(uint16 fee) external onlyOwner { require(contractConfiguration.canEditPlatformFees == true, "Can't edit platform fees"); require(fee <= 10000, 'Fees too high'); contractConfiguration.platformFee = fee; emit ConfigurationUpdate(); } function setPlatformBeneficiary(address payable beneficiary) external onlyOwner { require(contractConfiguration.canEditPlatformFees == true, "Can't edit platform fees"); require(address(beneficiary) != address(0), 'Invalid beneficiary'); contractConfiguration.platformBeneficiary = beneficiary; emit ConfigurationUpdate(); } function setDefaultFactoryActivation(bool isDefaultActive) external onlyOwner { contractConfiguration.defaultFactoryActivation = isDefaultActive; emit ConfigurationUpdate(); } function setRestricted(bool restricted) external onlyOwner { contractConfiguration.restricted = restricted; emit ConfigurationUpdate(); } function setFactoriesConsumers(address unique, address editions) external onlyOwner { if (address(0) != unique) { contractConfiguration.uniqueConsumer = unique; } if (address(0) != editions) { contractConfiguration.editionsConsumer = editions; } emit ConfigurationUpdate(); } /** * @dev Pauses all token creation. * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function pause() public virtual onlyOwner { _pause(); } /** * @dev Unpauses all token creation. * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function unpause() public virtual onlyOwner { _unpause(); } /** * @dev This function does the minting process. * It checkes that the factory exists, and if there is a seed, that it wasn't already * used for it. * * Depending on the factory type, it will call the right contract to mint the token * to msg.sender * * Requirements: * - contract musn't be paused * - If there is a seed, it must not have been used for this Factory */ function _mintFromFactory( uint256 factoryId, bytes32 seed, string memory openSeed, uint256 amount, address to, address swapContract, uint256 swapTokenId ) internal whenNotPaused { require(amount >= 1, 'Amount is zero'); Factory storage factory = factories[factoryId]; require(factory.active && !factory.paused, 'Factory inactive or not found'); require( factory.maxSupply == 0 || factory.created < factory.maxSupply, 'Factory max supply reached' ); // if the factory requires a seed (user seed, random seed) if (factory.withSeed) { // verify that the seed is not empty and that it was never used before // for this factory require( seed != 0x0 && factoriesSeed[factoryId][seed] == false, 'Invalid seed or already taken' ); factoriesSeed[factoryId][seed] = true; } factory.created++; address consumer = _doPayment(factoryId, factory, swapContract, swapTokenId); // if people mint to another address if (to == address(0)) { to = msg.sender; } uint256 tokenId = IFactoryConsumer(consumer).mint( to, factoryId, amount, factory.creator, factory.royaltyValue ); // emit minting from factory event with data and seed emit MintFromFactory( factoryId, to, factory.created, consumer, tokenId, seed, openSeed, msg.value ); if (factory.created == factory.maxSupply) { emit FactoryOut(factoryId); } } function _doPayment( uint256 factoryId, Factory storage factory, address swapContract, uint256 swapTokenId ) internal returns (address) { ContractConfiguration memory contractConfiguration_ = contractConfiguration; // try swap if (swapContract != address(0)) { TokenSwap memory swap = factorySwap[factoryId]; // verify that the swap asked is the right one require( // contract match swap.swapContract == swapContract && // and either ANY idea id works, either the given ID is the right one (!swap.fixedId || swap.swapTokenId == swapTokenId), 'Invalid swap' ); require(msg.value == 0, 'No value allowed when swapping'); // checking if ERC1155 or ERC721 // and burn the tokenId // using 0xdead address to be sure it works with contracts // that have no burn function // // those functions calls should revert if there is a problem when transfering if (swap.is1155) { IERC1155Upgradeable(swapContract).safeTransferFrom( msg.sender, address(0xdEaD), swapTokenId, 1, '' ); } else { IERC721Upgradeable(swapContract).transferFrom( msg.sender, address(0xdEaD), swapTokenId ); } } else if (factory.price > 0) { require(msg.value == factory.price, 'Wrong value sent'); uint256 platformFee = (msg.value * uint256(contractConfiguration_.platformFee)) / 10000; DonationRecipient[] memory donationRecipients_ = donationRecipients; uint256 donation; if (donationRecipients_.length > 0) { donation = (msg.value * uint256(factory.donationAmount)) / 10000; // send fees to platform contractConfiguration_.platformBeneficiary.transfer(platformFee); if (factory.donationId > 0) { payable(donationRecipients_[factory.donationId - 1].recipient).transfer( donation ); } else { // send to current cursor EnumerableSetUpgradeable.UintSet storage autoDonations_ = autoDonations; payable(donationRecipients_[autoDonations_.at(donationCursor)].recipient) .transfer(donation); donationCursor = (donationCursor + 1) % autoDonations_.length(); } } // send rest to creator payable(factory.creator).transfer(msg.value - platformFee - donation); } if (factory.consumer != address(0)) { return factory.consumer; } return factory.factoryType == FactoryType.Multiple ? contractConfiguration_.editionsConsumer : contractConfiguration_.uniqueConsumer; } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } /** * @dev do not accept value sent directly to contract */ receive() external payable { revert('No value accepted'); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol'; contract FactoryStorage { enum FactoryType {Unique, Multiple} struct DonationRecipient { bool autoDonation; address recipient; string name; } struct TokenSwap { bool is1155; bool fixedId; address swapContract; uint256 swapTokenId; } struct Factory { // factory type FactoryType factoryType; // factory creator address creator; // if factory is active or not // this is changed by beyondNFT admins if abuse with factories bool active; // if factory is paused or not <- this is changed by creator bool paused; // if the factory requires a seed bool withSeed; // the contract this factory mint with address consumer; // donation amount, 2.5% (250) is the minimum amount uint16 donationAmount; // id of the donation recipient for this factory // this id must be id + 1, so 0 can be considered as automatic uint256 donationId; // price to mint uint256 price; // how many were minted already uint256 created; // 0 if infinite uint256 maxSupply; // royalties uint256 royaltyValue; // The factory metadata uri, contains all informations about where to find code, properties etc... // this is the base that will be used to create NFTs string metadata; } struct ContractConfiguration { bool restricted; bool defaultFactoryActivation; address uniqueConsumer; address editionsConsumer; bool canEditPlatformFees; uint16 platformFee; uint16 donationMinimum; address payable platformBeneficiary; } ContractConfiguration public contractConfiguration; uint256 public factoriesCount; // the factories mapping(uint256 => Factory) public factories; // some factories allow to swap other contracts token again one from the factory mapping(uint256 => TokenSwap) public factorySwap; // the seeds already used by each factories // not in the struct as it complicated things mapping(uint256 => mapping(bytes32 => bool)) public factoriesSeed; DonationRecipient[] public donationRecipients; uint256 donationCursor; EnumerableSetUpgradeable.UintSet internal autoDonations; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IFactoryConsumer { function mint( address creator, uint256 factoryId, uint256 amount, address royaltyRecipient, uint256 royaltyValue ) external returns (uint256); }
Pauses all token creation. Requirements: - the caller must have the `DEFAULT_ADMIN_ROLE`./
function pause() public virtual onlyOwner { _pause(); }
13,712,693
pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * 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 SafeERC20Transfer { function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @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 private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *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 Ownable { using SafeMath for uint256; using SafeERC20Transfer for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address private _wallet; // How many token units a buyer gets per 1 ETH. uint256 private _rate = 5000; // Amount of wei raised uint256 private _weiRaised; // Accrued tokens amount uint256 private _accruedTokensAmount; // freezing periods in seconds uint256 private _threeMonths = 5256000; uint256 private _sixMonths = 15768000; uint256 private _nineMonths = 21024000; uint256 private _twelveMonths = 31536000; // ICO configuration uint256 private _foundersTokens = 4e7; uint256 private _distributedTokens = 1e9; uint256 public softCap = 1000 ether; uint256 public hardCap = 35000 ether; uint256 public preICO_1_Start = 1541030400; // 01/11/2018 00:00:00 uint256 public preICO_2_Start = 1541980800; // 12/11/2018 00:00:00 uint256 public preICO_3_Start = 1542844800; // 22/11/2018 00:00:00 uint256 public ICO_Start = 1543622400; // 01/12/2018 00:00:00 uint256 public ICO_End = 1548979199; // 31/01/2019 23:59:59 uint32 public bonus1 = 30; // pre ICO phase 1 uint32 public bonus2 = 20; // pre ICO phase 2 uint32 public bonus3 = 10; // pre ICO phase 3 uint32 public whitelistedBonus = 10; mapping (address => bool) private _whitelist; // tokens accrual mapping (address => uint256) public threeMonthsFreezingAccrual; mapping (address => uint256) public sixMonthsFreezingAccrual; mapping (address => uint256) public nineMonthsFreezingAccrual; mapping (address => uint256) public twelveMonthsFreezingAccrual; // investors ledger mapping (address => uint256) public ledger; /** * Event for tokens accrual logging * @param to who tokens where accrued to * @param accruedAmount amount of tokens accrued * @param freezingTime period for freezing in seconds * @param purchasedAmount amount of tokens purchased * @param weiValue amount of ether contributed */ event Accrual( address to, uint256 accruedAmount, uint256 freezingTime, uint256 purchasedAmount, uint256 weiValue ); /** * Event for accrued tokens releasing logging * @param to who tokens where release to * @param amount amount of tokens released */ event Released( address to, uint256 amount ); /** * Event for refund logging * @param to who have got refund * @param value ether refunded */ event Refunded( address to, uint256 value ); /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param founders Address for founders tokens accrual * @param token Address of the token being sold */ constructor(address newOwner, address wallet, address founders, IERC20 token) public { require(wallet != address(0)); require(founders != address(0)); require(token != address(0)); require(newOwner != address(0)); transferOwnership(newOwner); _wallet = wallet; _token = token; twelveMonthsFreezingAccrual[founders] = _foundersTokens; _accruedTokensAmount = _foundersTokens; emit Accrual(founders, _foundersTokens, _twelveMonths, 0, 0); } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @return the token being sold. */ function token() public view returns(IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns(address) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @return if who is whitelisted. * @param who investors address */ function whitelist(address who) public view returns (bool) { return _whitelist[who]; } /** * add investor to whitelist * @param who investors address */ function addToWhitelist(address who) public onlyOwner { _whitelist[who] = true; } /** * remove investor from whitelist * @param who investors address */ function removeFromWhitelist(address who) public onlyOwner { _whitelist[who] = false; } /** * Accrue bonuses to advisors * @param to address for accrual * @param amount tokem amount */ function accrueAdvisorsTokens(address to, uint256 amount) public onlyOwner { require(now > ICO_End); uint256 tokenBalance = _token.balanceOf(address(this)); require(tokenBalance >= _accruedTokensAmount.add(amount)); _accruedTokensAmount = _accruedTokensAmount.add(amount); sixMonthsFreezingAccrual[to] = sixMonthsFreezingAccrual[to].add(amount); emit Accrual(to, amount, _sixMonths, 0, 0); } /** * Accrue bonuses to partners * @param to address for accrual * @param amount tokem amount */ function accruePartnersTokens(address to, uint256 amount) public onlyOwner { require(now > ICO_End); uint256 tokenBalance = _token.balanceOf(address(this)); require(tokenBalance >= _accruedTokensAmount.add(amount)); _accruedTokensAmount = _accruedTokensAmount.add(amount); nineMonthsFreezingAccrual[to] = nineMonthsFreezingAccrual[to].add(amount); emit Accrual(to, amount, _nineMonths, 0, 0); } /** * Accrue bounty and airdrop bonuses * @param to address for accrual * @param amount tokem amount */ function accrueBountyTokens(address to, uint256 amount) public onlyOwner { require(now > ICO_End); uint256 tokenBalance = _token.balanceOf(address(this)); require(tokenBalance >= _accruedTokensAmount.add(amount)); _accruedTokensAmount = _accruedTokensAmount.add(amount); twelveMonthsFreezingAccrual[to] = twelveMonthsFreezingAccrual[to].add(amount); emit Accrual(to, amount, _twelveMonths, 0, 0); } /** * release accrued tokens */ function release() public { address who = msg.sender; uint256 amount; if (now > ICO_End.add(_twelveMonths) && twelveMonthsFreezingAccrual[who] > 0) { amount = amount.add(twelveMonthsFreezingAccrual[who]); _accruedTokensAmount = _accruedTokensAmount.sub(twelveMonthsFreezingAccrual[who]); twelveMonthsFreezingAccrual[who] = 0; } if (now > ICO_End.add(_nineMonths) && nineMonthsFreezingAccrual[who] > 0) { amount = amount.add(nineMonthsFreezingAccrual[who]); _accruedTokensAmount = _accruedTokensAmount.sub(nineMonthsFreezingAccrual[who]); nineMonthsFreezingAccrual[who] = 0; } if (now > ICO_End.add(_sixMonths) && sixMonthsFreezingAccrual[who] > 0) { amount = amount.add(sixMonthsFreezingAccrual[who]); _accruedTokensAmount = _accruedTokensAmount.sub(sixMonthsFreezingAccrual[who]); sixMonthsFreezingAccrual[who] = 0; } if (now > ICO_End.add(_threeMonths) && threeMonthsFreezingAccrual[who] > 0) { amount = amount.add(threeMonthsFreezingAccrual[who]); _accruedTokensAmount = _accruedTokensAmount.sub(threeMonthsFreezingAccrual[who]); threeMonthsFreezingAccrual[who] = 0; } if (amount > 0) { _deliverTokens(who, amount); emit Released(who, amount); } } /** * refund ether */ function refund() public { address investor = msg.sender; require(now > ICO_End); require(_weiRaised < softCap); require(ledger[investor] > 0); uint256 value = ledger[investor]; ledger[investor] = 0; investor.transfer(value); emit Refunded(investor, value); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param beneficiary Address performing the token purchase */ function buyTokens(address beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // bonus tokens accrual and ensure token balance is enough for accrued tokens release _accrueBonusTokens(beneficiary, tokens, weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); if (_weiRaised >= softCap) _forwardFunds(); ledger[msg.sender] = ledger[msg.sender].add(msg.value); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Accrue bonus tokens. * @param beneficiary Address for tokens accrual * @param tokenAmount amount of tokens that beneficiary get */ function _accrueBonusTokens(address beneficiary, uint256 tokenAmount, uint256 weiAmount) internal { uint32 bonus = 0; uint256 bonusTokens = 0; uint256 tokenBalance = _token.balanceOf(address(this)); if (_whitelist[beneficiary] && now < ICO_Start) bonus = bonus + whitelistedBonus; if (now < preICO_2_Start) { bonus = bonus + bonus1; bonusTokens = tokenAmount.mul(bonus).div(100); require(tokenBalance >= _accruedTokensAmount.add(bonusTokens).add(tokenAmount)); _accruedTokensAmount = _accruedTokensAmount.add(bonusTokens); nineMonthsFreezingAccrual[beneficiary] = nineMonthsFreezingAccrual[beneficiary].add(bonusTokens); emit Accrual(beneficiary, bonusTokens, _nineMonths, tokenAmount, weiAmount); } else if (now < preICO_3_Start) { bonus = bonus + bonus2; bonusTokens = tokenAmount.mul(bonus).div(100); require(tokenBalance >= _accruedTokensAmount.add(bonusTokens).add(tokenAmount)); _accruedTokensAmount = _accruedTokensAmount.add(bonusTokens); sixMonthsFreezingAccrual[beneficiary] = sixMonthsFreezingAccrual[beneficiary].add(bonusTokens); emit Accrual(beneficiary, bonusTokens, _sixMonths, tokenAmount, weiAmount); } else if (now < ICO_Start) { bonus = bonus + bonus3; bonusTokens = tokenAmount.mul(bonus).div(100); require(tokenBalance >= _accruedTokensAmount.add(bonusTokens).add(tokenAmount)); _accruedTokensAmount = _accruedTokensAmount.add(bonusTokens); threeMonthsFreezingAccrual[beneficiary] = threeMonthsFreezingAccrual[beneficiary].add(bonusTokens); emit Accrual(beneficiary, bonusTokens, _threeMonths, tokenAmount, weiAmount); } else { require(tokenBalance >= _accruedTokensAmount.add(tokenAmount)); emit Accrual(beneficiary, 0, 0, tokenAmount, weiAmount); } } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { require(beneficiary != address(0)); require(weiAmount != 0); require(_weiRaised.add(weiAmount) <= hardCap); require(now >= preICO_1_Start); require(now <= ICO_End); } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev The way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount( uint256 weiAmount ) internal view returns (uint256) { return weiAmount.mul(_rate).div(1e18); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { uint256 balance = address(this).balance; _wallet.transfer(balance); } }
low level token purchase DO NOT OVERRIDE beneficiary Address performing the token purchase/ calculate token amount to be created bonus tokens accrual and ensure token balance is enough for accrued tokens release update state
function buyTokens(address beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); _accrueBonusTokens(beneficiary, tokens, weiAmount); _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); if (_weiRaised >= softCap) _forwardFunds(); ledger[msg.sender] = ledger[msg.sender].add(msg.value); }
12,909,233
pragma solidity ^0.4.12; contract KydyUtil { uint256 private randomSeed_ = 0; function isKydyUtil() public pure returns (bool) { return true; } function getRand(uint256 tempSeed) public returns (uint256) { bytes32 seedHash = keccak256(bytes32(tempSeed)); randomSeed_ += uint256(seedHash); return randomSeed_ + uint256(block.blockhash(block.number - 1)); } } contract GeneReleaseInterface { function isGeneRelease() public pure returns (bool); function isCodeReleased(uint256 traitIndex, uint256 code) public view returns (bool); } contract KydyUtilInterface { function isKydyUtil() public view returns (bool); function getRand(uint256 tempSeed) public returns(uint256); } /// @title A facet of KydyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KydyCore contract documentation to understand how the various contract facets are arranged. contract KydyAccessControl { // This facet controls access control for CryptoKydys. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the KydyCore constructor. // // - The CFO: The CFO can withdraw funds from KydyCore and its auction contracts. // // - The COO: The COO can release gen0 Kydys to auction, and mint promo cats. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) public onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } function withdrawBalance() external onlyCFO { cfoAddress.transfer(this.balance); } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() public onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title A deterministic implementation of Breeding algo for tests contract GeneScience is KydyAccessControl { bool public isGeneScience = true; uint256 traitBits_ = 20; uint256 codeBits_ = 5; uint256 traitsInGene_ = 12; KydyUtilInterface public kydyUtil_; GeneReleaseInterface private geneRelease_; function GeneScience(address kydyUtilAddr, address geneReleaseAddr) public { ceoAddress = msg.sender; cooAddress = msg.sender; cfoAddress = msg.sender; kydyUtil_ = KydyUtilInterface(kydyUtilAddr); geneRelease_ = GeneReleaseInterface(geneReleaseAddr); } function setKydyUtilAddress(address newKydyUtil) public onlyCEO { KydyUtilInterface candidateContract = KydyUtilInterface(newKydyUtil); require(candidateContract.isKydyUtil()); kydyUtil_ = candidateContract; } function setGeneReleaseAddress(address newGeneRelease) public onlyCEO { GeneReleaseInterface candidateContract = GeneReleaseInterface(newGeneRelease); require(candidateContract.isGeneRelease()); geneRelease_ = candidateContract; } function isGeneScience() public pure returns (bool) { return true; } event mixGeneResult(uint256 indexed gene1, uint256 indexed gene2, uint256 mixedGene); /// @dev given genes of Kydy 1 & 2, return a silly genetic combination function mixGenes(uint256 gene1, uint256 gene2) public returns (uint256) { uint256 _mixedGene = 0; for (uint8 i = 0 ; i < traitsInGene_; i++) { uint256 _mixedTrait = mixTraits( (gene1 >> (i * traitBits_)) & 0xfffff, (gene2 >> (i * traitBits_)) & 0xfffff, i ); _mixedGene += _mixedTrait << (i * traitBits_); } mixGeneResult(gene1, gene2, _mixedGene); return _mixedGene; } function mixTraits(uint256 trait1, uint256 trait2, uint256 traitIndex) public returns (uint256) { uint256 _mixedTrait = 0; for (uint8 i = 0 ; i < 4 ; i++) { uint256 _code1 = selectCode(trait1); uint256 _code2 = selectCode(trait2); _mixedTrait += mixCodes(_code1, _code2, traitIndex) << (i * codeBits_); } return _mixedTrait; } uint256 public selectSeed_ = uint256(keccak256("SELECT")); uint256 public selectDenom_ = 128; uint256 public selectActive_ = 96; uint256 public selectHidden1_ = selectActive_ + 24; uint256 public selectHidden2_ = selectHidden1_ + 6; // Selector 3 below is unnecessary // uint256 public selectHiddenNumer3_ = 2; function selectCode(uint256 trait) public returns (uint256) { uint256 _selector = kydyUtil_.getRand(selectSeed_) % selectDenom_; if (_selector < selectActive_) return trait & 0x1f; else if (_selector < selectHidden1_) return (trait >> codeBits_) & 0x1f; else if (_selector < selectHidden2_) return (trait >> (codeBits_ * 2)) & 0x1f; else return (trait >> (codeBits_ * 3)) & 0x1f; } function isMutatable(uint256 code1, uint256 code2) public pure returns (bool) { if (code1 - code2 == 1 || code2 - code1 == 1) { if ((code1 + code2) % 4 == 1) return true; } return false; } function mixCodes(uint256 code1, uint256 code2, uint256 traitIndex) public returns (uint256) { if (isMutatable(code1, code2)) return mixCodesMutatable(code1, code2, traitIndex); else return mixCodesNormal(code1, code2); } uint256 public mutateSeed_ = uint256(keccak256("MUTATE")); function mixCodesMutatable(uint256 code1, uint256 code2, uint256 traitIndex) public returns (uint256) { if (kydyUtil_.getRand(mutateSeed_) % 4 == 0) { uint256 result; if (code1 % 2 == 1) result = (code1 >> 1) + 0x10; else result = (code2 >> 1) + 0x10; if (geneRelease_.isCodeReleased(traitIndex, result)) return result; else return mixCodesNormal(code1, code2); } else { return mixCodesNormal(code1, code2); } } uint256 public normalSeed_ = uint256(keccak256("NORMAL")); function mixCodesNormal(uint256 code1, uint256 code2) public returns (uint256) { if (kydyUtil_.getRand(normalSeed_) % 2 == 0) return code1; else return code2; } }
given genes of Kydy 1 & 2, return a silly genetic combination
function mixGenes(uint256 gene1, uint256 gene2) public returns (uint256) { uint256 _mixedGene = 0; for (uint8 i = 0 ; i < traitsInGene_; i++) { uint256 _mixedTrait = mixTraits( (gene1 >> (i * traitBits_)) & 0xfffff, (gene2 >> (i * traitBits_)) & 0xfffff, i ); _mixedGene += _mixedTrait << (i * traitBits_); } mixGeneResult(gene1, gene2, _mixedGene); return _mixedGene; }
6,350,647
// SPDX-License-Identifier: Apache-2.0 /* Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol"; import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol"; import "../../fixins/FixinERC721Spender.sol"; import "../../migrations/LibMigrate.sol"; import "../../storage/LibERC721OrdersStorage.sol"; import "../interfaces/IFeature.sol"; import "../interfaces/IERC721OrdersFeature.sol"; import "../libs/LibNFTOrder.sol"; import "../libs/LibSignature.sol"; import "./NFTOrders.sol"; /// @dev Feature for interacting with ERC721 orders. contract ERC721OrdersFeature is IFeature, IERC721OrdersFeature, FixinERC721Spender, NFTOrders { using LibSafeMathV06 for uint256; using LibNFTOrder for LibNFTOrder.ERC721Order; using LibNFTOrder for LibNFTOrder.NFTOrder; /// @dev Name of this feature. string public constant override FEATURE_NAME = "ERC721Orders"; /// @dev Version of this feature. uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0); /// @dev The magic return value indicating the success of a `onERC721Received`. bytes4 private constant ERC721_RECEIVED_MAGIC_BYTES = this.onERC721Received.selector; constructor(address zeroExAddress, IEtherTokenV06 weth) public NFTOrders(zeroExAddress, weth) {} /// @dev Initialize and register this feature. /// Should be delegatecalled by `Migrate.migrate()`. /// @return success `LibMigrate.SUCCESS` on success. function migrate() external returns (bytes4 success) { _registerFeatureFunction(this.sellERC721.selector); _registerFeatureFunction(this.buyERC721.selector); _registerFeatureFunction(this.cancelERC721Order.selector); _registerFeatureFunction(this.batchBuyERC721s.selector); _registerFeatureFunction(this.matchERC721Orders.selector); _registerFeatureFunction(this.batchMatchERC721Orders.selector); _registerFeatureFunction(this.onERC721Received.selector); _registerFeatureFunction(this.preSignERC721Order.selector); _registerFeatureFunction(this.validateERC721OrderSignature.selector); _registerFeatureFunction(this.validateERC721OrderProperties.selector); _registerFeatureFunction(this.getERC721OrderStatus.selector); _registerFeatureFunction(this.getERC721OrderHash.selector); _registerFeatureFunction(this.getERC721OrderStatusBitVector.selector); return LibMigrate.MIGRATE_SUCCESS; } /// @dev Sells an ERC721 asset to fill the given order. /// @param buyOrder The ERC721 buy order. /// @param signature The order signature from the maker. /// @param erc721TokenId The ID of the ERC721 asset being /// sold. If the given order specifies properties, /// the asset must satisfy those properties. Otherwise, /// it must equal the tokenId in the order. /// @param unwrapNativeToken If this parameter is true and the /// ERC20 token of the order is e.g. WETH, unwraps the /// token before transferring it to the taker. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC721OrderCallback` on `msg.sender` after /// the ERC20 tokens have been transferred to `msg.sender` /// but before transferring the ERC721 asset to the buyer. function sellERC721( LibNFTOrder.ERC721Order memory buyOrder, LibSignature.Signature memory signature, uint256 erc721TokenId, bool unwrapNativeToken, bytes memory callbackData ) public override { _sellERC721( buyOrder, signature, erc721TokenId, unwrapNativeToken, msg.sender, // taker msg.sender, // owner callbackData ); } /// @dev Buys an ERC721 asset by filling the given order. /// @param sellOrder The ERC721 sell order. /// @param signature The order signature. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC721OrderCallback` on `msg.sender` after /// the ERC721 asset has been transferred to `msg.sender` /// but before transferring the ERC20 tokens to the seller. /// Native tokens acquired during the callback can be used /// to fill the order. function buyERC721( LibNFTOrder.ERC721Order memory sellOrder, LibSignature.Signature memory signature, bytes memory callbackData ) public override payable { uint256 ethBalanceBefore = address(this).balance .safeSub(msg.value); _buyERC721( sellOrder, signature, msg.value, callbackData ); uint256 ethBalanceAfter = address(this).balance; // Cannot use pre-existing ETH balance if (ethBalanceAfter < ethBalanceBefore) { LibNFTOrdersRichErrors.OverspentEthError( msg.value + (ethBalanceBefore - ethBalanceAfter), msg.value ).rrevert(); } // Refund _transferEth(msg.sender, ethBalanceAfter - ethBalanceBefore); } /// @dev Cancel a single ERC721 order by its nonce. The caller /// should be the maker of the order. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonce The order nonce. function cancelERC721Order(uint256 orderNonce) public override { // Mark order as cancelled _setOrderStatusBit(msg.sender, orderNonce); emit ERC721OrderCancelled(msg.sender, orderNonce); } /// @dev Cancel multiple ERC721 orders by their nonces. The caller /// should be the maker of the orders. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonces The order nonces. function batchCancelERC721Orders(uint256[] calldata orderNonces) external override { for (uint256 i = 0; i < orderNonces.length; i++) { cancelERC721Order(orderNonces[i]); } } /// @dev Buys multiple ERC721 assets by filling the /// given orders. /// @param sellOrders The ERC721 sell orders. /// @param signatures The order signatures. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @param callbackData The data (if any) to pass to the taker /// callback for each order. Refer to the `callbackData` /// parameter to for `buyERC721`. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuyERC721s( LibNFTOrder.ERC721Order[] memory sellOrders, LibSignature.Signature[] memory signatures, bytes[] memory callbackData, bool revertIfIncomplete ) public override payable returns (bool[] memory successes) { require( sellOrders.length == signatures.length && sellOrders.length == callbackData.length, "ERC721OrdersFeature::batchBuyERC721s/ARRAY_LENGTH_MISMATCH" ); successes = new bool[](sellOrders.length); uint256 ethBalanceBefore = address(this).balance .safeSub(msg.value); if (revertIfIncomplete) { for (uint256 i = 0; i < sellOrders.length; i++) { // Will revert if _buyERC721 reverts. _buyERC721( sellOrders[i], signatures[i], address(this).balance.safeSub(ethBalanceBefore), callbackData[i] ); successes[i] = true; } } else { for (uint256 i = 0; i < sellOrders.length; i++) { // Delegatecall `_buyERC721` to swallow reverts while // preserving execution context. // Note that `_buyERC721` is a public function but should _not_ // be registered in the Exchange Proxy. (successes[i], ) = _implementation.delegatecall( abi.encodeWithSelector( this._buyERC721.selector, sellOrders[i], signatures[i], address(this).balance.safeSub(ethBalanceBefore), // Remaining ETH available callbackData[i] ) ); } } // Cannot use pre-existing ETH balance uint256 ethBalanceAfter = address(this).balance; if (ethBalanceAfter < ethBalanceBefore) { LibNFTOrdersRichErrors.OverspentEthError( msg.value + (ethBalanceBefore - ethBalanceAfter), msg.value ).rrevert(); } // Refund _transferEth(msg.sender, ethBalanceAfter - ethBalanceBefore); } /// @dev Matches a pair of complementary orders that have /// a non-negative spread. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrder Order selling an ERC721 asset. /// @param buyOrder Order buying an ERC721 asset. /// @param sellOrderSignature Signature for the sell order. /// @param buyOrderSignature Signature for the buy order. /// @return profit The amount of profit earned by the caller /// of this function (denominated in the ERC20 token /// of the matched orders). function matchERC721Orders( LibNFTOrder.ERC721Order memory sellOrder, LibNFTOrder.ERC721Order memory buyOrder, LibSignature.Signature memory sellOrderSignature, LibSignature.Signature memory buyOrderSignature ) public override returns (uint256 profit) { // The ERC721 tokens must match if (sellOrder.erc721Token != buyOrder.erc721Token) { LibNFTOrdersRichErrors.ERC721TokenMismatchError( address(sellOrder.erc721Token), address(buyOrder.erc721Token) ).rrevert(); } LibNFTOrder.NFTOrder memory sellNFTOrder = sellOrder.asNFTOrder(); LibNFTOrder.NFTOrder memory buyNFTOrder = buyOrder.asNFTOrder(); { LibNFTOrder.OrderInfo memory sellOrderInfo = _getOrderInfo(sellNFTOrder); LibNFTOrder.OrderInfo memory buyOrderInfo = _getOrderInfo(buyNFTOrder); _validateSellOrder( sellNFTOrder, sellOrderSignature, sellOrderInfo, buyOrder.maker ); _validateBuyOrder( buyNFTOrder, buyOrderSignature, buyOrderInfo, sellOrder.maker, sellOrder.erc721TokenId ); // Mark both orders as filled. _updateOrderState(sellNFTOrder, sellOrderInfo.orderHash, 1); _updateOrderState(buyNFTOrder, buyOrderInfo.orderHash, 1); } // The buyer must be willing to pay at least the amount that the // seller is asking. if (buyOrder.erc20TokenAmount < sellOrder.erc20TokenAmount) { LibNFTOrdersRichErrors.NegativeSpreadError( sellOrder.erc20TokenAmount, buyOrder.erc20TokenAmount ).rrevert(); } // The difference in ERC20 token amounts is the spread. uint256 spread = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount; // Transfer the ERC721 asset from seller to buyer. _transferERC721AssetFrom( sellOrder.erc721Token, sellOrder.maker, buyOrder.maker, sellOrder.erc721TokenId ); // Handle the ERC20 side of the order: if ( address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS && buyOrder.erc20Token == WETH ) { // The sell order specifies ETH, while the buy order specifies WETH. // The orders are still compatible with one another, but we'll have // to unwrap the WETH on behalf of the buyer. // Step 1: Transfer WETH from the buyer to the EP. // Note that we transfer `buyOrder.erc20TokenAmount`, which // is the amount the buyer signaled they are willing to pay // for the ERC721 asset, which may be more than the seller's // ask. _transferERC20TokensFrom( WETH, buyOrder.maker, address(this), buyOrder.erc20TokenAmount ); // Step 2: Unwrap the WETH into ETH. We unwrap the entire // `buyOrder.erc20TokenAmount`. // The ETH will be used for three purposes: // - To pay the seller // - To pay fees for the sell order // - Any remaining ETH will be sent to // `msg.sender` as profit. WETH.withdraw(buyOrder.erc20TokenAmount); // Step 3: Pay the seller (in ETH). _transferEth(payable(sellOrder.maker), sellOrder.erc20TokenAmount); // Step 4: Pay fees for the buy order. Note that these are paid // in _WETH_ by the _buyer_. By signing the buy order, the // buyer signals that they are willing to spend a total // of `erc20TokenAmount` _plus_ fees, all denominated in // the `erc20Token`, which in this case is WETH. _payFees( buyNFTOrder, buyOrder.maker, // payer 1, // fillAmount 1, // orderAmount false // useNativeToken ); // Step 5: Pay fees for the sell order. The `erc20Token` of the // sell order is ETH, so the fees are paid out in ETH. // There should be `spread` wei of ETH remaining in the // EP at this point, which we will use ETH to pay the // sell order fees. uint256 sellOrderFees = _payFees( sellNFTOrder, address(this), // payer 1, // fillAmount 1, // orderAmount true // useNativeToken ); // Step 6: The spread must be enough to cover the sell order fees. // If not, either `_payFees` will have reverted, or we // have spent ETH that was in the EP before this // `matchERC721Orders` call, which we disallow. if (spread < sellOrderFees) { LibNFTOrdersRichErrors.SellOrderFeesExceedSpreadError( sellOrderFees, spread ).rrevert(); } // Step 7: The spread less the sell order fees is the amount of ETH // remaining in the EP that can be sent to `msg.sender` as // the profit from matching these two orders. profit = spread - sellOrderFees; if (profit > 0) { _transferEth(msg.sender, profit); } } else { // ERC20 tokens must match if (sellOrder.erc20Token != buyOrder.erc20Token) { LibNFTOrdersRichErrors.ERC20TokenMismatchError( address(sellOrder.erc20Token), address(buyOrder.erc20Token) ).rrevert(); } // Step 1: Transfer the ERC20 token from the buyer to the seller. // Note that we transfer `sellOrder.erc20TokenAmount`, which // is at most `buyOrder.erc20TokenAmount`. _transferERC20TokensFrom( buyOrder.erc20Token, buyOrder.maker, sellOrder.maker, sellOrder.erc20TokenAmount ); // Step 2: Pay fees for the buy order. Note that these are paid // by the buyer. By signing the buy order, the buyer signals // that they are willing to spend a total of // `buyOrder.erc20TokenAmount` _plus_ `buyOrder.fees`. _payFees( buyNFTOrder, buyOrder.maker, // payer 1, // fillAmount 1, // orderAmount false // useNativeToken ); // Step 3: Pay fees for the sell order. These are paid by the buyer // as well. After paying these fees, we may have taken more // from the buyer than they agreed to in the buy order. If // so, we revert in the following step. uint256 sellOrderFees = _payFees( sellNFTOrder, buyOrder.maker, // payer 1, // fillAmount 1, // orderAmount false // useNativeToken ); // Step 4: The spread must be enough to cover the sell order fees. // If not, `_payFees` will have taken more tokens from the // buyer than they had agreed to in the buy order, in which // case we revert here. if (spread < sellOrderFees) { LibNFTOrdersRichErrors.SellOrderFeesExceedSpreadError( sellOrderFees, spread ).rrevert(); } // Step 5: We calculate the profit as: // profit = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount - sellOrderFees // = spread - sellOrderFees // I.e. the buyer would've been willing to pay up to `profit` // more to buy the asset, so instead that amount is sent to // `msg.sender` as the profit from matching these two orders. profit = spread - sellOrderFees; if (profit > 0) { _transferERC20TokensFrom( buyOrder.erc20Token, buyOrder.maker, msg.sender, profit ); } } emit ERC721OrderFilled( sellOrder.direction, sellOrder.maker, buyOrder.maker, // taker sellOrder.nonce, sellOrder.erc20Token, sellOrder.erc20TokenAmount, sellOrder.erc721Token, sellOrder.erc721TokenId, msg.sender ); emit ERC721OrderFilled( buyOrder.direction, buyOrder.maker, sellOrder.maker, // taker buyOrder.nonce, buyOrder.erc20Token, buyOrder.erc20TokenAmount, buyOrder.erc721Token, sellOrder.erc721TokenId, msg.sender ); } /// @dev Matches pairs of complementary orders that have /// non-negative spreads. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrders Orders selling ERC721 assets. /// @param buyOrders Orders buying ERC721 assets. /// @param sellOrderSignatures Signatures for the sell orders. /// @param buyOrderSignatures Signatures for the buy orders. /// @return profits The amount of profit earned by the caller /// of this function for each pair of matched orders /// (denominated in the ERC20 token of the order pair). /// @return successes An array of booleans corresponding to /// whether each pair of orders was successfully matched. function batchMatchERC721Orders( LibNFTOrder.ERC721Order[] memory sellOrders, LibNFTOrder.ERC721Order[] memory buyOrders, LibSignature.Signature[] memory sellOrderSignatures, LibSignature.Signature[] memory buyOrderSignatures ) public override returns (uint256[] memory profits, bool[] memory successes) { require( sellOrders.length == buyOrders.length && sellOrderSignatures.length == buyOrderSignatures.length && sellOrders.length == sellOrderSignatures.length, "ERC721OrdersFeature::batchMatchERC721Orders/ARRAY_LENGTH_MISMATCH" ); profits = new uint256[](sellOrders.length); successes = new bool[](sellOrders.length); for (uint256 i = 0; i < sellOrders.length; i++) { bytes memory returnData; // Delegatecall `matchERC721Orders` to catch reverts while // preserving execution context. (successes[i], returnData) = _implementation.delegatecall( abi.encodeWithSelector( this.matchERC721Orders.selector, sellOrders[i], buyOrders[i], sellOrderSignatures[i], buyOrderSignatures[i] ) ); if (successes[i]) { // If the matching succeeded, record the profit. (uint256 profit) = abi.decode(returnData, (uint256)); profits[i] = profit; } } } /// @dev Callback for the ERC721 `safeTransferFrom` function. /// This callback can be used to sell an ERC721 asset if /// a valid ERC721 order, signature and `unwrapNativeToken` /// are encoded in `data`. This allows takers to sell their /// ERC721 asset without first calling `setApprovalForAll`. /// @param operator The address which called `safeTransferFrom`. /// @param tokenId The ID of the asset being transferred. /// @param data Additional data with no specified format. If a /// valid ERC721 order, signature and `unwrapNativeToken` /// are encoded in `data`, this function will try to fill /// the order using the received asset. /// @return success The selector of this function (0x150b7a02), /// indicating that the callback succeeded. function onERC721Received( address operator, address /* from */, uint256 tokenId, bytes calldata data ) external override returns (bytes4 success) { // Decode the order, signature, and `unwrapNativeToken` from // `data`. If `data` does not encode such parameters, this // will throw. ( LibNFTOrder.ERC721Order memory buyOrder, LibSignature.Signature memory signature, bool unwrapNativeToken ) = abi.decode( data, (LibNFTOrder.ERC721Order, LibSignature.Signature, bool) ); // `onERC721Received` is called by the ERC721 token contract. // Check that it matches the ERC721 token in the order. if (msg.sender != address(buyOrder.erc721Token)) { LibNFTOrdersRichErrors.ERC721TokenMismatchError( msg.sender, address(buyOrder.erc721Token) ).rrevert(); } _sellERC721( buyOrder, signature, tokenId, unwrapNativeToken, operator, // taker address(this), // owner (we hold the NFT currently) new bytes(0) // No taker callback ); return ERC721_RECEIVED_MAGIC_BYTES; } /// @dev Approves an ERC721 order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC721 order. function preSignERC721Order(LibNFTOrder.ERC721Order memory order) public override { require( order.maker == msg.sender, "ERC721OrdersFeature::preSignERC721Order/ONLY_MAKER" ); bytes32 orderHash = getERC721OrderHash(order); LibERC721OrdersStorage.getStorage().preSigned[orderHash] = true; emit ERC721OrderPreSigned( order.direction, order.maker, order.taker, order.expiry, order.nonce, order.erc20Token, order.erc20TokenAmount, order.fees, order.erc721Token, order.erc721TokenId, order.erc721TokenProperties ); } // Core settlement logic for selling an ERC721 asset. // Used by `sellERC721` and `onERC721Received`. function _sellERC721( LibNFTOrder.ERC721Order memory buyOrder, LibSignature.Signature memory signature, uint256 erc721TokenId, bool unwrapNativeToken, address taker, address currentNftOwner, bytes memory takerCallbackData ) private { _sellNFT( buyOrder.asNFTOrder(), signature, SellParams( 1, // sell amount erc721TokenId, unwrapNativeToken, taker, currentNftOwner, takerCallbackData ) ); emit ERC721OrderFilled( buyOrder.direction, buyOrder.maker, taker, buyOrder.nonce, buyOrder.erc20Token, buyOrder.erc20TokenAmount, buyOrder.erc721Token, erc721TokenId, address(0) ); } // Core settlement logic for buying an ERC721 asset. // Used by `buyERC721` and `batchBuyERC721s`. function _buyERC721( LibNFTOrder.ERC721Order memory sellOrder, LibSignature.Signature memory signature, uint256 ethAvailable, bytes memory takerCallbackData ) public payable { _buyNFT( sellOrder.asNFTOrder(), signature, BuyParams( 1, // buy amount ethAvailable, takerCallbackData ) ); emit ERC721OrderFilled( sellOrder.direction, sellOrder.maker, msg.sender, sellOrder.nonce, sellOrder.erc20Token, sellOrder.erc20TokenAmount, sellOrder.erc721Token, sellOrder.erc721TokenId, address(0) ); } /// @dev Checks whether the given signature is valid for the /// the given ERC721 order. Reverts if not. /// @param order The ERC721 order. /// @param signature The signature to validate. function validateERC721OrderSignature( LibNFTOrder.ERC721Order memory order, LibSignature.Signature memory signature ) public override view { bytes32 orderHash = getERC721OrderHash(order); _validateOrderSignature(orderHash, signature, order.maker); } /// @dev Validates that the given signature is valid for the /// given maker and order hash. Reverts if the signature /// is not valid. /// @param orderHash The hash of the order that was signed. /// @param signature The signature to check. /// @param maker The maker of the order. function _validateOrderSignature( bytes32 orderHash, LibSignature.Signature memory signature, address maker ) internal override view { if (signature.signatureType == LibSignature.SignatureType.PRESIGNED) { // Check if order hash has been pre-signed by the maker. bool isPreSigned = LibERC721OrdersStorage.getStorage().preSigned[orderHash]; if (!isPreSigned) { LibNFTOrdersRichErrors.InvalidSignerError(maker, address(0)).rrevert(); } } else { address signer = LibSignature.getSignerOfHash(orderHash, signature); if (signer != maker) { LibNFTOrdersRichErrors.InvalidSignerError(maker, signer).rrevert(); } } } /// @dev Transfers an NFT asset. /// @param token The address of the NFT contract. /// @param from The address currently holding the asset. /// @param to The address to transfer the asset to. /// @param tokenId The ID of the asset to transfer. /// @param amount The amount of the asset to transfer. Always /// 1 for ERC721 assets. function _transferNFTAssetFrom( address token, address from, address to, uint256 tokenId, uint256 amount ) internal override { assert(amount == 1); _transferERC721AssetFrom(IERC721Token(token), from, to, tokenId); } /// @dev Updates storage to indicate that the given order /// has been filled by the given amount. /// @param order The order that has been filled. /// @param fillAmount The amount (denominated in the NFT asset) /// that the order has been filled by. function _updateOrderState( LibNFTOrder.NFTOrder memory order, bytes32 /* orderHash */, uint128 fillAmount ) internal override { assert(fillAmount == 1); _setOrderStatusBit(order.maker, order.nonce); } function _setOrderStatusBit(address maker, uint256 nonce) private { // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (nonce & 255); // Update order status bit vector to indicate that the given order // has been cancelled/filled by setting the designated bit to 1. LibERC721OrdersStorage.getStorage().orderStatusByMaker [maker][uint248(nonce >> 8)] |= flag; } /// @dev If the given order is buying an ERC721 asset, checks /// whether or not the given token ID satisfies the required /// properties specified in the order. If the order does not /// specify any properties, this function instead checks /// whether the given token ID matches the ID in the order. /// Reverts if any checks fail, or if the order is selling /// an ERC721 asset. /// @param order The ERC721 order. /// @param erc721TokenId The ID of the ERC721 asset. function validateERC721OrderProperties( LibNFTOrder.ERC721Order memory order, uint256 erc721TokenId ) public override view { _validateOrderProperties( order.asNFTOrder(), erc721TokenId ); } /// @dev Get the current status of an ERC721 order. /// @param order The ERC721 order. /// @return status The status of the order. function getERC721OrderStatus(LibNFTOrder.ERC721Order memory order) public override view returns (LibNFTOrder.OrderStatus status) { // Only buy orders with `erc721TokenId` == 0 can be property // orders. if (order.erc721TokenProperties.length > 0 && (order.direction != LibNFTOrder.TradeDirection.BUY_NFT || order.erc721TokenId != 0)) { return LibNFTOrder.OrderStatus.INVALID; } // Buy orders cannot use ETH as the ERC20 token, since ETH cannot be // transferred from the buyer by a contract. if (order.direction == LibNFTOrder.TradeDirection.BUY_NFT && address(order.erc20Token) == NATIVE_TOKEN_ADDRESS) { return LibNFTOrder.OrderStatus.INVALID; } // Check for expiry. if (order.expiry <= block.timestamp) { return LibNFTOrder.OrderStatus.EXPIRED; } // Check `orderStatusByMaker` state variable to see if the order // has been cancelled or previously filled. LibERC721OrdersStorage.Storage storage stor = LibERC721OrdersStorage.getStorage(); // `orderStatusByMaker` is indexed by maker and nonce. uint256 orderStatusBitVector = stor.orderStatusByMaker[order.maker][uint248(order.nonce >> 8)]; // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (order.nonce & 255); // If the designated bit is set, the order has been cancelled or // previously filled, so it is now unfillable. if (orderStatusBitVector & flag != 0) { return LibNFTOrder.OrderStatus.UNFILLABLE; } // Otherwise, the order is fillable. return LibNFTOrder.OrderStatus.FILLABLE; } /// @dev Get the order info for an NFT order. /// @param order The NFT order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTOrder memory order) internal override view returns (LibNFTOrder.OrderInfo memory orderInfo) { LibNFTOrder.ERC721Order memory erc721Order = order.asERC721Order(); orderInfo.orderHash = getERC721OrderHash(erc721Order); orderInfo.status = getERC721OrderStatus(erc721Order); orderInfo.orderAmount = 1; orderInfo.remainingAmount = orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE ? 1 : 0; } /// @dev Get the EIP-712 hash of an ERC721 order. /// @param order The ERC721 order. /// @return orderHash The order hash. function getERC721OrderHash(LibNFTOrder.ERC721Order memory order) public override view returns (bytes32 orderHash) { return _getEIP712Hash(LibNFTOrder.getERC721OrderStructHash(order)); } /// @dev Get the order status bit vector for the given /// maker address and nonce range. /// @param maker The maker of the order. /// @param nonceRange Order status bit vectors are indexed /// by maker address and the upper 248 bits of the /// order nonce. We define `nonceRange` to be these /// 248 bits. /// @return bitVector The order status bit vector for the /// given maker and nonce range. function getERC721OrderStatusBitVector(address maker, uint248 nonceRange) external override view returns (uint256 bitVector) { LibERC721OrdersStorage.Storage storage stor = LibERC721OrdersStorage.getStorage(); return stor.orderStatusByMaker[maker][nonceRange]; } }
Get the EIP-712 hash of an ERC721 order. order The ERC721 order. return orderHash The order hash.
function getERC721OrderHash(LibNFTOrder.ERC721Order memory order) public override view returns (bytes32 orderHash) { return _getEIP712Hash(LibNFTOrder.getERC721OrderStructHash(order)); }
6,437,493
pragma solidity ^0.5.10; // File: openzeppelin-solidity/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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: openzeppelin-solidity/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. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/utils/Address.sol /** * @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. * * > 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. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.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 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); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: openzeppelin-solidity/contracts/utils/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 aplied 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. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File: openzeppelin-solidity/contracts/introspection/ERC165Checker.sol /** * @dev Library used to query support of an interface declared via `IERC165`. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the `IERC165` interface, */ function _supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for `IERC165` itself is queried automatically. * * See `IERC165.supportsInterface`. */ function _supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return _supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for `IERC165` itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * `IERC165` support. * * See `IERC165.supportsInterface`. */ function _supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!_supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with the `supportsERC165` method in this library. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool success, bool result) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); // solhint-disable-next-line no-inline-assembly assembly { let encodedParams_data := add(0x20, encodedParams) let encodedParams_size := mload(encodedParams) let output := mload(0x40) // Find empty storage location using "free memory pointer" mstore(output, 0x0) success := staticcall( 30000, // 30k gas account, // To addr encodedParams_data, encodedParams_size, output, 0x20 // Outputs are 32 bytes long ) result := mload(output) // Load the result } } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * [EIP](https://eips.ethereum.org/EIPS/eip-165). * * 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 * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * 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/introspection/ERC165.sol /** * @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: erc-payable-token/contracts/token/ERC1363/IERC1363.sol /** * @title IERC1363 Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for a Payable Token contract as defined in * https://github.com/ethereum/EIPs/issues/1363 */ contract IERC1363 is IERC20, ERC165 { /* * Note: the ERC-165 identifier for this interface is 0x4bbee2df. * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ /* * Note: the ERC-165 identifier for this interface is 0xfb9ec8ce. * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferAndCall(address to, uint256 value) public returns (bool); /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferAndCall(address to, uint256 value, bytes memory data) public returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @return true unless throwing */ function transferFromAndCall(address from, address to, uint256 value) public returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferFromAndCall(address from, address to, uint256 value, bytes memory data) public returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent */ function approveAndCall(address spender, uint256 value) public returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function approveAndCall(address spender, uint256 value, bytes memory data) public returns (bool); } // File: erc-payable-token/contracts/token/ERC1363/IERC1363Receiver.sol /** * @title IERC1363Receiver Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for any contract that wants to support transferAndCall or transferFromAndCall * from ERC1363 token contracts as defined in * https://github.com/ethereum/EIPs/issues/1363 */ contract IERC1363Receiver { /* * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) */ /** * @notice Handle the receipt of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after a `transfer` or a `transferFrom`. 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 token contract address is always the message sender. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` * unless throwing */ function onTransferReceived(address operator, address from, uint256 value, bytes memory data) public returns (bytes4); // solhint-disable-line max-line-length } // File: erc-payable-token/contracts/token/ERC1363/IERC1363Spender.sol /** * @title IERC1363Spender Interface * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Interface for any contract that wants to support approveAndCall * from ERC1363 token contracts as defined in * https://github.com/ethereum/EIPs/issues/1363 */ contract IERC1363Spender { /* * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) */ /** * @notice Handle the approval of ERC1363 tokens * @dev Any ERC1363 smart contract calls this function on the recipient * after an `approve`. This function MAY throw to revert and reject the * approval. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * @param owner address The address which called `approveAndCall` function * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` * unless throwing */ function onApprovalReceived(address owner, uint256 value, bytes memory data) public returns (bytes4); } // File: erc-payable-token/contracts/payment/ERC1363Payable.sol /** * @title ERC1363Payable * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Implementation proposal of a contract that wants to accept ERC1363 payments */ contract ERC1363Payable is IERC1363Receiver, IERC1363Spender, ERC165 { using ERC165Checker for address; /** * @dev Magic value to be returned upon successful reception of ERC1363 tokens * Equals to `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`, * which can be also obtained as `IERC1363Receiver(0).onTransferReceived.selector` */ bytes4 internal constant _INTERFACE_ID_ERC1363_RECEIVER = 0x88a7ca5c; /** * @dev Magic value to be returned upon successful approval of ERC1363 tokens. * Equals to `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`, * which can be also obtained as `IERC1363Spender(0).onApprovalReceived.selector` */ bytes4 internal constant _INTERFACE_ID_ERC1363_SPENDER = 0x7b04a2d0; /* * Note: the ERC-165 identifier for the ERC1363 token transfer * 0x4bbee2df === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) */ bytes4 private constant _INTERFACE_ID_ERC1363_TRANSFER = 0x4bbee2df; /* * Note: the ERC-165 identifier for the ERC1363 token approval * 0xfb9ec8ce === * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ bytes4 private constant _INTERFACE_ID_ERC1363_APPROVE = 0xfb9ec8ce; event TokensReceived( address indexed operator, address indexed from, uint256 value, bytes data ); event TokensApproved( address indexed owner, uint256 value, bytes data ); // The ERC1363 token accepted IERC1363 private _acceptedToken; /** * @param acceptedToken Address of the token being accepted */ constructor(IERC1363 acceptedToken) public { require(address(acceptedToken) != address(0)); require( acceptedToken.supportsInterface(_INTERFACE_ID_ERC1363_TRANSFER) && acceptedToken.supportsInterface(_INTERFACE_ID_ERC1363_APPROVE) ); _acceptedToken = acceptedToken; // register the supported interface to conform to IERC1363Receiver and IERC1363Spender via ERC165 _registerInterface(_INTERFACE_ID_ERC1363_RECEIVER); _registerInterface(_INTERFACE_ID_ERC1363_SPENDER); } /* * @dev Note: remember that the token contract address is always the message sender. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format */ function onTransferReceived(address operator, address from, uint256 value, bytes memory data) public returns (bytes4) { // solhint-disable-line max-line-length require(msg.sender == address(_acceptedToken)); emit TokensReceived(operator, from, value, data); _transferReceived(operator, from, value, data); return _INTERFACE_ID_ERC1363_RECEIVER; } /* * @dev Note: remember that the token contract address is always the message sender. * @param owner address The address which called `approveAndCall` function * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format */ function onApprovalReceived(address owner, uint256 value, bytes memory data) public returns (bytes4) { require(msg.sender == address(_acceptedToken)); emit TokensApproved(owner, value, data); _approvalReceived(owner, value, data); return _INTERFACE_ID_ERC1363_SPENDER; } /** * @dev The ERC1363 token accepted */ function acceptedToken() public view returns (IERC1363) { return _acceptedToken; } /** * @dev Called after validating a `onTransferReceived`. Override this method to * make your stuffs within your contract. * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format */ function _transferReceived(address operator, address from, uint256 value, bytes memory data) internal { // solhint-disable-previous-line no-empty-blocks // optional override } /** * @dev Called after validating a `onApprovalReceived`. Override this method to * make your stuffs within your contract. * @param owner address The address which called `approveAndCall` function * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format */ function _approvalReceived(address owner, uint256 value, bytes memory data) internal { // solhint-disable-previous-line no-empty-blocks // optional override } } // File: openzeppelin-solidity/contracts/ownership/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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { 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 = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/access/Roles.sol /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: dao-smartcontracts/contracts/access/roles/DAORoles.sol /** * @title DAORoles * @author Vittorio Minacori (https://github.com/vittominacori) * @dev It identifies the DAO roles */ contract DAORoles is Ownable { using Roles for Roles.Role; event OperatorAdded(address indexed account); event OperatorRemoved(address indexed account); event DappAdded(address indexed account); event DappRemoved(address indexed account); Roles.Role private _operators; Roles.Role private _dapps; constructor () internal {} // solhint-disable-line no-empty-blocks modifier onlyOperator() { require(isOperator(msg.sender)); _; } modifier onlyDapp() { require(isDapp(msg.sender)); _; } /** * @dev Check if an address has the `operator` role * @param account Address you want to check */ function isOperator(address account) public view returns (bool) { return _operators.has(account); } /** * @dev Check if an address has the `dapp` role * @param account Address you want to check */ function isDapp(address account) public view returns (bool) { return _dapps.has(account); } /** * @dev Add the `operator` role from address * @param account Address you want to add role */ function addOperator(address account) public onlyOwner { _addOperator(account); } /** * @dev Add the `dapp` role from address * @param account Address you want to add role */ function addDapp(address account) public onlyOperator { _addDapp(account); } /** * @dev Remove the `operator` role from address * @param account Address you want to remove role */ function removeOperator(address account) public onlyOwner { _removeOperator(account); } /** * @dev Remove the `operator` role from address * @param account Address you want to remove role */ function removeDapp(address account) public onlyOperator { _removeDapp(account); } function _addOperator(address account) internal { _operators.add(account); emit OperatorAdded(account); } function _addDapp(address account) internal { _dapps.add(account); emit DappAdded(account); } function _removeOperator(address account) internal { _operators.remove(account); emit OperatorRemoved(account); } function _removeDapp(address account) internal { _dapps.remove(account); emit DappRemoved(account); } } // File: dao-smartcontracts/contracts/dao/Organization.sol /** * @title Organization * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Library for managing organization */ library Organization { using SafeMath for uint256; // structure defining a member struct Member { uint256 id; address account; bytes9 fingerprint; uint256 creationDate; uint256 stakedTokens; uint256 usedTokens; bytes32 data; bool approved; } // structure defining members status struct Members { uint256 count; uint256 totalStakedTokens; uint256 totalUsedTokens; mapping(address => uint256) addressMap; mapping(uint256 => Member) list; } /** * @dev Returns if an address is member or not * @param members Current members struct * @param account Address of the member you are looking for * @return bool */ function isMember(Members storage members, address account) internal view returns (bool) { return members.addressMap[account] != 0; } /** * @dev Get creation date of a member * @param members Current members struct * @param account Address you want to check * @return uint256 Member creation date, zero otherwise */ function creationDateOf(Members storage members, address account) internal view returns (uint256) { Member storage member = members.list[members.addressMap[account]]; return member.creationDate; } /** * @dev Check how many tokens staked for given address * @param members Current members struct * @param account Address you want to check * @return uint256 Member staked tokens */ function stakedTokensOf(Members storage members, address account) internal view returns (uint256) { Member storage member = members.list[members.addressMap[account]]; return member.stakedTokens; } /** * @dev Check how many tokens used for given address * @param members Current members struct * @param account Address you want to check * @return uint256 Member used tokens */ function usedTokensOf(Members storage members, address account) internal view returns (uint256) { Member storage member = members.list[members.addressMap[account]]; return member.usedTokens; } /** * @dev Check if an address has been approved * @param members Current members struct * @param account Address you want to check * @return bool */ function isApproved(Members storage members, address account) internal view returns (bool) { Member storage member = members.list[members.addressMap[account]]; return member.approved; } /** * @dev Returns the member structure * @param members Current members struct * @param memberId Id of the member you are looking for * @return Member */ function getMember(Members storage members, uint256 memberId) internal view returns (Member storage) { Member storage structure = members.list[memberId]; require(structure.account != address(0)); return structure; } /** * @dev Generate a new member and the member structure * @param members Current members struct * @param account Address you want to make member * @return uint256 The new member id */ function addMember(Members storage members, address account) internal returns (uint256) { require(account != address(0)); require(!isMember(members, account)); uint256 memberId = members.count.add(1); bytes9 fingerprint = getFingerprint(account, memberId); members.addressMap[account] = memberId; members.list[memberId] = Member( memberId, account, fingerprint, block.timestamp, // solhint-disable-line not-rely-on-time 0, 0, "", false ); members.count = memberId; return memberId; } /** * @dev Add tokens to member stack * @param members Current members struct * @param account Address you want to stake tokens * @param amount Number of tokens to stake */ function stake(Members storage members, address account, uint256 amount) internal { require(isMember(members, account)); Member storage member = members.list[members.addressMap[account]]; member.stakedTokens = member.stakedTokens.add(amount); members.totalStakedTokens = members.totalStakedTokens.add(amount); } /** * @dev Remove tokens from member stack * @param members Current members struct * @param account Address you want to unstake tokens * @param amount Number of tokens to unstake */ function unstake(Members storage members, address account, uint256 amount) internal { require(isMember(members, account)); Member storage member = members.list[members.addressMap[account]]; require(member.stakedTokens >= amount); member.stakedTokens = member.stakedTokens.sub(amount); members.totalStakedTokens = members.totalStakedTokens.sub(amount); } /** * @dev Use tokens from member stack * @param members Current members struct * @param account Address you want to use tokens * @param amount Number of tokens to use */ function use(Members storage members, address account, uint256 amount) internal { require(isMember(members, account)); Member storage member = members.list[members.addressMap[account]]; require(member.stakedTokens >= amount); member.stakedTokens = member.stakedTokens.sub(amount); members.totalStakedTokens = members.totalStakedTokens.sub(amount); member.usedTokens = member.usedTokens.add(amount); members.totalUsedTokens = members.totalUsedTokens.add(amount); } /** * @dev Set the approved status for a member * @param members Current members struct * @param account Address you want to update * @param status Bool the new status for approved */ function setApproved(Members storage members, address account, bool status) internal { require(isMember(members, account)); Member storage member = members.list[members.addressMap[account]]; member.approved = status; } /** * @dev Set data for a member * @param members Current members struct * @param account Address you want to update * @param data bytes32 updated data */ function setData(Members storage members, address account, bytes32 data) internal { require(isMember(members, account)); Member storage member = members.list[members.addressMap[account]]; member.data = data; } /** * @dev Generate a member fingerprint * @param account Address you want to make member * @param memberId The member id * @return bytes9 It represents member fingerprint */ function getFingerprint(address account, uint256 memberId) private pure returns (bytes9) { return bytes9(keccak256(abi.encodePacked(account, memberId))); } } // File: dao-smartcontracts/contracts/dao/DAO.sol /** * @title DAO * @author Vittorio Minacori (https://github.com/vittominacori) * @dev It identifies the DAO and Organization logic */ contract DAO is ERC1363Payable, DAORoles { using SafeMath for uint256; using Organization for Organization.Members; using Organization for Organization.Member; event MemberAdded( address indexed account, uint256 id ); event MemberStatusChanged( address indexed account, bool approved ); event TokensStaked( address indexed account, uint256 value ); event TokensUnstaked( address indexed account, uint256 value ); event TokensUsed( address indexed account, address indexed dapp, uint256 value ); Organization.Members private _members; constructor (IERC1363 acceptedToken) public ERC1363Payable(acceptedToken) {} // solhint-disable-line no-empty-blocks /** * @dev fallback. This function will create a new member */ function () external payable { // solhint-disable-line no-complex-fallback require(msg.value == 0); _newMember(msg.sender); } /** * @dev Generate a new member and the member structure */ function join() external { _newMember(msg.sender); } /** * @dev Generate a new member and the member structure * @param account Address you want to make member */ function newMember(address account) external onlyOperator { _newMember(account); } /** * @dev Set the approved status for a member * @param account Address you want to update * @param status Bool the new status for approved */ function setApproved(address account, bool status) external onlyOperator { _members.setApproved(account, status); emit MemberStatusChanged(account, status); } /** * @dev Set data for a member * @param account Address you want to update * @param data bytes32 updated data */ function setData(address account, bytes32 data) external onlyOperator { _members.setData(account, data); } /** * @dev Use tokens from a specific account * @param account Address to use the tokens from * @param amount Number of tokens to use */ function use(address account, uint256 amount) external onlyDapp { _members.use(account, amount); IERC20(acceptedToken()).transfer(msg.sender, amount); emit TokensUsed(account, msg.sender, amount); } /** * @dev Remove tokens from member stack * @param amount Number of tokens to unstake */ function unstake(uint256 amount) public { _members.unstake(msg.sender, amount); IERC20(acceptedToken()).transfer(msg.sender, amount); emit TokensUnstaked(msg.sender, amount); } /** * @dev Returns the members number * @return uint256 */ function membersNumber() public view returns (uint256) { return _members.count; } /** * @dev Returns the total staked tokens number * @return uint256 */ function totalStakedTokens() public view returns (uint256) { return _members.totalStakedTokens; } /** * @dev Returns the total used tokens number * @return uint256 */ function totalUsedTokens() public view returns (uint256) { return _members.totalUsedTokens; } /** * @dev Returns if an address is member or not * @param account Address of the member you are looking for * @return bool */ function isMember(address account) public view returns (bool) { return _members.isMember(account); } /** * @dev Get creation date of a member * @param account Address you want to check * @return uint256 Member creation date, zero otherwise */ function creationDateOf(address account) public view returns (uint256) { return _members.creationDateOf(account); } /** * @dev Check how many tokens staked for given address * @param account Address you want to check * @return uint256 Member staked tokens */ function stakedTokensOf(address account) public view returns (uint256) { return _members.stakedTokensOf(account); } /** * @dev Check how many tokens used for given address * @param account Address you want to check * @return uint256 Member used tokens */ function usedTokensOf(address account) public view returns (uint256) { return _members.usedTokensOf(account); } /** * @dev Check if an address has been approved * @param account Address you want to check * @return bool */ function isApproved(address account) public view returns (bool) { return _members.isApproved(account); } /** * @dev Returns the member structure * @param memberAddress Address of the member you are looking for * @return array */ function getMemberByAddress(address memberAddress) public view returns ( uint256 id, address account, bytes9 fingerprint, uint256 creationDate, uint256 stakedTokens, uint256 usedTokens, bytes32 data, bool approved ) { return getMemberById(_members.addressMap[memberAddress]); } /** * @dev Returns the member structure * @param memberId Id of the member you are looking for * @return array */ function getMemberById(uint256 memberId) public view returns ( uint256 id, address account, bytes9 fingerprint, uint256 creationDate, uint256 stakedTokens, uint256 usedTokens, bytes32 data, bool approved ) { Organization.Member storage structure = _members.getMember(memberId); id = structure.id; account = structure.account; fingerprint = structure.fingerprint; creationDate = structure.creationDate; stakedTokens = structure.stakedTokens; usedTokens = structure.usedTokens; data = structure.data; approved = structure.approved; } /** * @dev Allow to recover tokens from contract * @param tokenAddress address The token contract address * @param tokenAmount uint256 Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { if (tokenAddress == address(acceptedToken())) { uint256 currentBalance = IERC20(acceptedToken()).balanceOf(address(this)); require(currentBalance.sub(_members.totalStakedTokens) >= tokenAmount); } IERC20(tokenAddress).transfer(owner(), tokenAmount); } /** * @dev Called after validating a `onTransferReceived` * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format */ function _transferReceived( address operator, // solhint-disable-line no-unused-vars address from, uint256 value, bytes memory data // solhint-disable-line no-unused-vars ) internal { _stake(from, value); } /** * @dev Called after validating a `onApprovalReceived` * @param owner address The address which called `approveAndCall` function * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format */ function _approvalReceived( address owner, uint256 value, bytes memory data // solhint-disable-line no-unused-vars ) internal { IERC20(acceptedToken()).transferFrom(owner, address(this), value); _stake(owner, value); } /** * @dev Generate a new member and the member structure * @param account Address you want to make member * @return uint256 The new member id */ function _newMember(address account) internal { uint256 memberId = _members.addMember(account); emit MemberAdded(account, memberId); } /** * @dev Add tokens to member stack * @param account Address you want to stake tokens * @param amount Number of tokens to stake */ function _stake(address account, uint256 amount) internal { if (!isMember(account)) { _newMember(account); } _members.stake(account, amount); emit TokensStaked(account, amount); } } // File: eth-token-recover/contracts/TokenRecover.sol /** * @title TokenRecover * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Allow to recover any ERC20 sent into the contract for error */ contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // File: contracts/access/roles/OperatorRole.sol contract OperatorRole { using Roles for Roles.Role; event OperatorAdded(address indexed account); event OperatorRemoved(address indexed account); Roles.Role private _operators; constructor() internal { _addOperator(msg.sender); } modifier onlyOperator() { require(isOperator(msg.sender)); _; } function isOperator(address account) public view returns (bool) { return _operators.has(account); } function addOperator(address account) public onlyOperator { _addOperator(account); } function renounceOperator() public { _removeOperator(msg.sender); } function _addOperator(address account) internal { _operators.add(account); emit OperatorAdded(account); } function _removeOperator(address account) internal { _operators.remove(account); emit OperatorRemoved(account); } } // File: contracts/utils/Contributions.sol /** * @title Contributions * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Utility contract where to save any information about Crowdsale contributions */ contract Contributions is OperatorRole, TokenRecover { using SafeMath for uint256; struct Contributor { uint256 weiAmount; uint256 tokenAmount; bool exists; } // the number of sold tokens uint256 private _totalSoldTokens; // the number of wei raised uint256 private _totalWeiRaised; // list of addresses who contributed in crowdsales address[] private _addresses; // map of contributors mapping(address => Contributor) private _contributors; constructor() public {} // solhint-disable-line no-empty-blocks /** * @return the number of sold tokens */ function totalSoldTokens() public view returns (uint256) { return _totalSoldTokens; } /** * @return the number of wei raised */ function totalWeiRaised() public view returns (uint256) { return _totalWeiRaised; } /** * @return address of a contributor by list index */ function getContributorAddress(uint256 index) public view returns (address) { return _addresses[index]; } /** * @dev return the contributions length * @return uint representing contributors number */ function getContributorsLength() public view returns (uint) { return _addresses.length; } /** * @dev get wei contribution for the given address * @param account Address has contributed * @return uint256 */ function weiContribution(address account) public view returns (uint256) { return _contributors[account].weiAmount; } /** * @dev get token balance for the given address * @param account Address has contributed * @return uint256 */ function tokenBalance(address account) public view returns (uint256) { return _contributors[account].tokenAmount; } /** * @dev check if a contributor exists * @param account The address to check * @return bool */ function contributorExists(address account) public view returns (bool) { return _contributors[account].exists; } /** * @dev add contribution into the contributions array * @param account Address being contributing * @param weiAmount Amount of wei contributed * @param tokenAmount Amount of token received */ function addBalance(address account, uint256 weiAmount, uint256 tokenAmount) public onlyOperator { if (!_contributors[account].exists) { _addresses.push(account); _contributors[account].exists = true; } _contributors[account].weiAmount = _contributors[account].weiAmount.add(weiAmount); _contributors[account].tokenAmount = _contributors[account].tokenAmount.add(tokenAmount); _totalWeiRaised = _totalWeiRaised.add(weiAmount); _totalSoldTokens = _totalSoldTokens.add(tokenAmount); } /** * @dev remove the `operator` role from address * @param account Address you want to remove role */ function removeOperator(address account) public onlyOwner { _removeOperator(account); } } // File: contracts/dealer/TokenDealer.sol /** * @title TokenDealer * @author Vittorio Minacori (https://github.com/vittominacori) * @dev TokenDealer is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. */ contract TokenDealer is ReentrancyGuard, TokenRecover { using SafeMath for uint256; using SafeERC20 for IERC20; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. uint256 private _rate; // Address where funds are collected address payable private _wallet; // The token being sold IERC20 private _token; // the DAO smart contract DAO private _dao; // reference to Contributions contract Contributions private _contributions; /** * Event for token purchase logging * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased(address indexed beneficiary, uint256 value, uint256 amount); /** * @param rate Number of token units a buyer gets per wei * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold * @param contributions Address of the contributions contract * @param dao DAO the decentralized organization address */ constructor( uint256 rate, address payable wallet, address token, address contributions, address payable dao ) public { require(rate > 0, "TokenDealer: rate is 0"); require(wallet != address(0), "TokenDealer: wallet is the zero address"); require(token != address(0), "TokenDealer: token is the zero address"); require(contributions != address(0), "TokenDealer: contributions is the zero address"); require(dao != address(0), "TokenDealer: dao is the zero address"); _rate = rate; _wallet = wallet; _token = IERC20(token); _contributions = Contributions(contributions); _dao = DAO(dao); } /** * @dev fallback function * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(); } /** * @dev low level token purchase * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. */ function buyTokens() public nonReentrant payable { address beneficiary = msg.sender; uint256 weiAmount = msg.value; require(weiAmount != 0, "TokenDealer: weiAmount is 0"); // calculate token amount to be sent uint256 tokenAmount = _getTokenAmount(beneficiary, weiAmount); _token.safeTransfer(beneficiary, tokenAmount); emit TokensPurchased(beneficiary, weiAmount, tokenAmount); _contributions.addBalance(beneficiary, weiAmount, tokenAmount); _wallet.transfer(weiAmount); } /** * @dev Function to update rate * @param newRate The rate is the conversion between wei and the smallest and indivisible token unit */ function setRate(uint256 newRate) public onlyOwner { require(newRate > 0, "TokenDealer: rate is 0"); _rate = newRate; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the crowdsale contributions contract address */ function contributions() public view returns (Contributions) { return _contributions; } /** * @return the crowdsale dao contract address */ function dao() public view returns (DAO) { return _dao; } /** * @dev Get expected token number for beneficiary. * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function expectedTokenAmount(address beneficiary, uint256 weiAmount) public view returns (uint256) { return _getTokenAmount(beneficiary, weiAmount); } /** * @dev The way in which ether is converted to tokens. * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(address beneficiary, uint256 weiAmount) internal view returns (uint256) { uint256 tokenAmount = weiAmount.mul(_rate); if (_dao.isMember(beneficiary)) { tokenAmount = tokenAmount.mul(2); if (_dao.stakedTokensOf(beneficiary) > 0) { tokenAmount = tokenAmount.mul(2); } if (_dao.usedTokensOf(beneficiary) > 0) { tokenAmount = tokenAmount.mul(2); } } return tokenAmount; } }
Function to update rate newRate The rate is the conversion between wei and the smallest and indivisible token unit/
function setRate(uint256 newRate) public onlyOwner { require(newRate > 0, "TokenDealer: rate is 0"); _rate = newRate; }
943,909
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** @dev This contract receives Bliss fees and is used to market sell that fee and buy WBTC with the ETH amount gained. * The wBTC bought is then sent into a staking contract */ contract BlissFeeHandler { address private _owner; constructor() public { _owner = msg.sender; } // Rescue any missent tokens to the contract function recoverERC20(address tokenAddress, uint256 tokenAmount) external { IERC20(tokenAddress).transfer(msg.sender, tokenAmount); } }
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); pragma solidity ^0.6.0; }
9,975,518
pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; contract Micronews is Ownable { using SafeMath for uint256; struct Channel { uint256 id; uint256 subscribers; bytes name; } uint256 CHANNEL_SUBSCRIPTION_FEE = 0.1 ether; uint256 CHANNEL_INITIATION_FEE = 0.2 ether; uint256 constant WEEK_IN_SECONDS = 86400 * 7; uint256 constant MAX_BOOKMARKS_PER_PERIOD = 5; mapping(uint256 => Channel) channels; mapping(uint256 => uint256) channelIdToTotalEquity; /* channelId => total tokens */ mapping(uint256 => mapping(address => uint256)) channelIdToUserEquity; /* channelId => user => tokens owned */ mapping(uint256 => mapping(uint256 => mapping(address => bool))) channelIdToUserSubscriptionStatus; /* feePeriodId => channelId => user => subscriptionStatusBool */ mapping(uint256 => mapping(address => uint256)) userBookmarksPerPeriod; mapping(uint256 => mapping(address => uint256)) receivedBookmarksPerPeriod; /* feePeriodId => user => number of bookmarks */ uint256 public channelId = 1; uint256 public RESERVE_RATIO = 500000; // 500k / 1 million = 50% uint256 public creatorId = 1; mapping(address => uint256) creatorAddressToId; mapping(uint256 => bytes) creatorIdToName; uint256 public postId = 1; mapping(uint256 => Post) public posts; mapping(uint256 => mapping(uint256 => uint256[])) channelPostsByFeePeriod; /* feePeriodId => channelId => posts */ mapping(address => mapping(uint256 => uint256[])) creatorToPostsByFeePeriod; mapping(address => uint256) creatorToLastPosted; uint256 public TIME_BETWEEN_POSTS = 12 hours; uint256 genesisTimestamp; constructor() public { genesisTimestamp = block.timestamp; } struct Post { uint256 id; uint256 channelId; uint256 feePeriodId; uint256 timestamp; uint256 upvotes; uint256 downvotes; string content; address creator; } /* Fee period id is universal but contract calculates distribution by channel */ struct FeePeriod { uint256 id; uint256 channelId; uint256 valueForEquityDistribution; uint256 valueForCreatorDistribution; } uint256 currentFeePeriod = 1; mapping(uint256 => mapping(uint256 => FeePeriod)) feePeriods; /* feePeriodId => channelId => FeePeriod */ mapping(uint256 => mapping(uint256 => mapping(address => bool))) periodFeesCollected; /* feePeriodId => channelId => owner address => boolean */ event PostCreated( address indexed creator, uint256 indexed channelId, string content ); /* ------ BONDING CURVE FUNCTIONS ------ */ /* @dev call bonded curve mint function and register channel equity ownership @param _channelId to call channel CBT contract */ /* Bonding curve mint tokens */ /* function mintEquity(uint256 _channelId) public payable { require(msg.value > 0, "Must transfer funds to mint equity"); uint256 amount = channelIdToContract[_channelId].mint.value( msg.value )(); channelIdToTotalEquity[_channelId] = channelIdToTotalEquity[_channelId] .add(amount); channelIdToUserEquity[_channelId][msg .sender] = channelIdToUserEquity[_channelId][msg.sender].add( amount ); } */ /* @dev call bonded curve burn function and register decrease in channel equity ownership @param _channelId to call channel CBT contract @param _burnAmount equity to sell */ /* Bonding curve burn token */ /* function burnEquity(uint256 _channelId, uint256 _burnAmount) public { channelIdToContract[_channelId].burn(_burnAmount); channelIdToTotalEquity[_channelId] = channelIdToTotalEquity[_channelId] .sub(_burnAmount); channelIdToUserEquity[_channelId][msg .sender] = channelIdToUserEquity[_channelId][msg.sender].sub( _burnAmount ); } */ /* ------ SUBSCRIPTION FUNCTIONS ------ */ /* @dev user subscribes for each fee period @param _channelId */ function subscribeToChannel(uint256 _channelId) public payable { require( msg.value == CHANNEL_SUBSCRIPTION_FEE, "Must pay exact fee to subscribe" ); channelIdToUserSubscriptionStatus[currentFeePeriod][_channelId][msg .sender] = true; } /* @dev user unsubscribes and loses access at end of fee period @param _channelId */ function unsubscribeToChannel(uint256 _channelId) public { channelIdToUserSubscriptionStatus[currentFeePeriod][_channelId][msg .sender] = false; } function isUserSubscribedToChannel(uint256 _channelId) public returns (bool) { return channelIdToUserSubscriptionStatus[currentFeePeriod][_channelId][msg .sender]; } /* ------ CONTENT FUNCTIONS ------ */ /* @dev deploys new CBT contract, one per content channel @param _channelName */ function createChannel(bytes memory _channelName) public { Channel memory newChannel = Channel({ id: channelId, subscribers: 0, name: _channelName }); channels[channelId++] = newChannel; } /* @dev content creators must register to begin building reputation @param _creatorName */ function registerContentCreator(bytes memory _creatorName) public { require(creatorAddressToId[msg.sender] == 0, "Creator already exists"); creatorAddressToId[msg.sender] = creatorId; creatorIdToName[creatorId] = _creatorName; } /* @dev creators posting content @param _content @param _channelId */ function createPost(string memory _content, uint256 _channelId) public { require(creatorAddressToId[msg.sender] > 0, "Creator not registered"); require( creatorToLastPosted[msg.sender] + TIME_BETWEEN_POSTS < block.timestamp, "Creator must wait 12 hours between posts" ); require( channelIdToUserSubscriptionStatus[currentFeePeriod][_channelId][msg .sender] == true, "Creator not subscribed to channel" ); Post memory newPost = Post({ id: postId, channelId: _channelId, feePeriodId: currentFeePeriod, timestamp: block.timestamp, upvotes: 0, downvotes: 0, content: _content, creator: msg.sender }); emit PostCreated(msg.sender, _channelId, _content); posts[postId] = newPost; channelPostsByFeePeriod[currentFeePeriod][_channelId].push(postId); creatorToPostsByFeePeriod[msg.sender][currentFeePeriod].push(postId++); } /* ------ VOTING FUNCTIONS ------ */ modifier isEquityOwner(uint256 _channelId) { require( channelIdToUserEquity[_channelId][msg.sender] > 0, "Voter isn't an equity owner" ); _; } /* @dev only equity owners in channel are capable of voting @param _channelId @param _postId @param upvote boolean */ function voteOnPost(uint256 _channelId, uint256 _postId, bool upvote) public isEquityOwner(_channelId) { if (upvote) { posts[_postId].upvotes++; } else { posts[_postId].downvotes++; } } /* @dev content consumers are endowed with five bookmarks per fee period bookmarks dictate half of the content creators payout @param _channelId @param _postId @param upvote boolean */ function bookmarkPost(uint256 _postId, uint256 _channelId) public { require( posts[_postId].feePeriodId == currentFeePeriod, "Bookmarks are only valid for posts in current fee period" ); require( userBookmarksPerPeriod[currentFeePeriod][msg.sender] < MAX_BOOKMARKS_PER_PERIOD, "User has no bookmarks remaining" ); require( channelIdToUserSubscriptionStatus[currentFeePeriod][_channelId][msg .sender] == true, "Bookmarker must be subscribed to channel" ); userBookmarksPerPeriod[currentFeePeriod][msg.sender]++; address postCreator = posts[_postId].creator; receivedBookmarksPerPeriod[currentFeePeriod][postCreator]++; } /* ------ FEE PERIOD FUNCTIONS ------ */ function closeFeePeriod() public onlyOwner { require( genesisTimestamp + currentFeePeriod.mul(WEEK_IN_SECONDS) > block.timestamp, "Fee period not yet complete" ); for (uint256 i = 0; i < getNumberOfChannels(); i++) { uint256 fee = (channels[i].subscribers) .mul(CHANNEL_SUBSCRIPTION_FEE) .div(2); feePeriods[currentFeePeriod][i].valueForEquityDistribution = fee; feePeriods[currentFeePeriod][i].valueForCreatorDistribution = fee; } currentFeePeriod++; } function collectEquityFees(uint256 _channelId) public isEquityOwner(_channelId) { uint256 equityOwnership = channelIdToUserEquity[_channelId][msg.sender]; uint256 totalEquity = channelIdToTotalEquity[_channelId]; uint256 payout = (equityOwnership * ( feePeriods[currentFeePeriod - 1][_channelId] .valueForEquityDistribution )) / totalEquity; periodFeesCollected[currentFeePeriod - 1][_channelId][msg .sender] = true; msg.sender.transfer(payout); } function collectContentFees(uint256 _channelId) public { // define isContentCreator } /* ------ GETTER FUNCTIONS ------ */ function getNumberOfChannels() public view returns (uint256 _num) { return channelId - 1; } function getNumberOfPosts(uint256 _feePeriodId, uint256 _channelId) public view returns (uint256 _num) { channelPostsByFeePeriod[_feePeriodId][_channelId].length; } function getPostById(uint256 _postId) public view returns ( uint256 _timestamp, uint256 _upvotes, uint256 _downvotes, string memory _content, address _creator ) { return ( posts[_postId].timestamp, posts[_postId].upvotes, posts[_postId].downvotes, posts[_postId].content, posts[_postId].creator ); } }
------ GETTER FUNCTIONS ------ /
function getNumberOfChannels() public view returns (uint256 _num) { return channelId - 1; }
1,033,347
pragma solidity ^0.4.11; // import "./ERC223BasicToken.sol"; // import "./SafeMath.sol"; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } // end import // import "./ERC223Basic.sol"; contract ERC223Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); function transfer(address to, uint value, bytes data); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } // end import // import "./ERC223ReceivingContract.sol"; /* * Contract that is working with ERC223 tokens */ contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data); } // end import contract ERC223BasicToken is ERC223Basic { using SafeMath for uint; mapping(address => uint) balances; // Function that is called when a user or another contract wants to transfer funds . function transfer(address to, uint value, bytes data) { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(to) } balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(to); receiver.tokenFallback(msg.sender, value, data); } Transfer(msg.sender, to, value, data); } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address to, uint value) { uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(to) } balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(to); bytes memory empty; receiver.tokenFallback(msg.sender, value, empty); } Transfer(msg.sender, to, value, empty); } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } // end import contract PreTgeExperty is ERC223BasicToken { // token constants string public constant name = "Pre-TGE Experty Token"; string public constant symbol = "PEXY"; uint8 public constant decimals = 18; // pre-tge variables uint8 public basicRate = 100; uint8 public preTgeBonus = 45; address public preTgeManager; address public multisigWallet; bool public isClosed = false; // keep track of burned tokens here mapping(address => uint) public burnedTokens; // preICO constructor function PreTgeExperty() { multisigWallet = 0x6fb25777000c069bf4c253b9f5f886a5144a0021; preTgeManager = 0x009A55A3c16953A359484afD299ebdC444200EdB; } // contribute function function() payable { // throw if pre-tge is closed if (isClosed) throw; uint ethers = msg.value; // calculate tokens amount and pre-tge bonus uint tokens = ethers * basicRate; uint bonus = ethers * preTgeBonus; // generate new tokens uint sum = tokens + bonus; balances[msg.sender] += sum; totalSupply += sum; // send ethers to secure wallet multisigWallet.transfer(ethers); } // allow to burn pre-tge tokens in order to teleport them to new contract function burnTokens(uint amount) { if (amount > balances[msg.sender]) throw; balances[msg.sender] = balances[msg.sender].sub(amount); burnedTokens[msg.sender] = burnedTokens[msg.sender].add(amount); } // allow contract manager to decrease bonus over time function changeBonus(uint8 _preTgeBonus) { if (msg.sender != preTgeManager) throw; // we can only decrease bonus if (_preTgeBonus > preTgeBonus) throw; preTgeBonus = _preTgeBonus; } // allow contract manager to close pre-tge function close() { if (msg.sender != preTgeManager) throw; isClosed = true; } }
allow to burn pre-tge tokens in order to teleport them to new contract
function burnTokens(uint amount) { if (amount > balances[msg.sender]) throw; balances[msg.sender] = balances[msg.sender].sub(amount); burnedTokens[msg.sender] = burnedTokens[msg.sender].add(amount); }
8,042,422
./partial_match/3/0x6f1eC6116E6eb7e9843A1dd8F0dC71Af0500D577/sources/ERC20.sol
assert(a == b c + a % b); There is no case in which this doesn't hold
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; }
5,085,628
./partial_match/1/0x3B807162EaFD8637cA81D8CdAAFBF43c0df23972/sources/Superbowl.sol
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./ assert(a == b c + a % b); There is no case in which this doesn't hold
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; }
3,887,368
./full_match/42161/0x947D83b35Cd2e71df4aC7B359C6761B07d0bce19/sources/code/contracts/oasis/OasisSwapPair.sol
if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IOasisSwapFactory(factory).feeTo(); feeOn = feeTo != address(0); if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(5).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } kLast = 0; } }
16,298,674
./full_match/42/0x275b8993c2c763B01f7D754a6b8b3158aaCcC2d3/sources/dex/Main.sol
ojo debo de aprobar que los tokens sean gastados por este contrato 0x9230646A9ebC810cdC893c65aE7684286786A62D, 100,100 actualizo balance del usuario usertoken[_user]= userDepositToken(_amount0,_amount1); agrego la cantidad de tokens que agrego un usuario envio de ETH y Token envio de TOKEN0, TOKEN1
function deposit(address _user,uint256 _amount0, uint256 _amount1) external payable{ usertoken[_user].amount0= usertoken[_user].amount0+_amount0; usertoken[_user].amount1= usertoken[_user].amount1+_amount1; if(tokenWETH==Token0){ require(_amount0==msg.value,"_amount0!=msg.value"); token[Token1].transferFrom(_user, address(this), _amount1); emit Deposit( _user,_amount0, _amount1); emit Deposit( _user,_amount0, _amount1); } token[Token0].approve(address(Token0),_amount0); }
16,240,502
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271Upgradeable { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.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 IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { 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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable { function __ERC721URIStorage_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721URIStorage_init_unchained(); } function __ERC721URIStorage_init_unchained() internal initializer { } using StringsUpgradeable for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSAUpgradeable.sol"; import "../AddressUpgradeable.sol"; import "../../interfaces/IERC1271Upgradeable.sol"; /** * @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and * ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with * smart contract wallets such as Argent and Gnosis. * * Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change * through time. It could return true at block N and false at block N+1 (or the opposite). * * _Available since v4.1._ */ library SignatureCheckerUpgradeable { function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSAUpgradeable.RecoverError error) = ECDSAUpgradeable.tryRecover(hash, signature); if (error == ECDSAUpgradeable.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271Upgradeable.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271Upgradeable.isValidSignature.selector); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 pragma solidity ^0.8.9; /// @title INiftyForge721 /// @author Simon Fremaux (@dievardump) interface INiftyForge721 { struct ModuleInit { address module; bool enabled; bool minter; } /// @notice totalSupply access function totalSupply() external view returns (uint256); /// @notice helper to know if everyone can mint or only minters function isMintingOpenToAll() external view returns (bool); /// @notice Toggle minting open to all state /// @param isOpen if the new state is open or not function setMintingOpenToAll(bool isOpen) external; /// @notice Mint token to `to` with `uri` /// @param to address of recipient /// @param uri token metadata uri /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transferring it to a recipient /// @return tokenId the tokenId function mint( address to, string memory uri, address feeRecipient, uint256 feeAmount, address transferTo ) external returns (uint256 tokenId); /// @notice Mint batch tokens to `to[i]` with `uri[i]` /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, address[] memory feeRecipients, uint256[] memory feeAmounts ) external returns (uint256[] memory tokenIds); /// @notice Mint `tokenId` to to` with `uri` /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it is doing. /// this also means, this function does not verify _maxTokenId /// @param to address of recipient /// @param uri token metadata uri /// @param tokenId token id wanted /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transferring it to a recipient /// @return tokenId the tokenId function mint( address to, string memory uri, uint256 tokenId_, address feeRecipient, uint256 feeAmount, address transferTo ) external returns (uint256 tokenId); /// @notice Mint batch tokens to `to[i]` with `uris[i]` /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it's doing. /// this also means, this function does not verify _maxTokenId /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param tokenIds array of token ids wanted /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, uint256[] memory tokenIds, address[] memory feeRecipients, uint256[] memory feeAmounts ) external returns (uint256[] memory); /// @notice Attach a module /// @param module a module to attach /// @param enabled if the module is enabled by default /// @param canModuleMint if the module has to be given the minter role function attachModule( address module, bool enabled, bool canModuleMint ) external; /// @dev Allows owner to enable a module /// @param module to enable /// @param canModuleMint if the module has to be given the minter role function enableModule(address module, bool canModuleMint) external; /// @dev Allows owner to disable a module /// @param module to disable function disableModule(address module, bool keepListeners) external; /// @notice function that returns a string that can be used to render the current token /// @param tokenId tokenId /// @return the URI to render token function renderTokenURI(uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import './ERC721Ownable.sol'; import './ERC721WithRoles.sol'; import './ERC721WithRoyalties.sol'; import './ERC721WithPermit.sol'; import './ERC721WithMutableURI.sol'; /// @title ERC721Full /// @dev This contains all the different overrides needed on /// ERC721 / URIStorage / Royalties /// This contract does not use ERC721enumerable because Enumerable adds quite some /// gas to minting costs and I am trying to make this cheap for creators. /// Also, since all NiftyForge contracts will be fully indexed in TheGraph it will easily /// Be possible to get tokenIds of an owner off-chain, before passing them to a contract /// which can verify ownership at the processing time /// @author Simon Fremaux (@dievardump) abstract contract ERC721Full is ERC721Ownable, ERC721BurnableUpgradeable, ERC721URIStorageUpgradeable, ERC721WithRoles, ERC721WithRoyalties, ERC721WithPermit, ERC721WithMutableURI { bytes32 public constant ROLE_EDITOR = keccak256('EDITOR'); bytes32 public constant ROLE_MINTER = keccak256('MINTER'); // base token uri string public baseURI; /// @notice modifier allowing only safe listed addresses to mint /// safeListed addresses have roles Minter, Editor or Owner modifier onlyMinter(address minter) virtual { require(canMint(minter), '!NOT_MINTER!'); _; } /// @notice only editor modifier onlyEditor(address sender) virtual override { require(canEdit(sender), '!NOT_EDITOR!'); _; } /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer) function __ERC721Full_init( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address owner_ ) internal { __ERC721Ownable_init( name_, symbol_, contractURI_, openseaProxyRegistry_, owner_ ); __ERC721WithPermit_init(name_); } // receive() external payable {} /// @notice This is a generic function that allows this contract's owner to withdraw /// any balance / ERC20 / ERC721 / ERC1155 it can have /// this contract has no payable nor receive function so it should not get any nativ token /// but this could save some ERC20, 721 or 1155 /// @param token the token to withdraw from. address(0) means native chain token /// @param amount the amount to withdraw if native token, erc20 or erc1155 - must be 0 for ERC721 /// @param tokenId the tokenId to withdraw for ERC1155 and ERC721 function withdraw( address token, uint256 amount, uint256 tokenId ) external onlyOwner { if (token == address(0)) { require( amount == 0 || address(this).balance >= amount, '!WRONG_VALUE!' ); (bool success, ) = msg.sender.call{value: amount}(''); require(success, '!TRANSFER_FAILED!'); } else { // if token is ERC1155 if ( IERC165Upgradeable(token).supportsInterface( type(IERC1155Upgradeable).interfaceId ) ) { IERC1155Upgradeable(token).safeTransferFrom( address(this), msg.sender, tokenId, amount, '' ); } else if ( IERC165Upgradeable(token).supportsInterface( type(IERC721Upgradeable).interfaceId ) ) { //else if ERC721 IERC721Upgradeable(token).safeTransferFrom( address(this), msg.sender, tokenId, '' ); } else { // we consider it's an ERC20 require( IERC20Upgradeable(token).transfer(msg.sender, amount), '!TRANSFER_FAILED!' ); } } } /// @inheritdoc ERC165Upgradeable function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { // all moved here to have less "jumps" when checking an interface return interfaceId == type(IERC721WithMutableURI).interfaceId || interfaceId == type(IERC2981Royalties).interfaceId || interfaceId == type(IRaribleSecondarySales).interfaceId || interfaceId == type(IFoundationSecondarySales).interfaceId || super.supportsInterface(interfaceId); } /// @inheritdoc ERC721Ownable function isApprovedForAll(address owner_, address operator) public view override(ERC721Upgradeable, ERC721Ownable) returns (bool) { return super.isApprovedForAll(owner_, operator); } /// @inheritdoc ERC721URIStorageUpgradeable function tokenURI(uint256 tokenId) public view virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(tokenId); } /// @notice Helper to know if an address can do the action an Editor can /// @param user the address to check function canEdit(address user) public view virtual returns (bool) { return isEditor(user) || owner() == user; } /// @notice Helper to know if an address can do the action an Editor can /// @param user the address to check function canMint(address user) public view virtual returns (bool) { return isMinter(user) || canEdit(user); } /// @notice Helper to know if an address is editor /// @param user the address to check function isEditor(address user) public view returns (bool) { return hasRole(ROLE_EDITOR, user); } /// @notice Helper to know if an address is minter /// @param user the address to check function isMinter(address user) public view returns (bool) { return hasRole(ROLE_MINTER, user); } /// @notice Allows to get approved using a permit and transfer in the same call /// @dev this supposes that the permit is for msg.sender /// @param from current owner /// @param to recipient /// @param tokenId the token id /// @param _data optional data to add /// @param deadline the deadline for the permit to be used /// @param signature of permit function safeTransferFromWithPermit( address from, address to, uint256 tokenId, bytes memory _data, uint256 deadline, bytes memory signature ) external { // use the permit to get msg.sender approved permit(msg.sender, tokenId, deadline, signature); // do the transfer safeTransferFrom(from, to, tokenId, _data); } /// @notice Set the base token URI /// @dev only an editor can do that (account or module) /// @param baseURI_ the new base token uri used in tokenURI() function setBaseURI(string memory baseURI_) external onlyEditor(msg.sender) { baseURI = baseURI_; } /// @notice Set the base mutable meta URI for tokens /// @param baseMutableURI_ the new base for mutable meta uri used in mutableURI() function setBaseMutableURI(string memory baseMutableURI_) external onlyEditor(msg.sender) { _setBaseMutableURI(baseMutableURI_); } /// @notice Set the mutable URI for a token /// @dev Mutable URI work like tokenURI /// -> if there is a baseMutableURI and a mutableURI, concat baseMutableURI + mutableURI /// -> else if there is only mutableURI, return mutableURI //. -> else if there is only baseMutableURI, concat baseMutableURI + tokenId /// @dev only an editor (account or module) can call this /// @param tokenId the token to set the mutable URI for /// @param mutableURI_ the mutable URI function setMutableURI(uint256 tokenId, string memory mutableURI_) external onlyEditor(msg.sender) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); _setMutableURI(tokenId, mutableURI_); } /// @notice Helper for the owner to add new editors /// @dev needs to be owner /// @param users list of new editors function addEditors(address[] memory users) public onlyOwner { for (uint256 i; i < users.length; i++) { _grantRole(ROLE_MINTER, users[i]); } } /// @notice Helper for the owner to remove editors /// @dev needs to be owner /// @param users list of removed editors function removeEditors(address[] memory users) public onlyOwner { for (uint256 i; i < users.length; i++) { _revokeRole(ROLE_MINTER, users[i]); } } /// @notice Helper for an editor to add new minter /// @dev needs to be owner /// @param users list of new minters function addMinters(address[] memory users) public onlyEditor(msg.sender) { for (uint256 i; i < users.length; i++) { _grantRole(ROLE_MINTER, users[i]); } } /// @notice Helper for an editor to remove minters /// @dev needs to be owner /// @param users list of removed minters function removeMinters(address[] memory users) public onlyEditor(msg.sender) { for (uint256 i; i < users.length; i++) { _revokeRole(ROLE_MINTER, users[i]); } } /// @notice Allows to change the default royalties recipient /// @dev an editor can call this /// @param recipient new default royalties recipient function setDefaultRoyaltiesRecipient(address recipient) external onlyEditor(msg.sender) { require(!hasPerTokenRoyalties(), '!PER_TOKEN_ROYALTIES!'); _setDefaultRoyaltiesRecipient(recipient); } /// @notice Allows a royalty recipient of a token to change their recipient address /// @dev only the current token royalty recipient can change the address /// @param tokenId the token to change the recipient for /// @param recipient new default royalties recipient function setTokenRoyaltiesRecipient(uint256 tokenId, address recipient) external { require(hasPerTokenRoyalties(), '!CONTRACT_WIDE_ROYALTIES!'); (address currentRecipient, ) = _getTokenRoyalty(tokenId); require(msg.sender == currentRecipient, '!NOT_ALLOWED!'); _setTokenRoyaltiesRecipient(tokenId, recipient); } /// @inheritdoc ERC721Upgradeable function _transfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721WithPermit) { super._transfer(from, to, tokenId); } /// @inheritdoc ERC721Upgradeable function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { // remove royalties _removeRoyalty(tokenId); // remove mutableURI _setMutableURI(tokenId, ''); // burn ERC721URIStorage super._burn(tokenId); } /// @inheritdoc ERC721Upgradeable function _baseURI() internal view virtual override returns (string memory) { return baseURI; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '../OpenSea/BaseOpenSea.sol'; /// @title ERC721Ownable /// @author Simon Fremaux (@dievardump) contract ERC721Ownable is OwnableUpgradeable, ERC721Upgradeable, BaseOpenSea { /// @notice modifier that allows higher level contracts to define /// editors that are not only the owner modifier onlyEditor(address sender) virtual { require(sender == owner(), '!NOT_EDITOR!'); _; } /// @notice constructor /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer) function __ERC721Ownable_init( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address owner_ ) internal initializer { __Ownable_init(); __ERC721_init_unchained(name_, symbol_); // set contract uri if present if (bytes(contractURI_).length > 0) { _setContractURI(contractURI_); } // set OpenSea proxyRegistry for gas-less trading if present if (address(0) != openseaProxyRegistry_) { _setOpenSeaRegistry(openseaProxyRegistry_); } // transferOwnership if needed if (address(0) != owner_) { transferOwnership(owner_); } } /// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user /// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy /// @inheritdoc ERC721Upgradeable function isApprovedForAll(address owner_, address operator) public view virtual override returns (bool) { // allows gas less trading on OpenSea return super.isApprovedForAll(owner_, operator) || isOwnersOpenSeaProxy(owner_, operator); } /// @notice Helper for the owner of the contract to set the new contract URI /// @dev needs to be owner /// @param contractURI_ new contract URI function setContractURI(string memory contractURI_) external onlyEditor(msg.sender) { _setContractURI(contractURI_); } /// @notice Helper for the owner to set OpenSea's proxy (allowing or not gas-less trading) /// @dev needs to be owner /// @param osProxyRegistry new opensea proxy registry function setOpenSeaRegistry(address osProxyRegistry) external onlyEditor(msg.sender) { _setOpenSeaRegistry(osProxyRegistry); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol'; import './IERC721WithMutableURI.sol'; /// @dev This is a contract used to add mutableURI to the contract /// @author Simon Fremaux (@dievardump) contract ERC721WithMutableURI is IERC721WithMutableURI, ERC721Upgradeable { using StringsUpgradeable for uint256; // base mutable meta URI string public baseMutableURI; mapping(uint256 => string) private _tokensMutableURIs; /// @notice See {ERC721WithMutableURI-mutableURI}. function mutableURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); string memory _tokenMutableURI = _tokensMutableURIs[tokenId]; string memory base = _baseMutableURI(); // If both are set, concatenate the baseURI and mutableURI (via abi.encodePacked). if (bytes(base).length > 0 && bytes(_tokenMutableURI).length > 0) { return string(abi.encodePacked(base, _tokenMutableURI)); } // If only token mutable URI is set if (bytes(_tokenMutableURI).length > 0) { return _tokenMutableURI; } // else return base + tokenId return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ''; } /// @dev helper to get the base for mutable meta /// @return the base for mutable meta uri function _baseMutableURI() internal view returns (string memory) { return baseMutableURI; } /// @dev Set the base mutable meta URI /// @param baseMutableURI_ the new base for mutable meta uri used in mutableURI() function _setBaseMutableURI(string memory baseMutableURI_) internal { baseMutableURI = baseMutableURI_; } /// @dev Set the mutable URI for a token /// @param tokenId the token id /// @param mutableURI_ the new mutableURI for tokenId function _setMutableURI(uint256 tokenId, string memory mutableURI_) internal { if (bytes(mutableURI_).length == 0) { if (bytes(_tokensMutableURIs[tokenId]).length > 0) { delete _tokensMutableURIs[tokenId]; } } else { _tokensMutableURIs[tokenId] = mutableURI_; } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/SignatureCheckerUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; /// @title ERC721WithPermit /// @author Simon Fremaux (@dievardump) /// @notice This implementation differs from what I can see everywhere else /// My take on Permits for NFTs is that the nonce should be linked to the tokens /// and not to an owner. /// Whenever a token is transfered, its nonce should increase. /// This allows to emit a lot of Permit (for sales for example) but ensure they /// will get invalidated after the token is transfered /// This also allows an owner to emit several Permit on different tokens /// and not have Permit to be used one after the other /// Example: /// An owner sign a Permit of sale on OpenSea and on Rarible at the same time /// Only the first one that will sell the item will be able to use the permit /// The nonce being incremented, this Permits won't be usable anymore abstract contract ERC721WithPermit is ERC721Upgradeable { bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)' ); bytes32 public DOMAIN_SEPARATOR; mapping(uint256 => uint256) private _nonces; // function to initialize the contract function __ERC721WithPermit_init(string memory name_) internal { DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ), keccak256(bytes(name_)), keccak256(bytes('1')), block.chainid, address(this) ) ); } /// @notice Allows to retrieve current nonce for token /// @param tokenId token id /// @return current nonce function nonce(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); return _nonces[tokenId]; } function makePermitDigest( address spender, uint256 tokenId, uint256 nonce_, uint256 deadline ) public view returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash( DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, spender, tokenId, nonce_, deadline ) ) ); } /// @notice function to be called by anyone to approve `spender` using a Permit signature /// @dev Anyone can call this to approve `spender`, even a third-party /// @param spender the actor to approve /// @param tokenId the token id /// @param deadline the deadline for the permit to be used /// @param signature permit function permit( address spender, uint256 tokenId, uint256 deadline, bytes memory signature ) public { require(deadline >= block.timestamp, '!PERMIT_DEADLINE_EXPIRED!'); // this will revert if token is burned address owner_ = ownerOf(tokenId); bytes32 digest = makePermitDigest( spender, tokenId, _nonces[tokenId], deadline ); (address recoveredAddress, ) = ECDSAUpgradeable.tryRecover( digest, signature ); require( ( // no need to check for recoveredAddress == 0 // because if it's 0, it won't work (recoveredAddress == owner_ || isApprovedForAll(owner_, recoveredAddress)) ) || // if owner is a contract, try to recover signature using SignatureChecker SignatureCheckerUpgradeable.isValidSignatureNow( owner_, digest, signature ), '!INVALID_PERMIT_SIGNATURE!' ); _approve(spender, tokenId); } /// @dev helper to easily increment a nonce for a given tokenId /// @param tokenId the tokenId to increment the nonce for function _incrementNonce(uint256 tokenId) internal { _nonces[tokenId]++; } /// @dev _transfer override to be able to increment the nonce /// @inheritdoc ERC721Upgradeable function _transfer( address from, address to, uint256 tokenId ) internal virtual override { super._transfer(from, to, tokenId); // increment the permit nonce linked to this tokenId. // this will ensure that a Permit can not be used on a token // if it were to leave the owner's hands and come back later // this if saves 20k on the mint, which is already expensive enough if (from != address(0)) { _incrementNonce(tokenId); } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol'; /// @title ERC721WithRoles /// @author Simon Fremaux (@dievardump) abstract contract ERC721WithRoles { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /// @notice emitted when a role is given to a user /// @param role the granted role /// @param user the user that got a role granted event RoleGranted(bytes32 indexed role, address indexed user); /// @notice emitted when a role is givrevoked from a user /// @param role the revoked role /// @param user the user that got a role revoked event RoleRevoked(bytes32 indexed role, address indexed user); mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /// @notice Helper to know is an address has a role /// @param role the role to check /// @param user the address to check function hasRole(bytes32 role, address user) public view returns (bool) { return _roleMembers[role].contains(user); } /// @notice Helper to list all users in a role /// @return list of role members function listRole(bytes32 role) external view returns (address[] memory list) { uint256 count = _roleMembers[role].length(); list = new address[](count); for (uint256 i; i < count; i++) { list[i] = _roleMembers[role].at(i); } } /// @notice internal helper to grant a role to a user /// @param role role to grant /// @param user to grant role to function _grantRole(bytes32 role, address user) internal returns (bool) { if (_roleMembers[role].add(user)) { emit RoleGranted(role, user); return true; } return false; } /// @notice Helper to revoke a role from a user /// @param role role to revoke /// @param user to revoke role from function _revokeRole(bytes32 role, address user) internal returns (bool) { if (_roleMembers[role].remove(user)) { emit RoleRevoked(role, user); return true; } return false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '../Royalties/ERC2981/ERC2981Royalties.sol'; import '../Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol'; import '../Royalties/FoundationSecondarySales/IFoundationSecondarySales.sol'; /// @dev This is a contract used for royalties on various platforms /// @author Simon Fremaux (@dievardump) contract ERC721WithRoyalties is ERC2981Royalties, IRaribleSecondarySales, IFoundationSecondarySales { /// @inheritdoc IRaribleSecondarySales function getFeeRecipients(uint256 tokenId) public view override returns (address payable[] memory recipients) { // using ERC2981 implementation to get the recipient & amount (address recipient, uint256 amount) = _getTokenRoyalty(tokenId); if (amount != 0) { recipients = new address payable[](1); recipients[0] = payable(recipient); } } /// @inheritdoc IRaribleSecondarySales function getFeeBps(uint256 tokenId) public view override returns (uint256[] memory fees) { // using ERC2981 implementation to get the amount (, uint256 amount) = _getTokenRoyalty(tokenId); if (amount != 0) { fees = new uint256[](1); fees[0] = amount; } } function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory recipients, uint256[] memory fees) { // using ERC2981 implementation to get the recipient & amount (address recipient, uint256 amount) = _getTokenRoyalty(tokenId); if (amount != 0) { recipients = new address payable[](1); recipients[0] = payable(recipient); fees = new uint256[](1); fees[0] = amount; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @dev This is the interface for NFT extension mutableURI /// @author Simon Fremaux (@dievardump) interface IERC721WithMutableURI { function mutableURI(uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @title OpenSea contract helper that defines a few things /// @author Simon Fremaux (@dievardump) /// @dev This is a contract used to add OpenSea's /// gas-less trading and contractURI support contract BaseOpenSea { event NewContractURI(string contractURI); string private _contractURI; address private _proxyRegistry; /// @notice Returns the contract URI function. Used on OpenSea to get details // about a contract (owner, royalties etc...) function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Returns the current OS proxyRegistry address registered function proxyRegistry() public view returns (address) { return _proxyRegistry; } /// @notice Helper allowing OpenSea gas-less trading by verifying who's operator /// for owner /// @dev Allows to check if `operator` is owner's OpenSea proxy on eth mainnet / rinkeby /// or to check if operator is OpenSea's proxy contract on Polygon and Mumbai /// @param owner the owner we check for /// @param operator the operator (proxy) we check for function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool) { address proxyRegistry_ = _proxyRegistry; // if we have a proxy registry if (proxyRegistry_ != address(0)) { // on ethereum mainnet or rinkeby use "ProxyRegistry" to // get owner's proxy if (block.chainid == 1 || block.chainid == 4) { return address(ProxyRegistry(proxyRegistry_).proxies(owner)) == operator; } else if (block.chainid == 137 || block.chainid == 80001) { // on Polygon and Mumbai just try with OpenSea's proxy contract // https://docs.opensea.io/docs/polygon-basic-integration return proxyRegistry_ == operator; } } return false; } /// @dev Internal function to set the _contractURI /// @param contractURI_ the new contract uri function _setContractURI(string memory contractURI_) internal { _contractURI = contractURI_; emit NewContractURI(contractURI_); } /// @dev Internal function to set the _proxyRegistry /// @param proxyRegistryAddress the new proxy registry address function _setOpenSeaRegistry(address proxyRegistryAddress) internal { _proxyRegistry = proxyRegistryAddress; } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './IERC2981Royalties.sol'; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 abstract contract ERC2981Royalties is IERC2981Royalties { struct RoyaltyData { address recipient; uint96 amount; } // this variable is set to true, whenever "contract wide" royalties are set // this can not be undone and this takes precedence to any other royalties already set. bool private _useContractRoyalties; // those are the "contract wide" royalties, used for collections that all pay royalties to // the same recipient, with the same value // once set, like any other royalties, it can not be modified RoyaltyData private _contractRoyalties; mapping(uint256 => RoyaltyData) private _royalties; function hasPerTokenRoyalties() public view returns (bool) { return !_useContractRoyalties; } /// @inheritdoc IERC2981Royalties function royaltyInfo(uint256 tokenId, uint256 value) public view override returns (address receiver, uint256 royaltyAmount) { // get base values (receiver, royaltyAmount) = _getTokenRoyalty(tokenId); // calculate due amount if (royaltyAmount != 0) { royaltyAmount = (value * royaltyAmount) / 10000; } } /// @dev Sets token royalties /// @param id the token id fir which we register the royalties function _removeRoyalty(uint256 id) internal { delete _royalties[id]; } /// @dev Sets token royalties /// @param id the token id for which we register the royalties /// @param recipient recipient of the royalties /// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0) function _setTokenRoyalty( uint256 id, address recipient, uint256 value ) internal { // you can't set per token royalties if using "contract wide" ones require( !_useContractRoyalties, '!ERC2981Royalties:ROYALTIES_CONTRACT_WIDE!' ); require(value <= 10000, '!ERC2981Royalties:TOO_HIGH!'); _royalties[id] = RoyaltyData(recipient, uint96(value)); } /// @dev Gets token royalties /// @param id the token id for which we check the royalties function _getTokenRoyalty(uint256 id) internal view virtual returns (address, uint256) { RoyaltyData memory data; if (_useContractRoyalties) { data = _contractRoyalties; } else { data = _royalties[id]; } return (data.recipient, uint256(data.amount)); } /// @dev set contract royalties; /// This can only be set once, because we are of the idea that royalties /// Amounts should never change after they have been set /// Once default values are set, it will be used for all royalties inquiries /// @param recipient the default royalties recipient /// @param value the default royalties value function _setDefaultRoyalties(address recipient, uint256 value) internal { require( _useContractRoyalties == false, '!ERC2981Royalties:DEFAULT_ALREADY_SET!' ); require(value <= 10000, '!ERC2981Royalties:TOO_HIGH!'); _useContractRoyalties = true; _contractRoyalties = RoyaltyData(recipient, uint96(value)); } /// @dev allows to set the default royalties recipient /// @param recipient the new recipient function _setDefaultRoyaltiesRecipient(address recipient) internal { _contractRoyalties.recipient = recipient; } /// @dev allows to set a tokenId royalties recipient /// @param tokenId the token Id /// @param recipient the new recipient function _setTokenRoyaltiesRecipient(uint256 tokenId, address recipient) internal { _royalties[tokenId].recipient = recipient; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; interface IFoundationSecondarySales { /// @notice returns a list of royalties recipients and the amount /// @param tokenId the token Id to check for /// @return all the recipients and their basis points, for tokenId function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; interface IRaribleSecondarySales { /// @notice returns a list of royalties recipients /// @param tokenId the token Id to check for /// @return all the recipients for tokenId function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); /// @notice returns a list of royalties amounts /// @param tokenId the token Id to check for /// @return all the amounts for tokenId function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './Modules/INFModuleWithEvents.sol'; /// @title INiftyForgeBase /// @author Simon Fremaux (@dievardump) interface INiftyForgeModules { enum ModuleStatus { UNKNOWN, ENABLED, DISABLED } /// @notice Helper to list all modules with their state /// @return list of modules and status function listModules() external view returns (address[] memory list, uint256[] memory status); /// @notice allows a module to listen to events (mint, transfer, burn) /// @param eventType the type of event to listen to function addEventListener(INFModuleWithEvents.Events eventType) external; /// @notice allows a module to stop listening to events (mint, transfer, burn) /// @param eventType the type of event to stop listen to function removeEventListener(INFModuleWithEvents.Events eventType) external; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol'; interface INFModule is IERC165Upgradeable { /// @notice Called by a Token Registry whenever the module is Attached /// @return if the attach worked function onAttach() external returns (bool); /// @notice Called by a Token Registry whenever the module is Enabled /// @return if the enabling worked function onEnable() external returns (bool); /// @notice Called by a Token Registry whenever the module is Disabled function onDisable() external; /// @notice returns an URI with information about the module /// @return the URI where to find information about the module function contractURI() external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleMutableURI is INFModule { function mutableURI(uint256 tokenId) external view returns (string memory); function mutableURI(address registry, uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleRenderTokenURI is INFModule { function renderTokenURI(uint256 tokenId) external view returns (string memory); function renderTokenURI(address registry, uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleTokenURI is INFModule { function tokenURI(uint256 tokenId) external view returns (string memory); function tokenURI(address registry, uint256 tokenId) external view returns (string memory); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleWithEvents is INFModule { enum Events { MINT, TRANSFER, BURN } /// @dev callback received from a contract when an event happens /// @param eventType the type of event fired /// @param tokenId the token for which the id is fired /// @param from address from /// @param to address to function onEvent( Events eventType, uint256 tokenId, address from, address to ) external; } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './INFModule.sol'; interface INFModuleWithRoyalties is INFModule { /// @notice Return royalties (recipient, basisPoint) for tokenId /// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters /// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible) /// @param tokenId token to check /// @return recipient and basisPoint for this tokenId function royaltyInfo(uint256 tokenId) external view returns (address recipient, uint256 basisPoint); /// @notice Return royalties (recipient, basisPoint) for tokenId /// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters /// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible) /// @param registry registry to check id of /// @param tokenId token to check /// @return recipient and basisPoint for this tokenId function royaltyInfo(address registry, uint256 tokenId) external view returns (address recipient, uint256 basisPoint); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol'; import './Modules/INFModule.sol'; import './Modules/INFModuleWithEvents.sol'; import './INiftyForgeModules.sol'; /// @title NiftyForgeBase /// @author Simon Fremaux (@dievardump) /// @notice These modules can be attached to a contract and enabled/disabled later /// They can be used to mint elements (need Minter Role) but also can listen /// To events like MINT, TRANSFER and BURN /// /// To module developers: /// Remember cross contract calls have a high cost, and reads too. /// Do not abuse of Events and only use them if there is a high value to it /// Gas is not cheap, always think of users first. contract NiftyForgeModules is INiftyForgeModules { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; // event emitted whenever a module status changed event ModuleChanged(address module); // 3 types of events Mint, Transfer and Burn EnumerableSetUpgradeable.AddressSet[3] private _listeners; // modules list // should create a module role instead? EnumerableSetUpgradeable.AddressSet internal modules; // modules status mapping(address => ModuleStatus) public modulesStatus; modifier onlyEnabledModule() { require( modulesStatus[msg.sender] == ModuleStatus.ENABLED, '!MODULE_NOT_ENABLED!' ); _; } /// @notice Helper to list all modules with their state /// @return list of modules and status function listModules() external view override returns (address[] memory list, uint256[] memory status) { uint256 count = modules.length(); list = new address[](count); status = new uint256[](count); for (uint256 i; i < count; i++) { list[i] = modules.at(i); status[i] = uint256(modulesStatus[list[i]]); } } /// @notice allows a module to listen to events (mint, transfer, burn) /// @param eventType the type of event to listen to function addEventListener(INFModuleWithEvents.Events eventType) external override onlyEnabledModule { _listeners[uint256(eventType)].add(msg.sender); } /// @notice allows a module to stop listening to events (mint, transfer, burn) /// @param eventType the type of event to stop listen to function removeEventListener(INFModuleWithEvents.Events eventType) external override onlyEnabledModule { _listeners[uint256(eventType)].remove(msg.sender); } /// @notice Attach a module /// @param module a module to attach /// @param enabled if the module is enabled by default function _attachModule(address module, bool enabled) internal { require( modulesStatus[module] == ModuleStatus.UNKNOWN, '!ALREADY_ATTACHED!' ); // add to modules list modules.add(module); // tell the module it's attached // making sure module can be attached to this contract require(INFModule(module).onAttach(), '!ATTACH_FAILED!'); if (enabled) { _enableModule(module); } else { _disableModule(module, true); } } /// @dev Allows owner to enable a module (needs to be disabled) /// @param module to enable function _enableModule(address module) internal { require( modulesStatus[module] != ModuleStatus.ENABLED, '!NOT_DISABLED!' ); modulesStatus[module] = ModuleStatus.ENABLED; // making sure module can be enabled on this contract require(INFModule(module).onEnable(), '!ENABLING_FAILED!'); emit ModuleChanged(module); } /// @dev Disables a module /// @param module the module to disable /// @param keepListeners a boolean to know if the module can still listen to events /// meaning the module can not interact with the contract anymore but is still working /// for example: a module that transfers an ERC20 to people Minting function _disableModule(address module, bool keepListeners) internal virtual { require( modulesStatus[module] != ModuleStatus.DISABLED, '!NOT_ENABLED!' ); modulesStatus[module] = ModuleStatus.DISABLED; // we do a try catch without checking return or error here // because owners should be able to disable a module any time without the module being ok // with it or not try INFModule(module).onDisable() {} catch {} // remove all listeners if not explicitely asked to keep them if (!keepListeners) { _listeners[uint256(INFModuleWithEvents.Events.MINT)].remove(module); _listeners[uint256(INFModuleWithEvents.Events.TRANSFER)].remove( module ); _listeners[uint256(INFModuleWithEvents.Events.BURN)].remove(module); } emit ModuleChanged(module); } /// @dev fire events to listeners /// @param eventType the type of event fired /// @param tokenId the token for which the id is fired /// @param from address from /// @param to address to function _fireEvent( INFModuleWithEvents.Events eventType, uint256 tokenId, address from, address to ) internal { EnumerableSetUpgradeable.AddressSet storage listeners = _listeners[ uint256(eventType) ]; uint256 length = listeners.length(); for (uint256 i; i < length; i++) { INFModuleWithEvents(listeners.at(i)).onEvent( eventType, tokenId, from, to ); } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import './NFT/ERC721Helpers/ERC721Full.sol'; import './NiftyForge/Modules/INFModuleWithEvents.sol'; import './NiftyForge/Modules/INFModuleTokenURI.sol'; import './NiftyForge/Modules/INFModuleRenderTokenURI.sol'; import './NiftyForge/Modules/INFModuleWithRoyalties.sol'; import './NiftyForge/Modules/INFModuleMutableURI.sol'; import './NiftyForge/NiftyForgeModules.sol'; import './INiftyForge721.sol'; /// @title NiftyForge721 /// @author Simon Fremaux (@dievardump) contract NiftyForge721 is INiftyForge721, NiftyForgeModules, ERC721Full { /// @dev This contains the last token id that was created uint256 public lastTokenId; uint256 public totalSupply; bool private _mintingOpenToAll; // this can be set only once by the owner of the contract // this is used to ensure a max token creation that can be used // for example when people create a series of XX elements // since this contract works with "Minters", it is good to // be able to set in it that there is a max number of elements // and that this can not change uint256 public maxTokenId; mapping(uint256 => address) public tokenIdToModule; /// @notice modifier allowing only safe listed addresses to mint /// safeListed addresses have roles Minter, Editor or Owner modifier onlyMinter(address minter) virtual override { require(isMintingOpenToAll() || canMint(minter), '!NOT_MINTER!'); _; } /// @notice this is the constructor of the contract, called at the time of creation /// Although it uses what are called upgradeable contracts, this is only to /// be able to make deployment cheap using a Proxy but NiftyForge contracts /// ARE NOT UPGRADEABLE => the proxy used is not an upgradeable proxy, the implementation is immutable /// @param name_ name of the contract (see ERC721) /// @param symbol_ symbol of the contract (see ERC721) /// @param contractURI_ The contract URI (containing its metadata) - can be empty "" /// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0) /// @param owner_ Address to whom transfer ownership /// @param modulesInit_ modules to add / enable directly at creation /// @param contractRoyaltiesRecipient the recipient, if the contract has "contract wide royalties" /// @param contractRoyaltiesValue the value, modules to add / enable directly at creation function initialize( string memory name_, string memory symbol_, string memory contractURI_, address openseaProxyRegistry_, address owner_, ModuleInit[] memory modulesInit_, address contractRoyaltiesRecipient, uint256 contractRoyaltiesValue ) external initializer { __ERC721Full_init( name_, symbol_, contractURI_, openseaProxyRegistry_, owner_ ); for (uint256 i; i < modulesInit_.length; i++) { _attachModule(modulesInit_[i].module, modulesInit_[i].enabled); if (modulesInit_[i].enabled && modulesInit_[i].minter) { _grantRole(ROLE_MINTER, modulesInit_[i].module); } } // here, if contractRoyaltiesRecipient is not address(0) but // contractRoyaltiesValue is 0, this will mean that this contract will // NEVER have royalties, because whenever default royalties are set, it is // always used for every tokens. if ( contractRoyaltiesRecipient != address(0) || contractRoyaltiesValue != 0 ) { _setDefaultRoyalties( contractRoyaltiesRecipient, contractRoyaltiesValue ); } } /// @notice helper to know if everyone can mint or only minters function isMintingOpenToAll() public view override returns (bool) { return _mintingOpenToAll; } /// @notice returns a tokenURI /// @dev This function will first check if there is a tokenURI registered for this token in the contract /// if not it will check if the token comes from a Module, and if yes, try to get the tokenURI from it /// /// @param tokenId a parameter just like in doxygen (must be followed by parameter name) /// @return uri the tokenURI /// @inheritdoc ERC721Upgradeable function tokenURI(uint256 tokenId) public view virtual override returns (string memory uri) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); // first, try to get the URI from the module that might have created it (bool support, address module) = _moduleSupports( tokenId, type(INFModuleTokenURI).interfaceId ); if (support) { uri = INFModuleTokenURI(module).tokenURI(tokenId); } // if uri not set, get it with the normal tokenURI if (bytes(uri).length == 0) { uri = super.tokenURI(tokenId); } } /// @notice function that returns a string that can be used to render the current token /// this can be an URL but also any other data uri /// This is something that I would like to present as an EIP later to allow dynamique /// render URL /// @param tokenId tokenId /// @return uri the URI to render token function renderTokenURI(uint256 tokenId) public view override returns (string memory uri) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); // Try to get the URI from the module that might have created this token (bool support, address module) = _moduleSupports( tokenId, type(INFModuleRenderTokenURI).interfaceId ); if (support) { uri = INFModuleRenderTokenURI(module).renderTokenURI(tokenId); } } /// @notice Toggle minting open to all state /// @param isOpen if the new state is open or not function setMintingOpenToAll(bool isOpen) external override onlyEditor(msg.sender) { _mintingOpenToAll = isOpen; } /// @notice allows owner to set maxTokenId /// @dev be careful, this is a one time call function. /// When set, the maxTokenId can not be reverted nor changed /// @param maxTokenId_ the max token id possible function setMaxTokenId(uint256 maxTokenId_) external onlyEditor(msg.sender) { require(maxTokenId == 0, '!MAX_TOKEN_ALREADY_SET!'); maxTokenId = maxTokenId_; } /// @notice function that returns a string that can be used to add metadata on top of what is in tokenURI /// This function has been added because sometimes, we want some metadata to be completly immutable /// But to have others that aren't (for example if a token is linked to a physical token, and the physical /// token state can change over time) /// This way we can reflect those changes without risking breaking the base meta (tokenURI) /// @param tokenId tokenId /// @return uri the URI where mutable can be found function mutableURI(uint256 tokenId) public view override returns (string memory uri) { require(_exists(tokenId), '!UNKNOWN_TOKEN!'); // first, try to get the URI from the module that might have created it (bool support, address module) = _moduleSupports( tokenId, type(INFModuleMutableURI).interfaceId ); if (support) { uri = INFModuleMutableURI(module).mutableURI(tokenId); } // if uri not set, get it with the normal mutableURI if (bytes(uri).length == 0) { uri = super.mutableURI(tokenId); } } /// @notice Mint token to `to` with `uri` /// @param to address of recipient /// @param uri token metadata uri /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transfering it to a recipient /// @return tokenId the tokenId function mint( address to, string memory uri, address feeRecipient, uint256 feeAmount, address transferTo ) public override onlyMinter(msg.sender) returns (uint256 tokenId) { tokenId = lastTokenId + 1; lastTokenId = mint( to, uri, tokenId, feeRecipient, feeAmount, transferTo ); } /// @notice Mint batch tokens to `to[i]` with `uri[i]` /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, address[] memory feeRecipients, uint256[] memory feeAmounts ) public override onlyMinter(msg.sender) returns (uint256[] memory tokenIds) { require( to.length == uris.length && to.length == feeRecipients.length && to.length == feeAmounts.length, '!LENGTH_MISMATCH!' ); uint256 tokenId = lastTokenId; tokenIds = new uint256[](to.length); // verify that we don't overflow // done here instead of in _mint so we do one read // instead of to.length _verifyMaxTokenId(tokenId + to.length); bool isModule = modulesStatus[msg.sender] == ModuleStatus.ENABLED; for (uint256 i; i < to.length; i++) { tokenId++; _mint( to[i], uris[i], tokenId, feeRecipients[i], feeAmounts[i], isModule ); tokenIds[i] = tokenId; } // setting lastTokenId after will ensure that any reEntrancy will fail // to mint, because the minting will throw with a duplicate id lastTokenId = tokenId; } /// @notice Mint `tokenId` to to` with `uri` and transfer to transferTo if not null /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it is doing. /// this also means, this function does not verify maxTokenId /// @param to address of recipient /// @param uri token metadata uri /// @param tokenId_ token id wanted /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amount. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param transferTo the address to transfer the NFT to after mint /// this is used when we want to mint the NFT to the creator address /// before transfering it to a recipient /// @return the tokenId function mint( address to, string memory uri, uint256 tokenId_, address feeRecipient, uint256 feeAmount, address transferTo ) public override onlyMinter(msg.sender) returns (uint256) { // minting will throw if the tokenId_ already exists // we also verify maxTokenId in this case // because else it would allow owners to mint arbitrary tokens // after setting the max _verifyMaxTokenId(tokenId_); _mint( to, uri, tokenId_, feeRecipient, feeAmount, modulesStatus[msg.sender] == ModuleStatus.ENABLED ); if (transferTo != address(0)) { _transfer(to, transferTo, tokenId_); } return tokenId_; } /// @notice Mint batch tokens to `to[i]` with `uris[i]` /// Because not all tokenIds have incremental ids /// be careful with this function, it does not increment lastTokenId /// and expects the minter to actually know what it's doing. /// this also means, this function does not verify maxTokenId /// @param to array of address of recipients /// @param uris array of token metadata uris /// @param tokenIds array of token ids wanted /// @param feeRecipients the recipients of royalties for each id /// @param feeAmounts the royalties amounts for each id. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @return tokenIds the tokenIds function mintBatch( address[] memory to, string[] memory uris, uint256[] memory tokenIds, address[] memory feeRecipients, uint256[] memory feeAmounts ) public override onlyMinter(msg.sender) returns (uint256[] memory) { // minting will throw if any tokenIds[i] already exists require( to.length == uris.length && to.length == tokenIds.length && to.length == feeRecipients.length && to.length == feeAmounts.length, '!LENGTH_MISMATCH!' ); uint256 highestId; for (uint256 i; i < tokenIds.length; i++) { if (tokenIds[i] > highestId) { highestId = tokenIds[i]; } } // we also verify maxTokenId in this case // because else it would allow owners to mint arbitrary tokens // after setting the max _verifyMaxTokenId(highestId); bool isModule = modulesStatus[msg.sender] == ModuleStatus.ENABLED; for (uint256 i; i < to.length; i++) { if (tokenIds[i] > highestId) { highestId = tokenIds[i]; } _mint( to[i], uris[i], tokenIds[i], feeRecipients[i], feeAmounts[i], isModule ); } return tokenIds; } /// @notice Attach a module /// @param module a module to attach /// @param enabled if the module is enabled by default /// @param moduleCanMint if the module has to be given the minter role function attachModule( address module, bool enabled, bool moduleCanMint ) external override onlyEditor(msg.sender) { // give the minter role if enabled and moduleCanMint if (moduleCanMint && enabled) { _grantRole(ROLE_MINTER, module); } _attachModule(module, enabled); } /// @dev Allows owner to enable a module /// @param module to enable /// @param moduleCanMint if the module has to be given the minter role function enableModule(address module, bool moduleCanMint) external override onlyEditor(msg.sender) { // give the minter role if moduleCanMint if (moduleCanMint) { _grantRole(ROLE_MINTER, module); } _enableModule(module); } /// @dev Allows owner to disable a module /// @param module to disable function disableModule(address module, bool keepListeners) external override onlyEditor(msg.sender) { _disableModule(module, keepListeners); } /// @dev Internal mint function /// @param to token recipient /// @param uri token uri /// @param tokenId token Id /// @param feeRecipient the recipient of royalties /// @param feeAmount the royalties amounts. From 0 to 10000 /// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50% /// @param isModule if the minter is a module function _mint( address to, string memory uri, uint256 tokenId, address feeRecipient, uint256 feeAmount, bool isModule ) internal { _safeMint(to, tokenId, ''); if (bytes(uri).length > 0) { _setTokenURI(tokenId, uri); } if (feeAmount > 0) { _setTokenRoyalty(tokenId, feeRecipient, feeAmount); } if (isModule) { tokenIdToModule[tokenId] = msg.sender; } } // here we override _mint, _transfer and _burn because we want the event to be fired // only after the action is done // else we would have done that in _beforeTokenTransfer /// @dev _mint override to be able to fire events /// @inheritdoc ERC721Upgradeable function _mint(address to, uint256 tokenId) internal virtual override { super._mint(to, tokenId); totalSupply++; _fireEvent(INFModuleWithEvents.Events.MINT, tokenId, address(0), to); } /// @dev _transfer override to be able to fire events /// @inheritdoc ERC721Upgradeable function _transfer( address from, address to, uint256 tokenId ) internal virtual override { super._transfer(from, to, tokenId); if (to == address(0xdEaD)) { _fireEvent(INFModuleWithEvents.Events.BURN, tokenId, from, to); } else { _fireEvent(INFModuleWithEvents.Events.TRANSFER, tokenId, from, to); } } /// @dev _burn override to be able to fire event /// @inheritdoc ERC721Upgradeable function _burn(uint256 tokenId) internal virtual override { address owner_ = ownerOf(tokenId); super._burn(tokenId); totalSupply--; _fireEvent( INFModuleWithEvents.Events.BURN, tokenId, owner_, address(0) ); } function _disableModule(address module, bool keepListeners) internal override { // always revoke the minter role when disabling a module _revokeRole(ROLE_MINTER, module); super._disableModule(module, keepListeners); } /// @dev Verifies that we do not create more token ids than the max if set /// @param tokenId the tokenId to verify function _verifyMaxTokenId(uint256 tokenId) internal view { uint256 maxTokenId_ = maxTokenId; require(maxTokenId_ == 0 || tokenId <= maxTokenId_, '!MAX_TOKEN_ID!'); } /// @dev Gets token royalties taking modules into account /// @param tokenId the token id for which we check the royalties function _getTokenRoyalty(uint256 tokenId) internal view override returns (address royaltyRecipient, uint256 royaltyAmount) { (royaltyRecipient, royaltyAmount) = super._getTokenRoyalty(tokenId); // if there are no royalties set either contract wide or per token if (royaltyAmount == 0) { // try to see if the token was created by a module that manages royalties (bool support, address module) = _moduleSupports( tokenId, type(INFModuleWithRoyalties).interfaceId ); if (support) { (royaltyRecipient, royaltyAmount) = INFModuleWithRoyalties( module ).royaltyInfo(tokenId); } } } function _moduleSupports(uint256 tokenId, bytes4 interfaceId) internal view returns (bool support, address module) { module = tokenIdToModule[tokenId]; support = module != address(0) && IERC165Upgradeable(module).supportsInterface(interfaceId); } }
Allows to change the default royalties recipient an editor can call this recipient new default royalties recipient
function setDefaultRoyaltiesRecipient(address recipient) external onlyEditor(msg.sender) { require(!hasPerTokenRoyalties(), '!PER_TOKEN_ROYALTIES!'); _setDefaultRoyaltiesRecipient(recipient); }
1,626,324
pragma solidity 0.5.16; import "./Governable.sol"; contract Controllable is Governable { constructor(address _storage) public Governable(_storage) {} modifier onlyController() { require(store.isController(msg.sender), "Not a controller"); _; } modifier onlyControllerOrGovernance() { require( (store.isController(msg.sender) || store.isGovernance(msg.sender)), "The caller must be controller or governance" ); _; } function controller() public view returns (address) { return store.controller(); } } pragma solidity 0.5.16; import "./Storage.sol"; contract Governable { Storage public store; constructor(address _store) public { require(_store != address(0), "new storage shouldn't be empty"); store = Storage(_store); } modifier onlyGovernance() { require(store.isGovernance(msg.sender), "Not governance"); _; } function setStorage(address _store) public onlyGovernance { require(_store != address(0), "new storage shouldn't be empty"); store = Storage(_store); } function governance() public view returns (address) { return store.governance(); } } pragma solidity 0.5.16; contract Storage { address public governance; address public controller; constructor() public { governance = msg.sender; } modifier onlyGovernance() { require(isGovernance(msg.sender), "Not governance"); _; } function setGovernance(address _governance) public onlyGovernance { require(_governance != address(0), "new governance shouldn't be empty"); governance = _governance; } function setController(address _controller) public onlyGovernance { require(_controller != address(0), "new controller shouldn't be empty"); controller = _controller; } function isGovernance(address account) public view returns (bool) { return account == governance; } function isController(address account) public view returns (bool) { return account == controller; } } pragma solidity 0.5.16; interface IController { // [Grey list] // An EOA can safely interact with the system no matter what. // If you're using Metamask, you're using an EOA. // Only smart contracts may be affected by this grey list. // // This contract will not be able to ban any EOA from the system // even if an EOA is being added to the greyList, he/she will still be able // to interact with the whole system as if nothing happened. // Only smart contracts will be affected by being added to the greyList. // This grey list is only used in Vault.sol, see the code there for reference function greyList(address _target) external view returns (bool); function addVaultAndStrategy(address _vault, address _strategy) external; function forceUnleashed(address _vault) external; function hasVault(address _vault) external returns (bool); function salvage(address _token, uint256 amount) external; function salvageStrategy( address _strategy, address _token, uint256 amount ) external; function notifyFee(address _underlying, uint256 fee) external; function profitSharingNumerator() external view returns (uint256); function profitSharingDenominator() external view returns (uint256); } pragma solidity 0.5.16; interface IStrategy { function unsalvagableTokens(address tokens) external view returns (bool); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function vault() external view returns (address); function withdrawAllToVault() external; function withdrawToVault(uint256 amount) external; function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch() // should only be called by controller function salvage( address recipient, address token, uint256 amount ) external; function forceUnleashed() external; function depositArbCheck() external view returns (bool); } pragma solidity 0.5.16; interface IVault { function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function strategy() external view returns (address); function setStrategy(address _strategy) external; function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external; function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdrawAll() external; function withdraw(uint256 numberOfShares) external; function getPricePerFullShare() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) external view returns (uint256); // force unleash should be callable only by the controller (by the force unleasher) or by governance function forceUnleashed() external; function rebalance() external; } pragma solidity 0.5.16; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IController.sol"; import "../Controllable.sol"; contract ProfitNotifier is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public profitSharingNumerator; uint256 public profitSharingDenominator; address public underlying; event ProfitLog( uint256 oldBalance, uint256 newBalance, uint256 feeAmount, uint256 timestamp ); constructor(address _storage, address _underlying) public Controllable(_storage) { underlying = _underlying; profitSharingNumerator = 0; profitSharingDenominator = 100; require( profitSharingNumerator < profitSharingDenominator, "invalid profit share" ); } function notifyProfit(uint256 oldBalance, uint256 newBalance) internal { if (newBalance > oldBalance && profitSharingNumerator > 0) { uint256 profit = newBalance.sub(oldBalance); uint256 feeAmount = profit.mul(profitSharingNumerator).div( profitSharingDenominator ); emit ProfitLog(oldBalance, newBalance, feeAmount, block.timestamp); IERC20(underlying).safeApprove(controller(), 0); IERC20(underlying).safeApprove(controller(), feeAmount); IController(controller()).notifyFee(underlying, feeAmount); } else { emit ProfitLog(oldBalance, newBalance, 0, block.timestamp); } } function setProfitSharingNumerator(uint256 _profitSharingNumerator) external onlyGovernance { profitSharingNumerator = _profitSharingNumerator; } } pragma solidity 0.5.16; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/Gauge.sol"; import "./interfaces/ICurveFi.sol"; import "./interfaces/yVault.sol"; import "../../uniswap/interfaces/IUniswapV2Router02.sol"; import "../../interfaces/IStrategy.sol"; import "../../interfaces/IVault.sol"; import "../ProfitNotifier.sol"; /** * This strategy is for the yCRV vault, i.e., the underlying token is yCRV. It is not to accept * stable coins. It will farm the CRV crop. For liquidation, it swaps CRV into DAI and uses DAI * to produce yCRV. */ contract CRVStrategyYCRV is IStrategy, ProfitNotifier { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; event Liquidating(uint256 amount); // yDAIyUSDCyUSDTyTUSD (yCRV) address public underlying; address public pool; address public mintr; address public crv; address public curve; address public weth; address public dai; address public yDai; address public uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // these tokens cannot be claimed by the governance mapping(address => bool) public unsalvagableTokens; // our vault holding the underlying token (yCRV) address public vault; uint256 maxUint = uint256(~0); address[] public uniswap_CRV2DAI; modifier restricted() { require( msg.sender == vault || msg.sender == controller() || msg.sender == governance(), "The sender has to be the controller, governance, or vault" ); _; } constructor( address _storage, address _vault, address _underlying, address _gauge, address _mintr, address _crv, address _curve, address _weth, address _dai, address _yDai, address _uniswap ) public ProfitNotifier(_storage, _dai) { require( IVault(_vault).underlying() == _underlying, "vault does not support yCRV" ); vault = _vault; underlying = _underlying; pool = _gauge; mintr = _mintr; crv = _crv; curve = _curve; weth = _weth; dai = _dai; yDai = _yDai; uni = _uniswap; uniswap_CRV2DAI = [crv, weth, dai]; // set these tokens to be not salvageable unsalvagableTokens[underlying] = true; unsalvagableTokens[crv] = true; } function depositArbCheck() public view returns (bool) { return true; } /** * Salvages a token. We should not be able to salvage CRV and yCRV (underlying). */ function salvage( address recipient, address token, uint256 amount ) public onlyGovernance { // To make sure that governance cannot come in and take away the coins require( !unsalvagableTokens[token], "token is defined as not salvageable" ); IERC20(token).safeTransfer(recipient, amount); } /** * Withdraws yCRV from the investment pool that mints crops. */ function withdrawYCrvFromPool(uint256 amount) internal { Gauge(pool).withdraw( Math.min(Gauge(pool).balanceOf(address(this)), amount) ); } /** * Withdraws the yCRV tokens to the pool in the specified amount. */ function withdrawToVault(uint256 amountUnderlying) external restricted { withdrawYCrvFromPool(amountUnderlying); if (IERC20(underlying).balanceOf(address(this)) < amountUnderlying) { claimAndLiquidateCrv(); } uint256 toTransfer = Math.min( IERC20(underlying).balanceOf(address(this)), amountUnderlying ); IERC20(underlying).safeTransfer(vault, toTransfer); } /** * Withdraws all the yCRV tokens to the pool. */ function withdrawAllToVault() external restricted { claimAndLiquidateCrv(); withdrawYCrvFromPool(maxUint); uint256 balance = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransfer(vault, balance); } /** * Invests all the underlying yCRV into the pool that mints crops (CRV_. */ function investAllUnderlying() public restricted { uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { IERC20(underlying).safeApprove(pool, 0); IERC20(underlying).safeApprove(pool, underlyingBalance); Gauge(pool).deposit(underlyingBalance); } } /** * Claims the CRV crop, converts it to DAI on Uniswap, and then uses DAI to mint yCRV using the * Curve protocol. */ function claimAndLiquidateCrv() internal { Mintr(mintr).mint(pool); // claiming rewards and sending them to the master strategy uint256 crvBalance = IERC20(crv).balanceOf(address(this)); emit Liquidating(crvBalance); if (crvBalance > 0) { uint256 daiBalanceBefore = IERC20(dai).balanceOf(address(this)); IERC20(crv).safeApprove(uni, 0); IERC20(crv).safeApprove(uni, crvBalance); // we can accept 1 as the minimum because this will be called only by a trusted worker IUniswapV2Router02(uni).swapExactTokensForTokens( crvBalance, 1, uniswap_CRV2DAI, address(this), block.timestamp ); // now we have DAI // pay fee before making yCRV notifyProfit( daiBalanceBefore, IERC20(dai).balanceOf(address(this)) ); // liquidate if there is any DAI left if (IERC20(dai).balanceOf(address(this)) > 0) { yCurveFromDai(); } // now we have yCRV } } /** * Claims and liquidates CRV into yCRV, and then invests all underlying. */ function forceUnleashed() public restricted { claimAndLiquidateCrv(); investAllUnderlying(); } /** * Investing all underlying. */ function investedUnderlyingBalance() public view returns (uint256) { return Gauge(pool).balanceOf(address(this)).add( IERC20(underlying).balanceOf(address(this)) ); } /** * Converts all DAI to yCRV using the CRV protocol. */ function yCurveFromDai() internal { uint256 daiBalance = IERC20(dai).balanceOf(address(this)); if (daiBalance > 0) { IERC20(dai).safeApprove(yDai, 0); IERC20(dai).safeApprove(yDai, daiBalance); yERC20(yDai).deposit(daiBalance); } uint256 yDaiBalance = IERC20(yDai).balanceOf(address(this)); if (yDaiBalance > 0) { IERC20(yDai).safeApprove(curve, 0); IERC20(yDai).safeApprove(curve, yDaiBalance); // we can accept 0 as minimum, this will be called only by trusted roles uint256 minimum = 0; ICurveFi(curve).add_liquidity([yDaiBalance, 0, 0, 0], minimum); } // now we have yCRV } } pragma solidity 0.5.16; import "./CRVStrategyYCRV.sol"; /** * This strategy is for the yCRV vault, i.e., the underlying token is yCRV. It is not to accept * stable coins. It will farm the CRV crop. For liquidation, it swaps CRV into DAI and uses DAI * to produce yCRV. */ contract CRVStrategyYCRVMainnet is CRVStrategyYCRV { constructor(address _storage, address _vault) public CRVStrategyYCRV( _storage, _vault, address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8), // yCRV underlying address(0xFA712EE4788C042e2B7BB55E6cb8ec569C4530c1), // _gauge address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0), // _mintr address(0xD533a949740bb3306d119CC777fa900bA034cd52), // _crv address(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51), // _curve address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2), // _weth address(0x6B175474E89094C44Da98b954EedeAC495271d0F), // _dai address(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01), // _yDai address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) // _uniswap ) {} } pragma solidity 0.5.16; interface Gauge { function deposit(uint256) external; function balanceOf(address) external view returns (uint256); function withdraw(uint256) external; function user_checkpoint(address) external; } interface VotingEscrow { function create_lock(uint256 v, uint256 time) external; function increase_amount(uint256 _value) external; function increase_unlock_time(uint256 _unlock_time) external; function withdraw() external; } interface Mintr { function mint(address) external; } pragma solidity 0.5.16; interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[4] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function calc_token_amount(uint256[4] calldata amounts, bool deposit) external view returns (uint256); } pragma solidity 0.5.16; interface yERC20 { function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function getPricePerFullShare() external view returns (uint256); } pragma solidity >=0.5.0; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } pragma solidity >=0.5.0; import "./IUniswapV2Router01.sol"; interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } 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; } } 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); } pragma solidity ^0.5.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 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"); } } } 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"); } }
Investing all underlying./
function investedUnderlyingBalance() public view returns (uint256) { return Gauge(pool).balanceOf(address(this)).add( IERC20(underlying).balanceOf(address(this)) ); }
10,033,053
./full_match/5/0x5E37A79cBFBC036467e1295d0A00Cc8c73051580/sources/@reality.eth/contracts/development/contracts/RealityETH_ERC20-3.0.sol
Update the current bond level, if there's a bond (ie anything except arbitration)
function _addAnswerToHistory(bytes32 question_id, bytes32 answer_or_commitment_id, address answerer, uint256 bond, bool is_commitment) internal { bytes32 new_history_hash = keccak256(abi.encodePacked(questions[question_id].history_hash, answer_or_commitment_id, bond, answerer, is_commitment)); if (bond > 0) { questions[question_id].bond = bond; } questions[question_id].history_hash = new_history_hash; emit LogNewAnswer(answer_or_commitment_id, question_id, new_history_hash, answerer, bond, block.timestamp, is_commitment); }
1,897,813
./partial_match/1/0x18B32bC20951b0eaE36247Aa5C8C22A77244d6cd/sources/contracts/ERC721X.sol
Approve `to` to operate on `tokenId` Emits a {Approval} event./
function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); }
4,202,206
// SPDX-License-Identifier: MIT // SYS 64738 // Version 2.0 // Author: 0xTycoon // Contributor: Alphasoup <twitter: alphasoups> // Special Thanks: straybits1, cryptopunkart, cyounessi1, ethereumdegen, Punk7572, sherone.eth, // songadaymann, Redlioneye.eth, tw1tte7, PabloPunkasso, Kaprekar_Punk, aradtski, // phantom_scribbs, Cryptopapa.eth, johnhenderson, thekriskay, PerfectoidPeter, // uxt_exe, 0xUnicorn, dansickles.eth, Blon Dee#9649, VRPunk1, Don Seven Slices, hogo.eth, // GeoCities#5700, "HP OfficeJet Pro 9015e #2676", gigiuz#0061, danpolko.eth, mariano.eth, // 0xfoobar, jakerockland, Mudit__Gupta, BokkyPooBah, 0xaaby.eth, and // everyone at the discord, and all the awesome people who gave feedback for this project! // Greetings to: Punk3395, foxthepunk, bushleaf.eth, 570KylΞ.eth, bushleaf.eth, Tokyolife, Joshuad.eth (1641), // markchesler_coinwitch, decideus.eth, zachologylol, punk8886, jony_bee, nfttank, DolAtoR, punk8886 // DonJon.eth, kilifibaobab, joked507, cryptoed#3040, DroScott#7162, 0xAllen.eth, Tschuuuly#5158, // MetasNomadic#0349, punk8653, NittyB, heygareth.eth, Aaru.eth, robertclarke.eth, Acmonides#6299, // Gustavus99 (1871), Foobazzler // Repo: github.com/0xTycoon/punksceo pragma solidity ^0.8.11; //import "./safemath.sol"; // don't need since v0.8 //import "./ceo.sol"; //import "hardhat/console.sol"; /* PUNKS CEO (and "Cigarette" token) WEB: https://punksceo.eth.limo / https://punksceo.eth.link IPFS: See content hash record for punksceo.eth Token Address: cigtoken.eth , - ~ ~ ~ - , , ' ' , , 🚬 , , 🚬 , , 🚬 , , 🚬 , , ============= , , ||█ , , ============= , , , ' ' - , _ _ _ , ' ### THE RULES OF THE GAME 1. Anybody can buy the CEO title at any time using Cigarettes. (The CEO of all cryptopunks) 2. When buying the CEO title, you must nominate a punk, set the price and pre-pay the tax. 3. The CEO title can be bought from the existing CEO at any time. 4. To remain a CEO, a daily tax needs to be paid. 5. The tax is 0.1% of the price to buy the CEO title, to be charged per epoch. 6. The CEO can be removed if they fail to pay the tax. A reward of CIGs is paid to the whistleblower. 7. After Removing a CEO: A dutch auction is held, where the price will decrease 10% every half-an-epoch. 8. The price can be changed by the CEO at any time. (Once per block) 9. An epoch is 7200 blocks. 10. All the Cigarettes from the sale are burned. 11. All tax is burned 12. After buying the CEO title, the old CEO will get their unspent tax deposit refunded ### CEO perk 13. The CEO can increase or decrease the CIG farming block reward by 20% every 2nd epoch! However, note that the issuance can never be more than 1000 CIG per block, also never under 0.0001 CIG. 14. THE CEO gets to hold a NFT in their wallet. There will only be ever 1 this NFT. The purpose of this NFT is so that everyone can see that they are the CEO. IMPORTANT: This NFT will be revoked once the CEO title changes. Also, the NFT cannot be transferred by the owner, the only way to transfer is for someone else to buy the CEO title! (Think of this NFT as similar to a "title belt" in boxing.) END * states * 0 = initial * 1 = CEO reigning * 2 = Dutch auction * 3 = Migration Notes: It was decided that whoever buys the CEO title does not have to hold a punk and can nominate any punk they wish. This is because some may hold their punks in cold storage, plus checking ownership costs additional gas. Besides, CEOs are usually appointed by the board. Credits: - LP Staking based on code from SushiSwap's MasterChef.sol - ERC20 & SafeMath based on lib from OpenZeppelin */ contract Cig { //using SafeMath for uint256; // no need since Solidity 0.8 string public constant name = "Cigarette Token"; string public constant symbol = "CIG"; uint8 public constant decimals = 18; uint256 public totalSupply = 0; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // UserInfo keeps track of user LP deposits and withdrawals struct UserInfo { uint256 deposit; // How many LP tokens the user has deposited. uint256 rewardDebt; // keeps track of how much reward was paid out } mapping(address => UserInfo) public farmers; // keeps track of UserInfo for each staking address with own pool mapping(address => UserInfo) public farmersMasterchef; // keeps track of UserInfo for each staking address with masterchef pool mapping(address => uint256) public wBal; // keeps tracked of wrapped old cig address public admin; // admin is used for deployment, burned after ILiquidityPoolERC20 public lpToken; // lpToken is the address of LP token contract that's being staked. uint256 public lastRewardBlock; // Last block number that cigarettes distribution occurs. uint256 public accCigPerShare; // Accumulated cigarettes per share, times 1e12. See below. uint256 public masterchefDeposits; // How much has been deposited onto the masterchef contract uint256 public cigPerBlock; // CIGs per-block rewarded and split with LPs bytes32 public graffiti; // a 32 character graffiti set when buying a CEO ICryptoPunk public punks; // a reference to the CryptoPunks contract event Deposit(address indexed user, uint256 amount); // when depositing LP tokens to stake event Harvest(address indexed user, address to, uint256 amount);// when withdrawing LP tokens form staking event Withdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed event EmergencyWithdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed event ChefDeposit(address indexed user, uint256 amount); // when depositing LP tokens to stake event ChefWithdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed event RewardUp(uint256 reward, uint256 upAmount); // when cigPerBlock is increased event RewardDown(uint256 reward, uint256 downAmount); // when cigPerBlock is decreased event Claim(address indexed owner, uint indexed punkIndex, uint256 value); // when a punk is claimed mapping(uint => bool) public claims; // keep track of claimed punks modifier onlyAdmin { require( msg.sender == admin, "Only admin can call this" ); _; } uint256 constant MIN_PRICE = 1e12; // 0.000001 CIG uint256 constant CLAIM_AMOUNT = 100000 ether; // claim amount for each punk uint256 constant MIN_REWARD = 1e14; // minimum block reward of 0.0001 CIG (1e14 wei) uint256 constant MAX_REWARD = 1000 ether; // maximum block reward of 1000 CIG uint256 constant STARTING_REWARDS = 512 ether;// starting rewards at end of migration address public The_CEO; // address of CEO uint public CEO_punk_index; // which punk id the CEO is using uint256 public CEO_price = 50000 ether; // price to buy the CEO title uint256 public CEO_state; // state has 3 states, described above. uint256 public CEO_tax_balance; // deposit to be used to pay the CEO tax uint256 public taxBurnBlock; // The last block when the tax was burned uint256 public rewardsChangedBlock; // which block was the last reward increase / decrease uint256 private immutable CEO_epoch_blocks; // secs per day divided by 12 (86400 / 12), assuming 12 sec blocks uint256 private immutable CEO_auction_blocks; // 3600 blocks // NewCEO 0x09b306c6ea47db16bdf4cc36f3ea2479af494cd04b4361b6485d70f088658b7e event NewCEO(address indexed user, uint indexed punk_id, uint256 new_price, bytes32 graffiti); // when a CEO is bought // TaxDeposit 0x2ab3b3b53aa29a0599c58f343221e29a032103d015c988fae9a5cdfa5c005d9d event TaxDeposit(address indexed user, uint256 amount); // when tax is deposited // RevenueBurned 0x1b1be00a9ca19f9c14f1ca5d16e4aba7d4dd173c2263d4d8a03484e1c652c898 event RevenueBurned(address indexed user, uint256 amount); // when tax is burned // TaxBurned 0x9ad3c710e1cc4e96240264e5d3cd5aeaa93fd8bd6ee4b11bc9be7a5036a80585 event TaxBurned(address indexed user, uint256 amount); // when tax is burned // CEODefaulted b69f2aeff650d440d3e7385aedf764195cfca9509e33b69e69f8c77cab1e1af1 event CEODefaulted(address indexed called_by, uint256 reward); // when CEO defaulted on tax // CEOPriceChange 0x10c342a321267613a25f77d4273d7f2688bef174a7214bc3dde44b31c5064ff6 event CEOPriceChange(uint256 price); // when CEO changed price modifier onlyCEO { require( msg.sender == The_CEO, "only CEO can call this" ); _; } IRouterV2 private immutable V2ROUTER; // address of router used to get the price quote ICEOERC721 private immutable The_NFT; // reference to the CEO NFT token address private immutable MASTERCHEF_V2; // address pointing to SushiSwap's MasterChefv2 contract IOldCigtoken private immutable OC; // Old Contract /** * @dev constructor * @param _cigPerBlock Number of CIG tokens rewarded per block * @param _punks address of the cryptopunks contract * @param _CEO_epoch_blocks how many blocks between each epochs * @param _CEO_auction_blocks how many blocks between each auction discount * @param _CEO_price starting price to become CEO (in CIG) * @param _graffiti bytes32 initial graffiti message * @param _NFT address pointing to the NFT contract * @param _V2ROUTER address pointing to the SushiSwap router * @param _OC address pointing to the original Cig Token contract * @param _MASTERCHEF_V2 address for the sushi masterchef v2 contract */ constructor( uint256 _cigPerBlock, address _punks, uint _CEO_epoch_blocks, uint _CEO_auction_blocks, uint256 _CEO_price, bytes32 _graffiti, address _NFT, address _V2ROUTER, address _OC, uint256 _migration_epochs, address _MASTERCHEF_V2 ) { cigPerBlock = _cigPerBlock; admin = msg.sender; // the admin key will be burned after deployment punks = ICryptoPunk(_punks); CEO_epoch_blocks = _CEO_epoch_blocks; CEO_auction_blocks = _CEO_auction_blocks; CEO_price = _CEO_price; graffiti = _graffiti; The_NFT = ICEOERC721(_NFT); V2ROUTER = IRouterV2(_V2ROUTER); OC = IOldCigtoken(_OC); lastRewardBlock = block.number + (CEO_epoch_blocks * _migration_epochs); // set the migration window end MASTERCHEF_V2 = _MASTERCHEF_V2; CEO_state = 3; // begin in migration state } /** * @dev buyCEO allows anybody to be the CEO * @param _max_spend the total CIG that can be spent * @param _new_price the new price for the punk (in CIG) * @param _tax_amount how much to pay in advance (in CIG) * @param _punk_index the id of the punk 0-9999 * @param _graffiti a little message / ad from the buyer */ function buyCEO( uint256 _max_spend, uint256 _new_price, uint256 _tax_amount, uint256 _punk_index, bytes32 _graffiti ) external { require (CEO_state != 3); // disabled in in migration state if (CEO_state == 1 && (taxBurnBlock != block.number)) { _burnTax(); // _burnTax can change CEO_state to 2 } if (CEO_state == 2) { // Auction state. The price goes down 10% every `CEO_auction_blocks` blocks CEO_price = _calcDiscount(); } require (CEO_price + _tax_amount <= _max_spend, "overpaid"); // prevent CEO over-payment require (_new_price >= MIN_PRICE, "price 2 smol"); // price cannot be under 0.000001 CIG require (_punk_index <= 9999, "invalid punk"); // validate the punk index require (_tax_amount >= _new_price / 1000, "insufficient tax" ); // at least %0.1 fee paid for 1 epoch transfer(address(this), CEO_price); // pay for the CEO title _burn(address(this), CEO_price); // burn the revenue emit RevenueBurned(msg.sender, CEO_price); _returnDeposit(The_CEO, CEO_tax_balance); // return deposited tax back to old CEO transfer(address(this), _tax_amount); // deposit tax (reverts if not enough) CEO_tax_balance = _tax_amount; // store the tax deposit amount _transferNFT(The_CEO, msg.sender); // yank the NFT to the new CEO CEO_price = _new_price; // set the new price CEO_punk_index = _punk_index; // store the punk id The_CEO = msg.sender; // store the CEO's address taxBurnBlock = block.number; // store the block number // (tax may not have been burned if the // previous state was 0) CEO_state = 1; graffiti = _graffiti; emit TaxDeposit(msg.sender, _tax_amount); emit NewCEO(msg.sender, _punk_index, _new_price, _graffiti); } /** * @dev _returnDeposit returns the tax deposit back to the CEO * @param _to address The address which you want to transfer to * remember to update CEO_tax_balance after calling this */ function _returnDeposit( address _to, uint256 _amount ) internal { if (_amount == 0) { return; } balanceOf[address(this)] = balanceOf[address(this)] - _amount; balanceOf[_to] = balanceOf[_to] + _amount; emit Transfer(address(this), _to, _amount); //CEO_tax_balance = 0; // can be omitted since value gets overwritten by caller } /** * @dev transfer the NFT to a new wallet */ function _transferNFT(address _oldCEO, address _newCEO) internal { The_NFT.transferFrom(_oldCEO, _newCEO, 0); } /** * @dev depositTax pre-pays tax for the existing CEO. * It may also burn any tax debt the CEO may have. * @param _amount amount of tax to pre-pay */ function depositTax(uint256 _amount) external onlyCEO { require (CEO_state == 1, "no CEO"); if (_amount > 0) { transfer(address(this), _amount); // place the tax on deposit CEO_tax_balance = CEO_tax_balance + _amount; // record the balance emit TaxDeposit(msg.sender, _amount); } if (taxBurnBlock != block.number) { _burnTax(); // settle any tax debt taxBurnBlock = block.number; } } /** * @dev burnTax is called to burn tax. * It removes the CEO if tax is unpaid. * 1. deduct tax, update last update * 2. if not enough tax, remove & begin auction * 3. reward the caller by minting a reward from the amount indebted * A Dutch auction begins where the price decreases 10% every hour. */ function burnTax() external { if (taxBurnBlock == block.number) return; if (CEO_state == 1) { _burnTax(); taxBurnBlock = block.number; } } /** * @dev _burnTax burns any tax debt. Boots the CEO if defaulted, paying a reward to the caller */ function _burnTax() internal { // calculate tax per block (tpb) uint256 tpb = CEO_price / 1000 / CEO_epoch_blocks; // 0.1% per epoch uint256 debt = (block.number - taxBurnBlock) * tpb; if (CEO_tax_balance !=0 && CEO_tax_balance >= debt) { // Does CEO have enough deposit to pay debt? CEO_tax_balance = CEO_tax_balance - debt; // deduct tax _burn(address(this), debt); // burn the tax emit TaxBurned(msg.sender, debt); } else { // CEO defaulted uint256 default_amount = debt - CEO_tax_balance; // calculate how much defaulted _burn(address(this), CEO_tax_balance); // burn the tax emit TaxBurned(msg.sender, CEO_tax_balance); CEO_state = 2; // initiate a Dutch auction. CEO_tax_balance = 0; _transferNFT(The_CEO, address(this)); // This contract holds the NFT temporarily The_CEO = address(this); // This contract is the "interim CEO" _mint(msg.sender, default_amount); // reward the caller for reporting tax default emit CEODefaulted(msg.sender, default_amount); } } /** * @dev setPrice changes the price for the CEO title. * @param _price the price to be paid. The new price most be larger tan MIN_PRICE and not default on debt */ function setPrice(uint256 _price) external onlyCEO { require(CEO_state == 1, "No CEO in charge"); require (_price >= MIN_PRICE, "price 2 smol"); require (CEO_tax_balance >= _price / 1000, "price would default"); // need at least 0.1% for tax if (block.number != taxBurnBlock) { _burnTax(); taxBurnBlock = block.number; } // The state is 1 if the CEO hasn't defaulted on tax if (CEO_state == 1) { CEO_price = _price; // set the new price emit CEOPriceChange(_price); } } /** * @dev rewardUp allows the CEO to increase the block rewards by %20 * Can only be called by the CEO every 2 epochs * @return _amount increased by */ function rewardUp() external onlyCEO returns (uint256) { require(CEO_state == 1, "No CEO in charge"); require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks"); require (cigPerBlock < MAX_REWARD, "reward already max"); rewardsChangedBlock = block.number; uint256 _amount = cigPerBlock / 5; // %20 uint256 _new_reward = cigPerBlock + _amount; if (_new_reward > MAX_REWARD) { _amount = MAX_REWARD - cigPerBlock; _new_reward = MAX_REWARD; // cap } cigPerBlock = _new_reward; emit RewardUp(_new_reward, _amount); return _amount; } /** * @dev rewardDown decreases the block rewards by 20% * Can only be called by the CEO every 2 epochs */ function rewardDown() external onlyCEO returns (uint256) { require(CEO_state == 1, "No CEO in charge"); require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks"); require(cigPerBlock > MIN_REWARD, "reward already low"); rewardsChangedBlock = block.number; uint256 _amount = cigPerBlock / 5; // %20 uint256 _new_reward = cigPerBlock - _amount; if (_new_reward < MIN_REWARD) { _amount = cigPerBlock - MIN_REWARD; _new_reward = MIN_REWARD; // limit } cigPerBlock = _new_reward; emit RewardDown(_new_reward, _amount); return _amount; } /** * @dev _calcDiscount calculates the discount for the CEO title based on how many blocks passed */ function _calcDiscount() internal view returns (uint256) { unchecked { uint256 d = (CEO_price / 10) // 10% discount // multiply by the number of discounts accrued * ((block.number - taxBurnBlock) / CEO_auction_blocks); if (d > CEO_price) { // overflow assumed, reset to MIN_PRICE return MIN_PRICE; } uint256 price = CEO_price - d; if (price < MIN_PRICE) { price = MIN_PRICE; } return price; } } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Information used by the UI 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev getStats helps to fetch some stats for the GUI in a single web3 call * @param _user the address to return the report for * @return uint256[27] the stats * @return address of the current CEO * @return bytes32 Current graffiti */ function getStats(address _user) external view returns(uint256[] memory, address, bytes32, uint112[] memory) { uint[] memory ret = new uint[](27); uint112[] memory reserves = new uint112[](2); uint256 tpb = (CEO_price / 1000) / (CEO_epoch_blocks); // 0.1% per epoch uint256 debt = (block.number - taxBurnBlock) * tpb; uint256 price = CEO_price; UserInfo memory info = farmers[_user]; if (CEO_state == 2) { price = _calcDiscount(); } ret[0] = CEO_state; ret[1] = CEO_tax_balance; ret[2] = taxBurnBlock; // the block number last tax burn ret[3] = rewardsChangedBlock; // the block of the last staking rewards change ret[4] = price; // price of the CEO title ret[5] = CEO_punk_index; // punk ID of CEO ret[6] = cigPerBlock; // staking reward per block ret[7] = totalSupply; // total supply of CIG if (address(lpToken) != address(0)) { ret[8] = lpToken.balanceOf(address(this)); // Total LP staking ret[16] = lpToken.balanceOf(_user); // not staked by user ret[17] = pendingCig(_user); // pending harvest (reserves[0], reserves[1], ) = lpToken.getReserves(); // uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ret[18] = V2ROUTER.getAmountOut(1 ether, uint(reserves[0]), uint(reserves[1])); // CIG price in ETH if (isContract(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2))) { // are we on mainnet? ILiquidityPoolERC20 ethusd = ILiquidityPoolERC20(address(0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f)); // sushi DAI-WETH pool uint112 r0; uint112 r1; (r0, r1, ) = ethusd.getReserves(); // get the price of ETH in USD ret[19] = V2ROUTER.getAmountOut(1 ether, uint(r0), uint(r1)); // ETH price in USD } ret[22] = lpToken.totalSupply(); // total supply } ret[9] = block.number; // current block number ret[10] = tpb; // "tax per block" (tpb) ret[11] = debt; // tax debt accrued ret[12] = lastRewardBlock; // the block of the last staking rewards payout update ret[13] = info.deposit; // amount of LP tokens staked by user ret[14] = info.rewardDebt; // amount of rewards paid out ret[15] = balanceOf[_user]; // amount of CIG held by user ret[20] = accCigPerShare; // Accumulated cigarettes per share ret[21] = balanceOf[address(punks)]; // amount of CIG to be claimed ret[23] = wBal[_user]; // wrapped cig balance ret[24] = OC.balanceOf(_user); // balance of old cig in old isContract ret[25] = OC.allowance(_user, address(this));// is old contract approved (ret[26], ) = OC.userInfo(_user); // old contract stake bal return (ret, The_CEO, graffiti, reserves); } /** * @dev Returns true if `account` is a contract. * * credits https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol */ function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Token distribution and farming stuff 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev isClaimed checks to see if a punk was claimed * @param _punkIndex the punk number */ function isClaimed(uint256 _punkIndex) external view returns (bool) { if (claims[_punkIndex]) { return true; } if (OC.claims(_punkIndex)) { return true; } return false; } /** * Claim claims the initial CIG airdrop using a punk * @param _punkIndex the index of the punk, number between 0-9999 */ function claim(uint256 _punkIndex) external returns(bool) { require (CEO_state != 3, "invalid state"); // disabled in migration state require (_punkIndex <= 9999, "invalid punk"); require(claims[_punkIndex] == false, "punk already claimed"); require(OC.claims(_punkIndex) == false, "punk already claimed"); // claimed in old contract require(msg.sender == punks.punkIndexToAddress(_punkIndex), "punk 404"); claims[_punkIndex] = true; balanceOf[address(punks)] = balanceOf[address(punks)] - CLAIM_AMOUNT; // deduct from the punks contract balanceOf[msg.sender] = balanceOf[msg.sender] + CLAIM_AMOUNT; // deposit to the caller emit Transfer(address(punks), msg.sender, CLAIM_AMOUNT); emit Claim(msg.sender, _punkIndex, CLAIM_AMOUNT); return true; } /** * @dev Gets the LP supply, with masterchef deposits taken into account. */ function stakedlpSupply() public view returns(uint256) { return lpToken.balanceOf(address(this)) + masterchefDeposits; } /** * @dev update updates the accCigPerShare value and mints new CIG rewards to be distributed to LP stakers * Credits go to MasterChef.sol * Modified the original by removing poolInfo as there is only a single pool * Removed totalAllocPoint and pool.allocPoint * pool.lastRewardBlock moved to lastRewardBlock * There is no need for getMultiplier (rewards are adjusted by the CEO) * */ function update() public { if (block.number <= lastRewardBlock) { return; } uint256 supply = stakedlpSupply(); if (supply == 0) { lastRewardBlock = block.number; return; } // mint some new cigarette rewards to be distributed uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock; _mint(address(this), cigReward); accCigPerShare = accCigPerShare + ( cigReward * 1e12 / supply ); lastRewardBlock = block.number; } /** * @dev pendingCig displays the amount of cig to be claimed * @param _user the address to report */ function pendingCig(address _user) view public returns (uint256) { uint256 _acps = accCigPerShare; // accumulated cig per share UserInfo storage user = farmers[_user]; uint256 supply = stakedlpSupply(); if (block.number > lastRewardBlock && supply != 0) { uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock; _acps = _acps + ( cigReward * 1e12 / supply ); } return (user.deposit * _acps / 1e12) - user.rewardDebt; } /** * @dev userInfo is added for compatibility with the Snapshot.org interface. */ function userInfo(uint256, address _user) view external returns (uint256, uint256 depositAmount) { return (0,farmers[_user].deposit + farmersMasterchef[_user].deposit); } /** * @dev deposit deposits LP tokens to be staked. * @param _amount the amount of LP tokens to deposit. Assumes this contract has been approved for the _amount. */ function deposit(uint256 _amount) external { require(_amount != 0, "You cannot deposit only 0 tokens"); // Check how many bytes UserInfo storage user = farmers[msg.sender]; update(); _deposit(user, _amount); require(lpToken.transferFrom( address(msg.sender), address(this), _amount )); emit Deposit(msg.sender, _amount); } function _deposit(UserInfo storage _user, uint256 _amount) internal { _user.deposit += _amount; _user.rewardDebt += _amount * accCigPerShare / 1e12; } /** * @dev withdraw takes out the LP tokens * @param _amount the amount to withdraw */ function withdraw(uint256 _amount) external { UserInfo storage user = farmers[msg.sender]; update(); /* harvest beforehand, so _withdraw can safely decrement their reward count */ _harvest(user, msg.sender); _withdraw(user, _amount); /* Interact */ require(lpToken.transferFrom( address(this), address(msg.sender), _amount )); emit Withdraw(msg.sender, _amount); } /** * @dev Internal withdraw, updates internal accounting after withdrawing LP * @param _amount to subtract */ function _withdraw(UserInfo storage _user, uint256 _amount) internal { require(_user.deposit >= _amount, "Balance is too low"); _user.deposit -= _amount; uint256 _rewardAmount = _amount * accCigPerShare / 1e12; _user.rewardDebt -= _rewardAmount; } /** * @dev harvest redeems pending rewards & updates state */ function harvest() external { UserInfo storage user = farmers[msg.sender]; update(); _harvest(user, msg.sender); } /** * @dev Internal harvest * @param _to the amount to harvest */ function _harvest(UserInfo storage _user, address _to) internal { uint256 potentialValue = (_user.deposit * accCigPerShare / 1e12); uint256 delta = potentialValue - _user.rewardDebt; safeSendPayout(_to, delta); // Recalculate their reward debt now that we've given them their reward _user.rewardDebt = _user.deposit * accCigPerShare / 1e12; emit Harvest(msg.sender, _to, delta); } /** * @dev safeSendPayout, just in case if rounding error causes pool to not have enough CIGs. * @param _to recipient address * @param _amount the value to send */ function safeSendPayout(address _to, uint256 _amount) internal { uint256 cigBal = balanceOf[address(this)]; require(cigBal >= _amount, "insert more tobacco leaves..."); unchecked { balanceOf[address(this)] = balanceOf[address(this)] - _amount; balanceOf[_to] = balanceOf[_to] + _amount; } emit Transfer(address(this), _to, _amount); } /** * @dev emergencyWithdraw does a withdraw without caring about rewards. EMERGENCY ONLY. */ function emergencyWithdraw() external { UserInfo storage user = farmers[msg.sender]; uint256 amount = user.deposit; user.deposit = 0; user.rewardDebt = 0; // Interact require(lpToken.transfer( address(msg.sender), amount )); emit EmergencyWithdraw(msg.sender, amount); } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Migration 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev renounceOwnership burns the admin key, so this contract is unruggable */ function renounceOwnership() external onlyAdmin { admin = address(0); } /** * @dev setStartingBlock sets the starting block for LP staking rewards * Admin only, used only for initial configuration. * @param _startBlock the block to start rewards for */ function setStartingBlock(uint256 _startBlock) external onlyAdmin { lastRewardBlock = _startBlock; } /** * @dev setPool address to an LP pool. Only Admin. (used only in testing/deployment) */ function setPool(ILiquidityPoolERC20 _addr) external onlyAdmin { require(address(lpToken) == address(0), "pool already set"); lpToken = _addr; } /** * @dev setReward sets the reward. Admin only (used only in testing/deployment) */ function setReward(uint256 _value) public onlyAdmin { cigPerBlock = _value; } /** * @dev migrationComplete completes the migration */ function migrationComplete() external { require (CEO_state == 3); require (OC.CEO_state() == 1); require (block.number > lastRewardBlock, "cannot end migration yet"); CEO_state = 1; // CEO is in charge state OC.burnTax(); // before copy, burn the old CEO's tax /* copy the state over to this contract */ _mint(address(punks), OC.balanceOf(address(punks))); // CIG to be set aside for the remaining airdrop uint256 taxDeposit = OC.CEO_tax_balance(); The_CEO = OC.The_CEO(); // copy the CEO if (taxDeposit > 0) { // copy the CEO's outstanding tax _mint(address(this), taxDeposit); // mint tax that CEO had locked in previous contract (cannot be migrated) CEO_tax_balance = taxDeposit; } taxBurnBlock = OC.taxBurnBlock(); CEO_price = OC.CEO_price(); graffiti = OC.graffiti(); CEO_punk_index = OC.CEO_punk_index(); cigPerBlock = STARTING_REWARDS; // set special rewards lastRewardBlock = OC.lastRewardBlock();// start rewards rewardsChangedBlock = OC.rewardsChangedBlock(); /* Historical records */ _transferNFT( address(0), address(0x1e32a859d69dde58d03820F8f138C99B688D132F) ); emit NewCEO( address(0x1e32a859d69dde58d03820F8f138C99B688D132F), 0x00000000000000000000000000000000000000000000000000000000000015c9, 0x000000000000000000000000000000000000000000007618fa42aac317900000, 0x41732043454f2049206465636c617265204465632032322050756e6b20446179 ); _transferNFT( address(0x1e32a859d69dde58d03820F8f138C99B688D132F), address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d) ); emit NewCEO( address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d), 0x0000000000000000000000000000000000000000000000000000000000000343, 0x00000000000000000000000000000000000000000001a784379d99db42000000, 0x40617a756d615f626974636f696e000000000000000000000000000000000000 ); _transferNFT( address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d), address(0x4947DA4bEF9D79bc84bD584E6c12BfFa32D1bEc8) ); emit NewCEO( address(0x4947DA4bEF9D79bc84bD584E6c12BfFa32D1bEc8), 0x00000000000000000000000000000000000000000000000000000000000007fa, 0x00000000000000000000000000000000000000000014adf4b7320334b9000000, 0x46697273742070756e6b7320746f6b656e000000000000000000000000000000 ); } /** * @dev wrap wraps old CIG and issues new CIG 1:1 * @param _value how much old cig to wrap */ function wrap(uint256 _value) external { require (CEO_state == 3); OC.transferFrom(msg.sender, address(this), _value); // transfer old cig to here _mint(msg.sender, _value); // give user new cig wBal[msg.sender] = wBal[msg.sender] + _value; // record increase of wrapped old cig for caller } /** * @dev unwrap unwraps old CIG and burns new CIG 1:1 */ function unwrap(uint256 _value) external { require (CEO_state == 3); _burn(msg.sender, _value); // burn new cig OC.transfer(msg.sender, _value); // give back old cig wBal[msg.sender] = wBal[msg.sender] - _value; // record decrease of wrapped old cig for caller } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 ERC20 Token stuff 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev burn some tokens * @param _from The address to burn from * @param _amount The amount to burn */ function _burn(address _from, uint256 _amount) internal { balanceOf[_from] = balanceOf[_from] - _amount; totalSupply = totalSupply - _amount; emit Transfer(_from, address(0), _amount); } /** * @dev mint new tokens * @param _to The address to mint to. * @param _amount The amount to be minted. */ function _mint(address _to, uint256 _amount) internal { require(_to != address(0), "ERC20: mint to the zero address"); unchecked { totalSupply = totalSupply + _amount; balanceOf[_to] = balanceOf[_to] + _amount; } emit Transfer(address(0), _to, _amount); } /** * @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(_value <= balanceOf[msg.sender], "value exceeds balance"); // SafeMath already checks this balanceOf[msg.sender] = balanceOf[msg.sender] - _value; balanceOf[_to] = balanceOf[_to] + _value; emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { uint256 a = allowance[_from][msg.sender]; // read allowance //require(_value <= balanceOf[_from], "value exceeds balance"); // SafeMath already checks this if (a != type(uint256).max) { // not infinite approval require(_value <= a, "not approved"); unchecked { allowance[_from][msg.sender] = a - _value; } } balanceOf[_from] = balanceOf[_from] - _value; balanceOf[_to] = balanceOf[_to] + _value; emit Transfer(_from, _to, _value); return true; } /** * @dev Approve tokens of mount _value to be spent by _spender * @param _spender address The spender * @param _value the stipend to spend */ function approve(address _spender, uint256 _value) external returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Masterchef v2 integration 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev onSushiReward implements the SushiSwap masterchefV2 callback, guarded by the onlyMCV2 modifier * @param _user address called on behalf of * @param _to address who send rewards to * @param _sushiAmount uint256, if not 0 then the rewards will be harvested * @param _newLpAmount uint256, amount of LP tokens staked at Sushi */ function onSushiReward ( uint256 /* pid */, address _user, address _to, uint256 _sushiAmount, uint256 _newLpAmount) external onlyMCV2 { UserInfo storage user = farmersMasterchef[_user]; update(); // Harvest sushi when there is sushiAmount passed through as this only comes in the event of the masterchef contract harvesting if(_sushiAmount != 0) _harvest(user, _to); // send outstanding CIG to _to uint256 delta; // Withdraw stake if(user.deposit >= _newLpAmount) { // Delta is withdraw delta = user.deposit - _newLpAmount; masterchefDeposits -= delta; // subtract from staked total _withdraw(user, delta); emit ChefWithdraw(_user, delta); } // Deposit stake else if(user.deposit != _newLpAmount) { // Delta is deposit delta = _newLpAmount - user.deposit; masterchefDeposits += delta; // add to staked total _deposit(user, delta); emit ChefDeposit(_user, delta); } } // onlyMCV2 ensures only the MasterChefV2 contract can call this modifier onlyMCV2 { require( msg.sender == MASTERCHEF_V2, "Only MCV2" ); _; } } /* * 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 interfaces 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 */ /** * @dev IRouterV2 is the sushi router 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F */ interface IRouterV2 { function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external pure returns(uint256 amountOut); } /** * @dev ICryptoPunk used to query the cryptopunks contract to verify the owner */ interface ICryptoPunk { //function balanceOf(address account) external view returns (uint256); function punkIndexToAddress(uint256 punkIndex) external returns (address); //function punksOfferedForSale(uint256 punkIndex) external returns (bool, uint256, address, uint256, address); //function buyPunk(uint punkIndex) external payable; //function transferPunk(address to, uint punkIndex) external; } interface ICEOERC721 { function transferFrom(address _from, address _to, uint256 _tokenId) external payable; } /* * @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 * 0xTycoon was here * 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 from UniswapV2Pair.sol */ interface ILiquidityPoolERC20 is IERC20 { function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast); function totalSupply() external view returns(uint); } interface IOldCigtoken is IERC20 { function claims(uint256) external view returns (bool); function graffiti() external view returns (bytes32); function cigPerBlock() external view returns (uint256); function The_CEO() external view returns (address); function CEO_punk_index() external view returns (uint); function CEO_price() external view returns (uint256); function CEO_state() external view returns (uint256); function CEO_tax_balance() external view returns (uint256); function taxBurnBlock() external view returns (uint256); function lastRewardBlock() external view returns (uint256); function rewardsChangedBlock() external view returns (uint256); function userInfo(address) external view returns (uint256, uint256); function burnTax() external; } // 🚬
Returns the amount of tokens in existence./ Returns the amount of tokens owned by `account`./ Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event./ 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./ 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: 0xTycoon was here Emits an {Approval} event./ 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./ Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero./ Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance./ from UniswapV2Pair.sol/
interface ILiquidityPoolERC20 is IERC20 { function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast); function totalSupply() external view returns(uint); }
1,073,070
./full_match/11155111/0x6B086AA45FDC47ea899f7881FF511D89a59CA4B3/sources/@lukso/lsp-smart-contracts/contracts/LSP7DigitalAsset/LSP7DigitalAssetCore.sol
Mints `amount` of tokens and transfers it to `to`. to the address to mint tokens for. amount the amount of tokens to mint. allowNonLSP1Recipient a boolean that describe if transfer to a `to` address that does not support LSP1 is allowed or not. data Additional data the caller wants included in the emitted {Transfer} event, and sent in the LSP1 hook to the `to` address. @custom:requirements - `to` cannot be the zero address. @custom:events {Transfer} event with `address(0)` as `from`./
function _mint( address to, uint256 amount, bool allowNonLSP1Recipient, bytes memory data ) internal virtual { if (to == address(0)) { revert LSP7CannotSendWithAddressZero(); } address operator = msg.sender; _beforeTokenTransfer(address(0), to, amount); _tokenOwnerBalances[to] += amount; emit Transfer( operator, address(0), to, amount, allowNonLSP1Recipient, data ); bytes memory lsp1Data = abi.encode(address(0), to, amount, data); _notifyTokenReceiver(to, allowNonLSP1Recipient, lsp1Data); }
3,835,917
./partial_match/3/0xc7920b800569AC8895e1a0bA3869B6ddF56717e3/sources/PoR.sol
calculates the signature hash of a Bitcoin transaction with the provided details documented in bip143. many values are hardcoded here _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) _inputPKH the input pubkeyhash (hash160(sender_pubkey)) _inputValue the value of the input in satoshi _outputValue the value of the output in satoshi _outputPKH the output pubkeyhash (hash160(recipient_pubkey)) return the double-sha256 (hash256) signature hash as defined by bip143
function wpkhToWpkhSighash( ) internal pure returns (bytes32) { return wpkhSpendSighash( _outpoint, _inputPKH, _inputValue, _outputValue, abi.encodePacked( _outputPKH) ); }
5,220,646
// SPDX-License-Identifier: MIT // File: contracts/AddressChecksumStringUtil.sol pragma solidity ^0.8.0; // Derived from https://ethereum.stackexchange.com/a/63953, no license specified // Modified to remove unnecessary functionality and prepend the checksummed string address with "0x" /** * @dev This contract provides a set of pure functions for computing the EIP-55 * checksum of an account in formats friendly to both off-chain and on-chain * callers, as well as for checking if a given string hex representation of an * address has a valid checksum. These helper functions could also be repurposed * as a library that extends the `address` type. */ contract AddressChecksumStringUtil { function toChecksumString(address account) internal pure returns (string memory asciiString) { // convert the account argument from address to bytes. bytes20 data = bytes20(account); // create an in-memory fixed-size bytes array. bytes memory asciiBytes = new bytes(40); // declare variable types. uint8 b; uint8 leftNibble; uint8 rightNibble; bool leftCaps; bool rightCaps; uint8 asciiOffset; // get the capitalized characters in the actual checksum. bool[40] memory caps = _toChecksumCapsFlags(account); // iterate over bytes, processing left and right nibble in each iteration. for (uint256 i = 0; i < data.length; i++) { // locate the byte and extract each nibble. b = uint8(uint160(data) / (2**(8*(19 - i)))); leftNibble = b / 16; rightNibble = b - 16 * leftNibble; // locate and extract each capitalization status. leftCaps = caps[2*i]; rightCaps = caps[2*i + 1]; // get the offset from nibble value to ascii character for left nibble. asciiOffset = _getAsciiOffset(leftNibble, leftCaps); // add the converted character to the byte array. asciiBytes[2 * i] = bytes1(leftNibble + asciiOffset); // get the offset from nibble value to ascii character for right nibble. asciiOffset = _getAsciiOffset(rightNibble, rightCaps); // add the converted character to the byte array. asciiBytes[2 * i + 1] = bytes1(rightNibble + asciiOffset); } return string(abi.encodePacked("0x", string(asciiBytes))); } function _getAsciiOffset(uint8 nibble, bool caps) internal pure returns (uint8 offset) { // to convert to ascii characters, add 48 to 0-9, 55 to A-F, & 87 to a-f. if (nibble < 10) { offset = 48; } else if (caps) { offset = 55; } else { offset = 87; } } function _toChecksumCapsFlags(address account) internal pure returns (bool[40] memory characterCapitalized) { // convert the address to bytes. bytes20 a = bytes20(account); // hash the address (used to calculate checksum). bytes32 b = keccak256(abi.encodePacked(_toAsciiString(a))); // declare variable types. uint8 leftNibbleAddress; uint8 rightNibbleAddress; uint8 leftNibbleHash; uint8 rightNibbleHash; // iterate over bytes, processing left and right nibble in each iteration. for (uint256 i; i < a.length; i++) { // locate the byte and extract each nibble for the address and the hash. rightNibbleAddress = uint8(a[i]) % 16; leftNibbleAddress = (uint8(a[i]) - rightNibbleAddress) / 16; rightNibbleHash = uint8(b[i]) % 16; leftNibbleHash = (uint8(b[i]) - rightNibbleHash) / 16; characterCapitalized[2 * i] = (leftNibbleAddress > 9 && leftNibbleHash > 7); characterCapitalized[2 * i + 1] = (rightNibbleAddress > 9 && rightNibbleHash > 7); } } // based on https://ethereum.stackexchange.com/a/56499/48410 function _toAsciiString(bytes20 data) internal pure returns (string memory asciiString) { // create an in-memory fixed-size bytes array. bytes memory asciiBytes = new bytes(40); // declare variable types. uint8 b; uint8 leftNibble; uint8 rightNibble; // iterate over bytes, processing left and right nibble in each iteration. for (uint256 i = 0; i < data.length; i++) { // locate the byte and extract each nibble. b = uint8(uint160(data) / (2 ** (8 * (19 - i)))); leftNibble = b / 16; rightNibble = b - 16 * leftNibble; // to convert to ascii characters, add 48 to 0-9 and 87 to a-f. asciiBytes[2 * i] = bytes1(leftNibble + (leftNibble < 10 ? 48 : 87)); asciiBytes[2 * i + 1] = bytes1(rightNibble + (rightNibble < 10 ? 48 : 87)); } return string(asciiBytes); } } // 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: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File: @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/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/IAwooToken.sol pragma solidity 0.8.12; interface IAwooToken is IERC20 { function increaseVirtualBalance(address account, uint256 amount) external; function mint(address account, uint256 amount) external; function balanceOfVirtual(address account) external view returns(uint256); function spendVirtualAwoo(bytes32 hash, bytes memory sig, string calldata nonce, address account, uint256 amount) external; } // 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 v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/AwooToken.sol pragma solidity 0.8.12; contract AwooToken is IAwooToken, ERC20, ReentrancyGuard, Ownable, AddressChecksumStringUtil { using ECDSA for bytes32; using Strings for uint256; /// @dev Controls whether or not the deposit/withdraw functionality is enabled bool public isActive = true; /// @dev The percentage of spent virtual AWOO taken as a fee uint256 public awooFeePercentage = 10; /// @dev The Awoo Studios account where fees are sent address public awooStudiosAccount; address[2] private _admins; bool private _adminsSet; /// @dev Keeps track of which contracts are explicitly allowed to add virtual AWOO to a holder's address, spend from it, or /// in the future, mint ERC-20 tokens mapping(address => bool) private _authorizedContracts; /// @dev Keeps track of each holders virtual AWOO balance mapping(address => uint256) private _virtualBalance; /// @dev Keeps track of nonces used for spending events to prevent double spends mapping(string => bool) private _usedNonces; event AuthorizedContractAdded(address contractAddress, address addedBy); event AuthorizedContractRemoved(address contractAddress, address removedBy); event VirtualAwooSpent(address spender, uint256 amount); constructor(address awooAccount) ERC20("Awoo Token", "AWOO") { require(awooAccount != address(0), "Invalid awooAccount"); awooStudiosAccount = awooAccount; } /// @notice Allows an authorized contract to mint $AWOO /// @param account The account to receive the minted $AWOO tokens /// @param amount The amount of $AWOO to mint function mint(address account, uint256 amount) external nonReentrant onlyAuthorizedContract { require(account != address(0), "Cannot mint to the zero address"); require(amount > 0, "Amount cannot be zero"); _mint(account, amount); } /// @notice Allows the owner or an admin to add authorized contracts /// @param contractAddress The address of the contract to authorize function addAuthorizedContract(address contractAddress) external onlyOwnerOrAdmin { require(isContract(contractAddress), "Not a contract address"); _authorizedContracts[contractAddress] = true; emit AuthorizedContractAdded(contractAddress, _msgSender()); } /// @notice Allows the owner or an admin to remove authorized contracts /// @param contractAddress The address of the contract to revoke authorization for function removeAuthorizedContract(address contractAddress) external onlyOwnerOrAdmin { _authorizedContracts[contractAddress] = false; emit AuthorizedContractRemoved(contractAddress, _msgSender()); } /// @notice Exchanges virtual AWOO for ERC-20 $AWOO /// @param amount The amount of virtual AWOO to withdraw function withdraw(uint256 amount) external whenActive hasBalance(amount, _virtualBalance[_msgSender()]) nonReentrant { _mint(_msgSender(), amount); _virtualBalance[_msgSender()] -= amount; } /// @notice Exchanges ERC-20 $AWOO for virtual AWOO to be used in the Awoo Studios ecosystem /// @param amount The amount of $AWOO to deposit function deposit(uint256 amount) external whenActive hasBalance(amount, balanceOf(_msgSender())) nonReentrant { _burn(_msgSender(), amount); _virtualBalance[_msgSender()] += amount; } /// @notice Returns the amount of virtual AWOO held by the specified address /// @param account The holder account to check function balanceOfVirtual(address account) external view returns(uint256) { return _virtualBalance[account]; } /// @notice Returns the amount of ERC-20 $AWOO held by the specified address /// @param account The holder account to check function totalBalanceOf(address account) external view returns(uint256) { return _virtualBalance[account] + balanceOf(account); } /// @notice Allows authorized contracts to increase a holders virtual AWOO /// @param account The account to increase /// @param amount The amount of virtual AWOO to increase the account by function increaseVirtualBalance(address account, uint256 amount) external onlyAuthorizedContract { _virtualBalance[account] += amount; } /// @notice Allows authorized contracts to faciliate the spending of virtual AWOO, and fees to be paid to /// Awoo Studios. /// @notice Only amounts that have been signed and verified by the token holder can be spent /// @param hash The hash of the message displayed to and signed by the holder /// @param sig The signature of the messages that was signed by the holder /// @param nonce The unique code used to prevent double spends /// @param account The account of the holder to debit /// @param amount The amount of virtual AWOO to debit function spendVirtualAwoo(bytes32 hash, bytes memory sig, string calldata nonce, address account, uint256 amount) external onlyAuthorizedContract hasBalance(amount, _virtualBalance[account]) nonReentrant { require(_usedNonces[nonce] == false, "Duplicate nonce"); require(matchAddresSigner(account, hash, sig), "Message signer mismatch"); // Make sure that the spend request was authorized (signed) by the holder require(hashTransaction(account, amount) == hash, "Hash check failed"); // Make sure that only the amount authorized by the holder can be spent // debit the holder's virtual AWOO account _virtualBalance[account]-=amount; // Mint the spending fee to the Awoo Studios account _mint(awooStudiosAccount, ((amount * awooFeePercentage)/100)); _usedNonces[nonce] = true; emit VirtualAwooSpent(account, amount); } /// @notice Allows the owner to specify two addresses allowed to administer this contract /// @param adminAddresses A 2 item array of addresses function setAdmins(address[2] calldata adminAddresses) external onlyOwner { require(adminAddresses[0] != address(0) && adminAddresses[1] != address(0), "Invalid admin address"); _admins = adminAddresses; _adminsSet = true; } /// @notice Allows the owner or an admin to activate/deactivate deposit and withdraw functionality /// @notice This will only be used to disable functionality as a worst case scenario /// @param active The value specifiying whether or not deposits/withdraws should be allowed function setActiveState(bool active) external onlyOwnerOrAdmin { isActive = active; } /// @notice Allows the owner to change the account used for collecting spending fees /// @param awooAccount The new account function setAwooStudiosAccount(address awooAccount) external onlyOwner { require(awooAccount != address(0), "Invalid awooAccount"); awooStudiosAccount = awooAccount; } /// @notice Allows the owner to change the spending fee percentage /// @param feePercentage The new fee percentage function setFeePercentage(uint256 feePercentage) external onlyOwner { awooFeePercentage = feePercentage; // We're intentionally allowing the fee percentage to be set to 0%, incase no fees need to be collected } /// @notice Allows the owner to withdraw any Ethereum that was accidentally sent to this contract function rescueEth() external onlyOwner { payable(owner()).transfer(address(this).balance); } /// @dev Derived from @openzeppelin/contracts/utils/Address.sol function isContract(address account) private 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 Validates the specified account against the account that signed the message function matchAddresSigner(address account, bytes32 hash, bytes memory signature) private pure returns (bool) { return account == hash.recover(signature); } /// @dev Hashes the message we expected the spender to sign so we can compare the hashes to ensure that the owner /// of the specified address signed the same message /// @dev fractional ether unit amounts aren't supported function hashTransaction(address sender, uint256 amount) private pure returns (bytes32) { require(amount == ((amount/1e18)*1e18), "Invalid amount"); // Virtual $AWOO, much like the ERC-20 $AWOO is stored with 18 implied decimal places. // For user-friendliness, when prompting the user to sign the message, the amount is // _displayed_ without the implied decimals, but it is charged with the implied decimals, // so when validating the hash, we have to use the same value we displayed to the user. // This only affects the display value, nothing else amount = amount/1e18; string memory message = string(abi.encodePacked( "As the owner of Ethereum address\r\n", toChecksumString(sender), "\r\nI authorize the spending of ", amount.toString()," virtual $AWOO" )); uint256 messageLength = bytes(message).length; bytes32 hash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n",messageLength.toString(), message ) ); return hash; } modifier onlyAuthorizedContract() { require(_authorizedContracts[_msgSender()], "Sender is not authorized"); _; } modifier whenActive() { require(isActive, "Contract is not active"); _; } modifier hasBalance(uint256 amount, uint256 balance) { require(amount > 0, "Amount cannot be zero"); require(balance >= amount, "Insufficient Balance"); _; } modifier onlyOwnerOrAdmin() { require( _msgSender() == owner() || (_adminsSet && (_msgSender() == _admins[0] || _msgSender() == _admins[1])), "Caller is not the owner or an admin" ); _; } }
Exchanges ERC-20 $AWOO for virtual AWOO to be used in the Awoo Studios ecosystem amount The amount of $AWOO to deposit
function deposit(uint256 amount) external whenActive hasBalance(amount, balanceOf(_msgSender())) nonReentrant { _burn(_msgSender(), amount); _virtualBalance[_msgSender()] += amount; }
4,799,698
pragma solidity ^0.4.19; /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Ethernauts contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function takeOwnership(uint256 _tokenId) public; function implementsERC721() public pure returns (bool); // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // Extend this library for child contracts library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * @dev Compara two numbers, and return the bigger one. */ function max(int256 a, int256 b) internal pure returns (int256) { if (a > b) { return a; } else { return b; } } /** * @dev Compara two numbers, and return the bigger one. */ function min(int256 a, int256 b) internal pure returns (int256) { if (a < b) { return a; } else { return b; } } } /// @dev Base contract for all Ethernauts contracts holding global constants and functions. contract EthernautsBase { /*** CONSTANTS USED ACROSS CONTRACTS ***/ /// @dev Used by all contracts that interfaces with Ethernauts /// The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @dev due solidity limitation we cannot return dynamic array from methods /// so it creates incompability between functions across different contracts uint8 public constant STATS_SIZE = 10; uint8 public constant SHIP_SLOTS = 5; // Possible state of any asset enum AssetState { Available, UpForLease, Used } // Possible state of any asset // NotValid is to avoid 0 in places where category must be bigger than zero enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember } /// @dev Sector stats enum ShipStats {Level, Attack, Defense, Speed, Range, Luck} /// @notice Possible attributes for each asset /// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. /// 00000010 - Producible - Product of a factory and/or factory contract. /// 00000100 - Explorable- Product of exploration. /// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. /// 00010000 - Permanent - Cannot be removed, always owned by a user. /// 00100000 - Consumable - Destroyed after N exploration expeditions. /// 01000000 - Tradable - Buyable and sellable on the market. /// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 public ATTR_SEEDED = bytes2(2**0); bytes2 public ATTR_PRODUCIBLE = bytes2(2**1); bytes2 public ATTR_EXPLORABLE = bytes2(2**2); bytes2 public ATTR_LEASABLE = bytes2(2**3); bytes2 public ATTR_PERMANENT = bytes2(2**4); bytes2 public ATTR_CONSUMABLE = bytes2(2**5); bytes2 public ATTR_TRADABLE = bytes2(2**6); bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7); } /// @notice This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO and CTO. it also includes pausable pattern. contract EthernautsAccessControl is EthernautsBase { // This facet controls access control for Ethernauts. // All roles have same responsibilities and rights, but there is slight differences between them: // // - The CEO: The CEO can reassign other roles and only role that can unpause the smart contract. // It is initially set to the address that created the smart contract. // // - The CTO: The CTO can change contract address, oracle address and plan for upgrades. // // - The COO: The COO can change contract address and add create assets. // /// @dev Emited when contract is upgraded - See README.md for updgrade plan /// @param newContract address pointing to new contract event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public ctoAddress; address public cooAddress; address public oracleAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CTO-only functionality modifier onlyCTO() { require(msg.sender == ctoAddress); _; } /// @dev Access modifier for CTO-only functionality modifier onlyOracle() { require(msg.sender == oracleAddress); _; } modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == ctoAddress || msg.sender == cooAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CTO. Only available to the current CTO or CEO. /// @param _newCTO The address of the new CTO function setCTO(address _newCTO) external { require( msg.sender == ceoAddress || msg.sender == ctoAddress ); require(_newCTO != address(0)); ctoAddress = _newCTO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO or CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external { require( msg.sender == ceoAddress || msg.sender == cooAddress ); require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Assigns a new address to act as oracle. /// @param _newOracle The address of oracle function setOracle(address _newOracle) external { require(msg.sender == ctoAddress); require(_newOracle != address(0)); oracleAddress = _newOracle; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CTO account is compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title The facet of the Ethernauts contract that manages ownership, ERC-721 compliant. /// @notice This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // It interfaces with EthernautsStorage provinding basic functions as create and list, also holds // reference to logic contracts as Auction, Explore and so on /// @author Ethernatus - Fernando Pauer /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 contract EthernautsOwnership is EthernautsAccessControl, ERC721 { /// @dev Contract holding only data. EthernautsStorage public ethernautsStorage; /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "Ethernauts"; string public constant symbol = "ETNT"; /********* ERC 721 - COMPLIANCE CONSTANTS AND FUNCTIONS ***************/ /**********************************************************************/ bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); /*** EVENTS ***/ // Events as per ERC-721 event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed owner, address indexed approved, uint256 tokens); /// @dev When a new asset is create it emits build event /// @param owner The address of asset owner /// @param tokenId Asset UniqueID /// @param assetId ID that defines asset look and feel /// @param price asset price event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price); function implementsERC721() public pure returns (bool) { return true; } /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. ERC-165 and ERC-721. /// @param _interfaceID interface signature ID function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Checks if a given address is the current owner of a particular Asset. /// @param _claimant the address we are validating against. /// @param _tokenId asset UniqueId, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.ownerOf(_tokenId) == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Asset. /// @param _claimant the address we are confirming asset is approved for. /// @param _tokenId asset UniqueId, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.approvedFor(_tokenId) == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Assets on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { ethernautsStorage.approve(_tokenId, _approved); } /// @notice Returns the number of Assets owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ethernautsStorage.balanceOf(_owner); } /// @dev Required for ERC-721 compliance. /// @notice Transfers a Asset to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// Ethernauts specifically) or your Asset may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Asset to transfer. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any assets // (except very briefly after it is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the storage contract to prevent accidental // misuse. Auction or Upgrade contracts should only take ownership of assets // through the allow + transferFrom flow. require(_to != address(ethernautsStorage)); // You can only send your own asset. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. ethernautsStorage.transfer(msg.sender, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Grant another address the right to transfer a specific Asset via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Asset that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Asset owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Asset to be transferred. /// @param _to The address that should take ownership of the Asset. Can be any address, /// including the caller. /// @param _tokenId The ID of the Asset to be transferred. function _transferFrom( address _from, address _to, uint256 _tokenId ) internal { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any assets (except for used assets). require(_owns(_from, _tokenId)); // Check for approval and valid ownership require(_approvedFor(_to, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). ethernautsStorage.transfer(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Transfer a Asset owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Asset to be transfered. /// @param _to The address that should take ownership of the Asset. Can be any address, /// including the caller. /// @param _tokenId The ID of the Asset to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { _transferFrom(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. function takeOwnership(uint256 _tokenId) public { address _from = ethernautsStorage.ownerOf(_tokenId); // Safety check to prevent against an unexpected 0x0 default. require(_from != address(0)); _transferFrom(_from, msg.sender, _tokenId); } /// @notice Returns the total number of Assets currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return ethernautsStorage.totalSupply(); } /// @notice Returns owner of a given Asset(Token). /// @param _tokenId Token ID to get owner. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = ethernautsStorage.ownerOf(_tokenId); require(owner != address(0)); } /// @dev Creates a new Asset with the given fields. ONly available for C Levels /// @param _creatorTokenID The asset who is father of this asset /// @param _price asset price /// @param _assetID asset ID /// @param _category see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description function createNewAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _assetID, uint8 _category, uint8 _attributes, uint8[STATS_SIZE] _stats ) external onlyCLevel returns (uint256) { // owner must be sender require(_owner != address(0)); uint256 tokenID = ethernautsStorage.createAsset( _creatorTokenID, _owner, _price, _assetID, _category, uint8(AssetState.Available), _attributes, _stats, 0, 0 ); // emit the build event Build( _owner, tokenID, _assetID, _price ); return tokenID; } /// @notice verify if token is in exploration time /// @param _tokenId The Token ID that can be upgraded function isExploring(uint256 _tokenId) public view returns (bool) { uint256 cooldown; uint64 cooldownEndBlock; (,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId); return (cooldown > now) || (cooldownEndBlock > uint64(block.number)); } } /// @title Storage contract for Ethernauts Data. Common structs and constants. /// @notice This is our main data storage, constants and data types, plus // internal functions for managing the assets. It is isolated and only interface with // a list of granted contracts defined by CTO /// @author Ethernauts - Fernando Pauer contract EthernautsStorage is EthernautsAccessControl { function EthernautsStorage() public { // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is the initial CTO as well ctoAddress = msg.sender; // the creator of the contract is the initial CTO as well cooAddress = msg.sender; // the creator of the contract is the initial Oracle as well oracleAddress = msg.sender; } /// @notice No tipping! /// @dev Reject all Ether from being sent here. Hopefully, we can prevent user accidents. function() external payable { require(msg.sender == address(this)); } /*** Mapping for Contracts with granted permission ***/ mapping (address => bool) public contractsGrantedAccess; /// @dev grant access for a contract to interact with this contract. /// @param _v2Address The contract address to grant access function grantAccess(address _v2Address) public onlyCTO { // See README.md for updgrade plan contractsGrantedAccess[_v2Address] = true; } /// @dev remove access from a contract to interact with this contract. /// @param _v2Address The contract address to be removed function removeAccess(address _v2Address) public onlyCTO { // See README.md for updgrade plan delete contractsGrantedAccess[_v2Address]; } /// @dev Only allow permitted contracts to interact with this contract modifier onlyGrantedContracts() { require(contractsGrantedAccess[msg.sender] == true); _; } modifier validAsset(uint256 _tokenId) { require(assets[_tokenId].ID > 0); _; } /*** DATA TYPES ***/ /// @dev The main Ethernauts asset struct. Every asset in Ethernauts is represented by a copy /// of this structure. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Asset { // Asset ID is a identifier for look and feel in frontend uint16 ID; // Category = Sectors, Manufacturers, Ships, Objects (Upgrades/Misc), Factories and CrewMembers uint8 category; // The State of an asset: Available, On sale, Up for lease, Cooldown, Exploring uint8 state; // Attributes // byte pos - Definition // 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. // 00000010 - Producible - Product of a factory and/or factory contract. // 00000100 - Explorable- Product of exploration. // 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. // 00010000 - Permanent - Cannot be removed, always owned by a user. // 00100000 - Consumable - Destroyed after N exploration expeditions. // 01000000 - Tradable - Buyable and sellable on the market. // 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 attributes; // The timestamp from the block when this asset was created. uint64 createdAt; // The minimum timestamp after which this asset can engage in exploring activities again. uint64 cooldownEndBlock; // The Asset's stats can be upgraded or changed based on exploration conditions. // It will be defined per child contract, but all stats have a range from 0 to 255 // Examples // 0 = Ship Level // 1 = Ship Attack uint8[STATS_SIZE] stats; // Set to the cooldown time that represents exploration duration for this asset. // Defined by a successful exploration action, regardless of whether this asset is acting as ship or a part. uint256 cooldown; // a reference to a super asset that manufactured the asset uint256 builtBy; } /*** CONSTANTS ***/ // @dev Sanity check that allows us to ensure that we are pointing to the // right storage contract in our EthernautsLogic(address _CStorageAddress) call. bool public isEthernautsStorage = true; /*** STORAGE ***/ /// @dev An array containing the Asset struct for all assets in existence. The Asset UniqueId /// of each asset is actually an index into this array. Asset[] public assets; /// @dev A mapping from Asset UniqueIDs to the price of the token. /// stored outside Asset Struct to save gas, because price can change frequently mapping (uint256 => uint256) internal assetIndexToPrice; /// @dev A mapping from asset UniqueIDs to the address that owns them. All assets have some valid owner address. mapping (uint256 => address) internal assetIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) internal ownershipTokenCount; /// @dev A mapping from AssetUniqueIDs to an address that has been approved to call /// transferFrom(). Each Asset can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) internal assetIndexToApproved; /*** SETTERS ***/ /// @dev set new asset price /// @param _tokenId asset UniqueId /// @param _price asset price function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts { assetIndexToPrice[_tokenId] = _price; } /// @dev Mark transfer as approved /// @param _tokenId asset UniqueId /// @param _approved address approved function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts { assetIndexToApproved[_tokenId] = _approved; } /// @dev Assigns ownership of a specific Asset to an address. /// @param _from current owner address /// @param _to new owner address /// @param _tokenId asset UniqueId function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts { // Since the number of assets is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership assetIndexToOwner[_tokenId] = _to; // When creating new assets _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete assetIndexToApproved[_tokenId]; } } /// @dev A public method that creates a new asset and stores it. This /// method does basic checking and should only be called from other contract when the /// input data is known to be valid. Will NOT generate any event it is delegate to business logic contracts. /// @param _creatorTokenID The asset who is father of this asset /// @param _owner First owner of this asset /// @param _price asset price /// @param _ID asset ID /// @param _category see Asset Struct description /// @param _state see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description function createAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint256 _cooldown, uint64 _cooldownEndBlock ) public onlyGrantedContracts returns (uint256) { // Ensure our data structures are always valid. require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); Asset memory asset = Asset({ ID: _ID, category: _category, builtBy: _creatorTokenID, attributes: bytes2(_attributes), stats: _stats, state: _state, createdAt: uint64(now), cooldownEndBlock: _cooldownEndBlock, cooldown: _cooldown }); uint256 newAssetUniqueId = assets.push(asset) - 1; // Check it reached 4 billion assets but let's just be 100% sure. require(newAssetUniqueId == uint256(uint32(newAssetUniqueId))); // store price assetIndexToPrice[newAssetUniqueId] = _price; // This will assign ownership transfer(address(0), _owner, newAssetUniqueId); return newAssetUniqueId; } /// @dev A public method that edit asset in case of any mistake is done during process of creation by the developer. This /// This method doesn't do any checking and should only be called when the /// input data is known to be valid. /// @param _tokenId The token ID /// @param _creatorTokenID The asset that create that token /// @param _price asset price /// @param _ID asset ID /// @param _category see Asset Struct description /// @param _state see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description /// @param _cooldown asset cooldown index function editAsset( uint256 _tokenId, uint256 _creatorTokenID, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint16 _cooldown ) external validAsset(_tokenId) onlyCLevel returns (uint256) { // Ensure our data structures are always valid. require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); // store price assetIndexToPrice[_tokenId] = _price; Asset storage asset = assets[_tokenId]; asset.ID = _ID; asset.category = _category; asset.builtBy = _creatorTokenID; asset.attributes = bytes2(_attributes); asset.stats = _stats; asset.state = _state; asset.cooldown = _cooldown; } /// @dev Update only stats /// @param _tokenId asset UniqueId /// @param _stats asset state, see Asset Struct description function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].stats = _stats; } /// @dev Update only asset state /// @param _tokenId asset UniqueId /// @param _state asset state, see Asset Struct description function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].state = _state; } /// @dev Update Cooldown for a single asset /// @param _tokenId asset UniqueId /// @param _cooldown asset state, see Asset Struct description function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].cooldown = _cooldown; assets[_tokenId].cooldownEndBlock = _cooldownEndBlock; } /*** GETTERS ***/ /// @notice Returns only stats data about a specific asset. /// @dev it is necessary due solidity compiler limitations /// when we have large qty of parameters it throws StackTooDeepException /// @param _tokenId The UniqueId of the asset of interest. function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) { return assets[_tokenId].stats; } /// @dev return current price of an asset /// @param _tokenId asset UniqueId function priceOf(uint256 _tokenId) public view returns (uint256 price) { return assetIndexToPrice[_tokenId]; } /// @notice Check if asset has all attributes passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _attributes see Asset Struct description function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes == _attributes; } /// @notice Check if asset has any attribute passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _attributes see Asset Struct description function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes != 0x0; } /// @notice Check if asset is in the state passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _category see AssetCategory in EthernautsBase for possible states function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) { return assets[_tokenId].category == _category; } /// @notice Check if asset is in the state passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _state see enum AssetState in EthernautsBase for possible states function isState(uint256 _tokenId, uint8 _state) public view returns (bool) { return assets[_tokenId].state == _state; } /// @notice Returns owner of a given Asset(Token). /// @dev Required for ERC-721 compliance. /// @param _tokenId asset UniqueId function ownerOf(uint256 _tokenId) public view returns (address owner) { return assetIndexToOwner[_tokenId]; } /// @dev Required for ERC-721 compliance /// @notice Returns the number of Assets owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @dev Checks if a given address currently has transferApproval for a particular Asset. /// @param _tokenId asset UniqueId function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) { return assetIndexToApproved[_tokenId]; } /// @notice Returns the total number of Assets currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return assets.length; } /// @notice List all existing tokens. It can be filtered by attributes or assets with owner /// @param _owner filter all assets by owner function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns( uint256[6][] ) { uint256 totalAssets = assets.length; if (totalAssets == 0) { // Return an empty array return new uint256[6][](0); } else { uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets); uint256 resultIndex = 0; bytes2 hasAttributes = bytes2(_withAttributes); Asset memory asset; for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) { asset = assets[tokenId]; if ( (asset.state != uint8(AssetState.Used)) && (assetIndexToOwner[tokenId] == _owner || _owner == address(0)) && (asset.attributes & hasAttributes == hasAttributes) ) { result[resultIndex][0] = tokenId; result[resultIndex][1] = asset.ID; result[resultIndex][2] = asset.category; result[resultIndex][3] = uint256(asset.attributes); result[resultIndex][4] = asset.cooldown; result[resultIndex][5] = assetIndexToPrice[tokenId]; resultIndex++; } } return result; } } } /// @title The facet of the Ethernauts Logic contract handle all common code for logic/business contracts /// @author Ethernatus - Fernando Pauer contract EthernautsLogic is EthernautsOwnership { // Set in case the logic contract is broken and an upgrade is required address public newContractAddress; /// @dev Constructor function EthernautsLogic() public { // the creator of the contract is the initial CEO, COO, CTO ceoAddress = msg.sender; ctoAddress = msg.sender; cooAddress = msg.sender; oracleAddress = msg.sender; // Starts paused. paused = true; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCTO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @dev set a new reference to the NFT ownership contract /// @param _CStorageAddress - address of a deployed contract implementing EthernautsStorage. function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused { EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress); require(candidateContract.isEthernautsStorage()); ethernautsStorage = candidateContract; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(ethernautsStorage != address(0)); require(newContractAddress == address(0)); // require this contract to have access to storage contract require(ethernautsStorage.contractsGrantedAccess(address(this)) == true); // Actually unpause the contract. super.unpause(); } // @dev Allows the COO to capture the balance available to the contract. function withdrawBalances(address _to) public onlyCLevel { _to.transfer(this.balance); } /// return current contract balance function getBalance() public view onlyCLevel returns (uint256) { return this.balance; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. /// This provides public methods for Upgrade ship. /// /// - UpgradeShip: This provides public methods for managing how and if a ship can upgrade. /// The user can place a number of Ship Upgrades on the ship to affect the ship’s exploration. /// Combining the Explore and Upgrade actions together limits the amount of gas the user has to pay. /// @author Ethernatus - Fernando Pauer contract EthernautsUpgrade is EthernautsLogic { /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// and Delegate constructor to Nonfungible contract. function EthernautsUpgrade() public EthernautsLogic() {} /*** EVENTS ***/ /// @dev The Upgrade event is fired whenever a ship is upgraded. event Upgrade(uint256 indexed tokenId); /*** CONSTANTS ***/ uint8 STATS_CAPOUT = 2**8 - 1; // all stats have a range from 0 to 255 // ************************* UPGRADE SHIP **************************** /// @notice Check and define how a ship can upgrade /// Example: /// User A wants to Upgrade Ship A. Ship A has 5 available upgrade slots. /// Thankfully, User A has 5 Ship Upgrades in their inventory. /// They have 1x Plasma Cannons (+1 Attack), Hardened Plates (+2 Defense), /// 1x Navigation Processor (+1 Range), 1x Engine Tune (+2 Speed), and Lucky Shamrock (+1 Luck) . /// User A drags the 5 Ship Upgrades into the appropriate slots and hits the Upgrade button. /// Ship A’s stats are now improved by +1 Attack, +2 Defense, +1 Range, +2 Speed, and +1 Luck, forever. /// The Ship Upgrades are consumed and disappear. The Ship then increases in level +1 to a total level of 2. /// @param _tokenId The Token ID that can be upgraded /// @param _objects List of objects to be used in the upgrade function upgradeShip(uint256 _tokenId, uint256[SHIP_SLOTS] _objects) external whenNotPaused { // Checking if Asset is a ship or not require(ethernautsStorage.isCategory(_tokenId, uint8(AssetCategory.Ship))); // Ensure the Ship is in available state, otherwise it cannot be upgraded require(ethernautsStorage.isState(_tokenId, uint8(AssetState.Available))); // only owner can upgrade his/her ship require(msg.sender == ethernautsStorage.ownerOf(_tokenId)); // ship could not be in exploration require(!isExploring(_tokenId)); // get ship and objects current stats uint i = 0; uint8[STATS_SIZE] memory _shipStats = ethernautsStorage.getStats(_tokenId); uint256 level = _shipStats[uint(ShipStats.Level)]; uint8[STATS_SIZE][SHIP_SLOTS] memory _objectsStats; // check if level capped out, if yes no more upgrade is available require(level < 5); // a mapping to require upgrades should have different token ids uint256[] memory upgradesToTokenIndex = new uint256[](ethernautsStorage.totalSupply()); // all objects must be available to use for(i = 0; i < _objects.length; i++) { // sender should owner all assets require(msg.sender == ethernautsStorage.ownerOf(_objects[i])); require(!isExploring(_objects[i])); require(ethernautsStorage.isCategory(_objects[i], uint8(AssetCategory.Object))); // avoiding duplicate keys require(upgradesToTokenIndex[_objects[i]] == 0); // mark token id as read and avoid duplicated token ids upgradesToTokenIndex[_objects[i]] = _objects[i]; _objectsStats[i] = ethernautsStorage.getStats(_objects[i]); } // upgrading stats uint256 attack = _shipStats[uint(ShipStats.Attack)]; uint256 defense = _shipStats[uint(ShipStats.Defense)]; uint256 speed = _shipStats[uint(ShipStats.Speed)]; uint256 range = _shipStats[uint(ShipStats.Range)]; uint256 luck = _shipStats[uint(ShipStats.Luck)]; for(i = 0; i < SHIP_SLOTS; i++) { // Only objects with upgrades are allowed require(_objectsStats[i][1] + _objectsStats[i][2] + _objectsStats[i][3] + _objectsStats[i][4] + _objectsStats[i][5] > 0); attack += _objectsStats[i][uint(ShipStats.Attack)]; defense += _objectsStats[i][uint(ShipStats.Defense)]; speed += _objectsStats[i][uint(ShipStats.Speed)]; range += _objectsStats[i][uint(ShipStats.Range)]; luck += _objectsStats[i][uint(ShipStats.Luck)]; } if (attack > STATS_CAPOUT) { attack = STATS_CAPOUT; } if (defense > STATS_CAPOUT) { defense = STATS_CAPOUT; } if (speed > STATS_CAPOUT) { speed = STATS_CAPOUT; } if (range > STATS_CAPOUT) { range = STATS_CAPOUT; } if (luck > STATS_CAPOUT) { luck = STATS_CAPOUT; } // All stats must increase, even if its provided 5 upgrades in the slots require(attack > _shipStats[uint(ShipStats.Attack)]); require(defense > _shipStats[uint(ShipStats.Defense)]); require(speed > _shipStats[uint(ShipStats.Speed)]); require(range > _shipStats[uint(ShipStats.Range)]); require(luck > _shipStats[uint(ShipStats.Luck)]); _shipStats[uint(ShipStats.Level)] = uint8(level + 1); _shipStats[uint(ShipStats.Attack)] = uint8(attack); _shipStats[uint(ShipStats.Defense)] = uint8(defense); _shipStats[uint(ShipStats.Speed)] = uint8(speed); _shipStats[uint(ShipStats.Range)] = uint8(range); _shipStats[uint(ShipStats.Luck)] = uint8(luck); // only upgrade after confirmed transaction by Upgrade Ship Contract ethernautsStorage.updateStats(_tokenId, _shipStats); // mark all objects as used and change owner for(i = 0; i < _objects.length; i++) { ethernautsStorage.updateState(_objects[i], uint8(AssetState.Used)); // Register the approval and transfer to upgrade ship contract _approve(_objects[i], address(this)); _transferFrom(msg.sender, address(this), _objects[i]); } Upgrade(_tokenId); } function transfer( address _to, uint256 _tokenId ) external onlyOracle whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any assets // (except very briefly after it is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the storage contract to prevent accidental // misuse. Auction or Upgrade contracts should only take ownership of assets // through the allow + transferFrom flow. require(_to != address(ethernautsStorage)); // Contract needs to own asset. require(_owns(address(this), _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _approve(_tokenId, _to); ethernautsStorage.transfer(address(this), _to, _tokenId); } }
Safety check to prevent against an unexpected 0x0 default. Disallow transfers to this contract to prevent accidental misuse. The contract should never own any assets (except very briefly after it is created and before it goes on auction). Disallow transfers to the storage contract to prevent accidental misuse. Auction or Upgrade contracts should only take ownership of assets through the allow + transferFrom flow. Contract needs to own asset. Reassign ownership, clear pending approvals, emit Transfer event.
function transfer( address _to, uint256 _tokenId ) external onlyOracle whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(_to != address(ethernautsStorage)); require(_owns(address(this), _tokenId)); _approve(_tokenId, _to); ethernautsStorage.transfer(address(this), _to, _tokenId); }
14,876,199
pragma solidity ^0.4.20; /** * Authored by https://www.coinfabrik.com/ */ /** * @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; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() internal { 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)); owner = newOwner; } } /** * Abstract contract that allows children to implement an * emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. * */ contract Haltable is Ownable { bool public halted; event Halted(bool halted); modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; Halted(true); } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; Halted(false); } } /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint a, uint b) internal pure returns (uint) { return a >= b ? a : b; } function min256(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } } /** * Interface for the standard token. * Based on https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ interface EIP20Token { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool success); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); function allowance(address owner, address spender) public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /** ** Optional functions * function name() public view returns (string name); function symbol() public view returns (string symbol); function decimals() public view returns (uint8 decimals); * **/ } // Interface for burning tokens contract Burnable { // @dev Destroys tokens for an account // @param account Account whose tokens are destroyed // @param value Amount of tokens to destroy function burnTokens(address account, uint value) internal; event Burned(address account, uint value); } /** * Internal interface for the minting of tokens. */ contract Mintable { /** * @dev Mints tokens for an account * This function should emit the Minted event. */ function mintInternal(address receiver, uint amount) internal; /** Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); } /** * @title Standard token * @dev Basic implementation of the EIP20 standard token (also known as ERC20 token). */ contract StandardToken is EIP20Token, Burnable, Mintable { using SafeMath for uint; uint private total_supply; mapping(address => uint) private balances; mapping(address => mapping (address => uint)) private allowed; function totalSupply() public view returns (uint) { return total_supply; } /** * @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, uint value) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); return true; } /** * @dev Gets the balance of the specified address. * @param account The address whose balance is to be queried. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address account) public view returns (uint balance) { return balances[account]; } /** * @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 uint the amout of tokens to be transfered */ function transferFrom(address from, address to, uint value) public returns (bool success) { uint allowance = allowed[from][msg.sender]; // Check is not needed because sub(allowance, value) will already throw if this condition is not met // require(value <= allowance); // SafeMath uses assert instead of require though, beware when using an analysis tool balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowance.sub(value); Transfer(from, to, value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint value) public returns (bool success) { // To change the approve amount you first have to reduce the addresses' // allowance to zero by calling `approve(spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require (value == 0 || allowed[msg.sender][spender] == 0); allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param account address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still avaible for the spender. */ function allowance(address account, address spender) public view returns (uint remaining) { return allowed[account][spender]; } /** * Atomic increment of approved spending * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * */ function addApproval(address spender, uint addedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][spender]; allowed[msg.sender][spender] = oldValue.add(addedValue); Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } /** * Atomic decrement of approved spending. * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */ function subApproval(address spender, uint subtractedValue) public returns (bool success) { uint oldVal = allowed[msg.sender][spender]; if (subtractedValue > oldVal) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldVal.sub(subtractedValue); } Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } /** * @dev Provides an internal function for destroying tokens. Useful for upgrades. */ function burnTokens(address account, uint value) internal { balances[account] = balances[account].sub(value); total_supply = total_supply.sub(value); Transfer(account, 0, value); Burned(account, value); } /** * @dev Provides an internal minting function. */ function mintInternal(address receiver, uint amount) internal { total_supply = total_supply.add(amount); balances[receiver] = balances[receiver].add(amount); Minted(receiver, amount); // Beware: Address zero may be used for special transactions in a future fork. // This will make the mint transaction appear in EtherScan.io // We can remove this after there is a standardized minting event Transfer(0, receiver, amount); } } /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is StandardToken, Ownable { /* The finalizer contract that allows lifting the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Set the contract that can call release and make the token transferable. * * Since the owner of this contract is (or should be) the crowdsale, * it can only be called by a corresponding exposed API in the crowdsale contract in case of input error. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don't do interface check here as we might want to have a normal wallet address to act as a release agent. releaseAgent = addr; } /** * Owner can allow a particular address (e.g. a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } /** * One way function to release the tokens into the wild. * * Can be called only from the release agent that should typically be the finalize agent ICO contract. * In the scope of the crowdsale, it is only called if the crowdsale has been a success (first milestone reached). */ function releaseTokenTransfer() public onlyReleaseAgent { released = true; } /** * Limit token transfer until the crowdsale is over. */ modifier canTransfer(address sender) { require(released || transferAgents[sender]); _; } /** The function can be called only before or after the tokens have been released */ modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } /** We restrict transfer by overriding it */ function transfer(address to, uint value) public canTransfer(msg.sender) returns (bool success) { // Call StandardToken.transfer() return super.transfer(to, value); } /** We restrict transferFrom by overriding it */ function transferFrom(address from, address to, uint value) public canTransfer(from) returns (bool success) { // Call StandardToken.transferForm() return super.transferFrom(from, to, value); } } /** * Upgrade agent transfers tokens to a new contract. * Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting. * * The Upgrade agent is the interface used to implement a token * migration in the case of an emergency. * The function upgradeFrom has to implement the part of the creation * of new tokens on behalf of the user doing the upgrade. * * The new token can implement this interface directly, or use. */ contract UpgradeAgent { /** This value should be the same as the original token's total supply */ uint public originalSupply; /** Interface to ensure the contract is correctly configured */ function isUpgradeAgent() public pure returns (bool) { return true; } /** Upgrade an account When the token contract is in the upgrade status the each user will have to call `upgrade(value)` function from UpgradeableToken. The upgrade function adjust the balance of the user and the supply of the previous token and then call `upgradeFrom(value)`. The UpgradeAgent is the responsible to create the tokens for the user in the new contract. * @param from Account to upgrade. * @param value Tokens to upgrade. */ function upgradeFrom(address from, uint value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision. * */ contract UpgradeableToken is EIP20Token, Burnable { using SafeMath for uint; /** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint public totalUpgraded = 0; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet. This allows changing the upgrade agent while there is time. * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed from, address to, uint value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address master) internal { setUpgradeMaster(master); } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint value) public { UpgradeState state = getUpgradeState(); // Ensure it's not called in a bad state require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading); // Validate input value. require(value != 0); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); // Take tokens out from circulation burnTokens(msg.sender, value); totalUpgraded = totalUpgraded.add(value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles the upgrade process */ function setUpgradeAgent(address agent) onlyMaster external { // Check whether the token is in a state that we could think of upgrading require(canUpgrade()); require(agent != 0x0); // Upgrade has already begun for an agent require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent); // Bad interface require(upgradeAgent.isUpgradeAgent()); // Make sure that token supplies match in source and target require(upgradeAgent.originalSupply() == totalSupply()); UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public view returns(UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if (address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function changeUpgradeMaster(address new_master) onlyMaster public { setUpgradeMaster(new_master); } /** * Internal upgrade master setter. */ function setUpgradeMaster(address new_master) private { require(new_master != 0x0); upgradeMaster = new_master; } /** * Child contract can override to provide the condition in which the upgrade can begin. */ function canUpgrade() public view returns(bool) { return true; } modifier onlyMaster() { require(msg.sender == upgradeMaster); _; } } // This contract aims to provide an inheritable way to recover tokens from a contract not meant to hold tokens // To use this contract, have your token-ignoring contract inherit this one and implement getLostAndFoundMaster to decide who can move lost tokens. // Of course, this contract imposes support costs upon whoever is the lost and found master. contract LostAndFoundToken { /** * @return Address of the account that handles movements. */ function getLostAndFoundMaster() internal view returns (address); /** * @param agent Address that will be able to move tokens with transferFrom * @param tokens Amount of tokens approved for transfer * @param token_contract Contract of the token */ function enableLostAndFound(address agent, uint tokens, EIP20Token token_contract) public { require(msg.sender == getLostAndFoundMaster()); // We use approve instead of transfer to minimize the possibility of the lost and found master // getting them stuck in another address by accident. token_contract.approve(agent, tokens); } } /** * A public interface to increase the supply of a token. * * This allows uncapped crowdsale by dynamically increasing the supply when money pours in. * Only mint agents, usually contracts whitelisted by the owner, can mint new tokens. * */ contract MintableToken is Mintable, Ownable { using SafeMath for uint; bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state); function MintableToken(uint initialSupply, address multisig, bool mintable) internal { require(multisig != address(0)); // Cannot create a token without supply and no minting require(mintable || initialSupply != 0); // Create initially all balance on the team multisig if (initialSupply > 0) mintInternal(multisig, initialSupply); // No more new supply allowed after the token creation mintingFinished = !mintable; } /** * Create new tokens and allocate them to an address. * * Only callable by a mint agent (e.g. crowdsale contract). */ function mint(address receiver, uint amount) onlyMintAgent canMint public { mintInternal(receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { // Only mint agents are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** Make sure we are not done yet. */ modifier canMint() { require(!mintingFinished); _; } } /** * A crowdsale token. * * An ERC-20 token designed specifically for crowdsales with investor protection and further development path. * * - The token transfer() is disabled until the crowdsale is over * - The token contract gives an opt-in upgrade path to a new contract * - The same token can be part of several crowdsales through the approve() mechanism * - The token can be capped (supply set in the constructor) or uncapped (crowdsale contract can mint new tokens) * - ERC20 tokens transferred to this contract can be recovered by a lost and found master * */ contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken, LostAndFoundToken { string public name = "Ubanx"; string public symbol = "BANX"; uint8 public decimals; address public lost_and_found_master; /** * Construct the token. * * This token must be created through a team multisig wallet, so that it is owned by that wallet. * * @param initial_supply How many tokens we start with. * @param token_decimals Number of decimal places. * @param team_multisig Address of the multisig that receives the initial supply and is set as the upgrade master. * @param mintable Are new tokens created over the crowdsale or do we distribute only the initial supply? Note that when the token becomes transferable the minting always ends. * @param token_retriever Address of the account that handles ERC20 tokens that were accidentally sent to this contract. */ function CrowdsaleToken(uint initial_supply, uint8 token_decimals, address team_multisig, bool mintable, address token_retriever) public UpgradeableToken(team_multisig) MintableToken(initial_supply, team_multisig, mintable) { require(token_retriever != address(0)); decimals = token_decimals; lost_and_found_master = token_retriever; } /** * When token is released to be transferable, prohibit new token creation. */ function releaseTokenTransfer() public onlyReleaseAgent { mintingFinished = true; super.releaseTokenTransfer(); } /** * Allow upgrade agent functionality to kick in only if the crowdsale was a success. */ function canUpgrade() public view returns(bool) { return released && super.canUpgrade(); } function getLostAndFoundMaster() internal view returns(address) { return lost_and_found_master; } /** * We allow anyone to burn their tokens if they wish to do so. * We want to use this in the finalize function of the crowdsale in particular. */ function burn(uint amount) public { burnTokens(msg.sender, amount); } } /** * Abstract base contract for token sales. * * Handles * - start and end dates * - accepting investments * - various statistics during the crowdfund * - different investment policies (require server side customer id, allow only whitelisted addresses) * */ contract GenericCrowdsale is Haltable { using SafeMath for uint; /* The token we are selling */ CrowdsaleToken public token; /* ether will be transferred to this address */ address public multisigWallet; /* a contract may be deployed to function as a gateway for investments */ address public investmentGateway; /* the starting time of the crowdsale */ uint public startsAt; /* the ending time of the crowdsale */ uint public endsAt; /* the number of tokens already sold through this contract*/ uint public tokensSold = 0; /* How many wei of funding we have raised */ uint public weiRaised = 0; /* How many distinct addresses have invested */ uint public investorCount = 0; /* Has this crowdsale been finalized */ bool public finalized = false; /* Do we need to have a unique contributor id for each customer */ bool public requireCustomerId = false; /** * Do we verify that contributor has been cleared on the server side (accredited investors only). * This method was first used in the FirstBlood crowdsale to ensure all contributors had accepted terms of sale (on the web). */ bool public requiredSignedAddress = false; /** Server side address that signed allowed contributors (Ethereum addresses) that can participate the crowdsale */ address public signerAddress; /** How many ETH each address has invested in this crowdsale */ mapping (address => uint) public investedAmountOf; /** How many tokens this crowdsale has credited for each investor address */ mapping (address => uint) public tokenAmountOf; /** Addresses that are allowed to invest even before ICO officially opens. For testing, for ICO partners, etc. */ mapping (address => bool) public earlyParticipantWhitelist; /** State machine * * - Prefunding: We have not reached the starting time yet * - Funding: Active crowdsale * - Success: Crowdsale ended * - Finalized: The finalize function has been called and succesfully executed */ enum State{Unknown, PreFunding, Funding, Success, Finalized} // A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); // The rules about what kind of investments we accept were changed event InvestmentPolicyChanged(bool requireCId, bool requireSignedAddress, address signer); // Address early participation whitelist status changed event Whitelisted(address addr, bool status); // Crowdsale's finalize function has been called event Finalized(); /** * Basic constructor for the crowdsale. * @param team_multisig Address of the multisignature wallet of the team that will receive all the funds contributed in the crowdsale. * @param start Block number where the crowdsale will be officially started. It should be greater than the block number in which the contract is deployed. * @param end Block number where the crowdsale finishes. No tokens can be sold through this contract after this block. */ function GenericCrowdsale(address team_multisig, uint start, uint end) internal { setMultisig(team_multisig); // Don't mess the dates require(start != 0 && end != 0); require(block.timestamp < start && start < end); startsAt = start; endsAt = end; } /** * Default fallback behaviour is to call buy. * Ideally, no contract calls this crowdsale without supporting ERC20. * However, some sort of refunding function may be desired to cover such situations. */ function() payable public { buy(); } /** * Make an investment. * * The crowdsale must be running for one to invest. * We must have not pressed the emergency brake. * * @param receiver The Ethereum address who receives the tokens * @param customerId (optional) UUID v4 to track the successful payments on the server side * */ function investInternal(address receiver, uint128 customerId) stopInEmergency notFinished private { // Determine if it's a good time to accept investment from this participant if (getState() == State.PreFunding) { // Are we whitelisted for early deposit require(earlyParticipantWhitelist[msg.sender]); } uint weiAmount; uint tokenAmount; (weiAmount, tokenAmount) = calculateTokenAmount(msg.value, receiver); // Sanity check against bad implementation. assert(weiAmount <= msg.value); // Dust transaction if no tokens can be given require(tokenAmount != 0); if (investedAmountOf[receiver] == 0) { // A new investor investorCount++; } updateInvestorFunds(tokenAmount, weiAmount, receiver, customerId); // Pocket the money multisigWallet.transfer(weiAmount); // Return excess of money returnExcedent(msg.value.sub(weiAmount), msg.sender); } /** * Preallocate tokens for the early investors. * * Preallocated tokens have been sold before the actual crowdsale opens. * This function mints the tokens and moves the crowdsale needle. * * No money is exchanged, as the crowdsale team already have received the payment. * * @param receiver Account that receives the tokens. * @param fullTokens tokens as full tokens - decimal places are added internally. * @param weiPrice Price of a single indivisible token in wei. * */ function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner notFinished { require(receiver != address(0)); uint tokenAmount = fullTokens.mul(10**uint(token.decimals())); require(tokenAmount != 0); uint weiAmount = weiPrice.mul(tokenAmount); // This can also be 0, in which case we give out tokens for free updateInvestorFunds(tokenAmount, weiAmount, receiver , 0); } /** * Private function to update accounting in the crowdsale. */ function updateInvestorFunds(uint tokenAmount, uint weiAmount, address receiver, uint128 customerId) private { // Update investor investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount); // Update totals weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokenAmount); assignTokens(receiver, tokenAmount); // Tell us that the investment was completed successfully Invested(receiver, weiAmount, tokenAmount, customerId); } /** * Investing function that recognizes the receiver and verifies he is allowed to invest. * * @param customerId UUIDv4 that identifies this contributor */ function buyOnBehalfWithSignedAddress(address receiver, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable validCustomerId(customerId) { bytes32 hash = sha256(receiver); require(ecrecover(hash, v, r, s) == signerAddress); investInternal(receiver, customerId); } /** * Investing function that recognizes the receiver. * * @param customerId UUIDv4 that identifies this contributor */ function buyOnBehalfWithCustomerId(address receiver, uint128 customerId) public payable validCustomerId(customerId) unsignedBuyAllowed { investInternal(receiver, customerId); } /** * Buys tokens on behalf of an address. * * Pay for funding, get invested tokens back in the receiver address. */ function buyOnBehalf(address receiver) public payable { require(!requiredSignedAddress || msg.sender == investmentGateway); require(!requireCustomerId); // Crowdsale needs to track participants for thank you email investInternal(receiver, 0); } function setInvestmentGateway(address gateway) public onlyOwner { require(gateway != address(0)); investmentGateway = gateway; } /** * Investing function that recognizes the payer and verifies he is allowed to invest. * * @param customerId UUIDv4 that identifies this contributor */ function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { buyOnBehalfWithSignedAddress(msg.sender, customerId, v, r, s); } /** * Investing function that recognizes the payer. * * @param customerId UUIDv4 that identifies this contributor */ function buyWithCustomerId(uint128 customerId) public payable { buyOnBehalfWithCustomerId(msg.sender, customerId); } /** * The basic entry point to participate in the crowdsale process. * * Pay for funding, get invested tokens back in the sender address. */ function buy() public payable { buyOnBehalf(msg.sender); } /** * Finalize a succcesful crowdsale. * * The owner can trigger post-crowdsale actions, like releasing the tokens. * Note that by default tokens are not in a released state. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { finalized = true; Finalized(); } /** * Set policy do we need to have server-side customer ids for the investments. * */ function setRequireCustomerId(bool value) public onlyOwner { requireCustomerId = value; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } /** * Set policy if all investors must be cleared on the server side first. * * This is e.g. for the accredited investor clearing. * */ function setRequireSignedAddress(bool value, address signer) public onlyOwner { requiredSignedAddress = value; signerAddress = signer; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } /** * Allow addresses to do early participation. */ function setEarlyParticipantWhitelist(address addr, bool status) public onlyOwner notFinished stopInEmergency { earlyParticipantWhitelist[addr] = status; Whitelisted(addr, status); } /** * Internal setter for the multisig wallet */ function setMultisig(address addr) internal { require(addr != 0); multisigWallet = addr; } /** * Crowdfund state machine management. * * This function has the timed transition builtin. * So there is no chance of the variable being stale. */ function getState() public view returns (State) { if (finalized) return State.Finalized; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else return State.Success; } /** Internal functions that exist to provide inversion of control should they be overriden */ /** Interface for the concrete instance to interact with the token contract in a customizable way */ function assignTokens(address receiver, uint tokenAmount) internal; /** * Determine if the goal was already reached in the current crowdsale */ function isCrowdsaleFull() internal view returns (bool full); /** * Returns any excess wei received * * This function can be overriden to provide a different refunding method. */ function returnExcedent(uint excedent, address receiver) internal { if (excedent > 0) { receiver.transfer(excedent); } } /** * Calculate the amount of tokens that corresponds to the received amount. * The wei amount is returned too in case not all of it can be invested. * * Note: When there's an excedent due to rounding error, it should be returned to allow refunding. * This is worked around in the current design using an appropriate amount of decimals in the FractionalERC20 standard. * The workaround is good enough for most use cases, hence the simplified function signature. * @return weiAllowed The amount of wei accepted in this transaction. * @return tokenAmount The tokens that are assigned to the receiver in this transaction. */ function calculateTokenAmount(uint weiAmount, address receiver) internal view returns (uint weiAllowed, uint tokenAmount); // // Modifiers // modifier inState(State state) { require(getState() == state); _; } modifier unsignedBuyAllowed() { require(!requiredSignedAddress); _; } /** Modifier allowing execution only if the crowdsale is currently running. */ modifier notFinished() { State current_state = getState(); require(current_state == State.PreFunding || current_state == State.Funding); _; } modifier validCustomerId(uint128 customerId) { require(customerId != 0); // UUIDv4 sanity check _; } } /// @dev Tranche based pricing. /// Implementing "first price" tranches, meaning, that if a buyer's order is /// covering more than one tranche, the price of the lowest tranche will apply /// to the whole order. contract TokenTranchePricing { using SafeMath for uint; /** * Define pricing schedule using tranches. */ struct Tranche { // Amount in tokens when this tranche becomes inactive uint amount; // Time interval [start, end) // Starting timestamp (included in the interval) uint start; // Ending timestamp (excluded from the interval) uint end; // How many tokens per asset unit you will get while this tranche is active uint price; } // We define offsets and size for the deserialization of ordered tuples in raw arrays uint private constant amount_offset = 0; uint private constant start_offset = 1; uint private constant end_offset = 2; uint private constant price_offset = 3; uint private constant tranche_size = 4; Tranche[] public tranches; function getTranchesLength() public view returns (uint) { return tranches.length; } /// @dev Construction, creating a list of tranches /// @param init_tranches Raw array of ordered tuples: (end amount, start timestamp, end timestamp, price) function TokenTranchePricing(uint[] init_tranches) public { // Need to have tuples, length check require(init_tranches.length % tranche_size == 0); // A tranche with amount zero can never be selected and is therefore useless. // This check and the one inside the loop ensure no tranche can have an amount equal to zero. require(init_tranches[amount_offset] > 0); uint input_tranches_length = init_tranches.length.div(tranche_size); Tranche memory last_tranche; for (uint i = 0; i < input_tranches_length; i++) { uint tranche_offset = i.mul(tranche_size); uint amount = init_tranches[tranche_offset.add(amount_offset)]; uint start = init_tranches[tranche_offset.add(start_offset)]; uint end = init_tranches[tranche_offset.add(end_offset)]; uint price = init_tranches[tranche_offset.add(price_offset)]; // No invalid steps require(block.timestamp < start && start < end); // Bail out when entering unnecessary tranches // This is preferably checked before deploying contract into any blockchain. require(i == 0 || (end >= last_tranche.end && amount > last_tranche.amount) || (end > last_tranche.end && amount >= last_tranche.amount)); last_tranche = Tranche(amount, start, end, price); tranches.push(last_tranche); } } /// @dev Get the current tranche or bail out if there is no tranche defined for the current block. /// @param tokensSold total amount of tokens sold, for calculating the current tranche /// @return Returns the struct representing the current tranche function getCurrentTranche(uint tokensSold) private view returns (Tranche storage) { for (uint i = 0; i < tranches.length; i++) { if (tranches[i].start <= block.timestamp && block.timestamp < tranches[i].end && tokensSold < tranches[i].amount) { return tranches[i]; } } // No tranche is currently active revert(); } /// @dev Get the current price. May revert if there is no tranche currently active. /// @param tokensSold total amount of tokens sold, for calculating the current tranche /// @return The current price function getCurrentPrice(uint tokensSold) internal view returns (uint result) { return getCurrentTranche(tokensSold).price; } } // Simple deployment information store inside contract storage. contract DeploymentInfo { uint private deployed_on; function DeploymentInfo() public { deployed_on = block.number; } function getDeploymentBlock() public view returns (uint) { return deployed_on; } } // This contract has the sole objective of providing a sane concrete instance of the Crowdsale contract. contract Crowdsale is GenericCrowdsale, LostAndFoundToken, TokenTranchePricing, DeploymentInfo { uint8 private constant token_decimals = 18; // Initial supply is 400k, tokens put up on sale are obtained from the initial minting uint private constant token_initial_supply = 4 * (10 ** 8) * (10 ** uint(token_decimals)); bool private constant token_mintable = true; uint private constant sellable_tokens = 6 * (10 ** 8) * (10 ** uint(token_decimals)); // Sets minimum value that can be bought uint public minimum_buy_value = 18 * 1 ether / 1000; // Eth price multiplied by 1000; uint public milieurs_per_eth; // Address allowed to update eth price. address rate_admin; /** * Constructor for the crowdsale. * Normally, the token contract is created here. That way, the minting, release and transfer agents can be set here too. * * @param eth_price_in_eurs Ether price in EUR. * @param team_multisig Address of the multisignature wallet of the team that will receive all the funds contributed in the crowdsale. * @param start Block number where the crowdsale will be officially started. It should be greater than the block number in which the contract is deployed. * @param end Block number where the crowdsale finishes. No tokens can be sold through this contract after this block. * @param token_retriever Address that will handle tokens accidentally sent to the token contract. See the LostAndFoundToken and CrowdsaleToken contracts for further details. * @param init_tranches List of serialized tranches. See config.js and TokenTranchePricing for further details. */ function Crowdsale(uint eth_price_in_eurs, address team_multisig, uint start, uint end, address token_retriever, uint[] init_tranches) GenericCrowdsale(team_multisig, start, end) TokenTranchePricing(init_tranches) public { require(end == tranches[tranches.length.sub(1)].end); // Testing values token = new CrowdsaleToken(token_initial_supply, token_decimals, team_multisig, token_mintable, token_retriever); //Set eth price in EUR (multiplied by one thousand) updateEursPerEth(eth_price_in_eurs); // Set permissions to mint, transfer and release token.setMintAgent(address(this), true); token.setTransferAgent(address(this), true); token.setReleaseAgent(address(this)); // Allow the multisig to transfer tokens token.setTransferAgent(team_multisig, true); // Tokens to be sold through this contract token.mint(address(this), sellable_tokens); // We don't need to mint anymore during the lifetime of the contract. token.setMintAgent(address(this), false); } //Token assignation through transfer function assignTokens(address receiver, uint tokenAmount) internal { token.transfer(receiver, tokenAmount); } //Token amount calculation function calculateTokenAmount(uint weiAmount, address) internal view returns (uint weiAllowed, uint tokenAmount) { uint tokensPerEth = getCurrentPrice(tokensSold).mul(milieurs_per_eth).div(1000); uint maxWeiAllowed = sellable_tokens.sub(tokensSold).mul(1 ether).div(tokensPerEth); weiAllowed = maxWeiAllowed.min256(weiAmount); if (weiAmount < maxWeiAllowed) { //Divided by 1000 because eth eth_price_in_eurs is multiplied by 1000 tokenAmount = tokensPerEth.mul(weiAmount).div(1 ether); } // With this case we let the crowdsale end even when there are rounding errors due to the tokens to wei ratio else { tokenAmount = sellable_tokens.sub(tokensSold); } } // Implements the criterion of the funding state function isCrowdsaleFull() internal view returns (bool) { return tokensSold >= sellable_tokens; } /** * This function decides who handles lost tokens. * Do note that this function is NOT meant to be used in a token refund mechanism. * Its sole purpose is determining who can move around ERC20 tokens accidentally sent to this contract. */ function getLostAndFoundMaster() internal view returns (address) { return owner; } /** * @dev Sets new minimum buy value for a transaction. Only the owner can call it. */ function setMinimumBuyValue(uint newValue) public onlyOwner { minimum_buy_value = newValue; } /** * Investing function that recognizes the payer and verifies that he is allowed to invest. * * Overwritten to add configurable minimum value * * @param customerId UUIDv4 that identifies this contributor */ function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable investmentIsBigEnough(msg.sender) validCustomerId(customerId) { super.buyWithSignedAddress(customerId, v, r, s); } /** * Investing function that recognizes the payer. * * @param customerId UUIDv4 that identifies this contributor */ function buyWithCustomerId(uint128 customerId) public payable investmentIsBigEnough(msg.sender) validCustomerId(customerId) unsignedBuyAllowed { super.buyWithCustomerId(customerId); } /** * The basic entry point to participate in the crowdsale process. * * Pay for funding, get invested tokens back in the sender address. */ function buy() public payable investmentIsBigEnough(msg.sender) unsignedBuyAllowed { super.buy(); } // Extended to transfer half of the unused funds to the team's multisig and release the token function finalize() public inState(State.Success) onlyOwner stopInEmergency { token.releaseTokenTransfer(); uint unsoldTokens = token.balanceOf(address(this)); token.transfer(multisigWallet, unsoldTokens); super.finalize(); } //Change the the starting time in order to end the presale period early if needed. function setStartingTime(uint startingTime) public onlyOwner inState(State.PreFunding) { require(startingTime > block.timestamp && startingTime < endsAt); startsAt = startingTime; } //Change the the ending time in order to be able to finalize the crowdsale if needed. function setEndingTime(uint endingTime) public onlyOwner notFinished { require(endingTime > block.timestamp && endingTime > startsAt); endsAt = endingTime; } /** * Override to reject calls unless the crowdsale is finalized or * the token contract is not the one corresponding to this crowdsale */ function enableLostAndFound(address agent, uint tokens, EIP20Token token_contract) public { // Either the state is finalized or the token_contract is not this crowdsale token require(address(token_contract) != address(token) || getState() == State.Finalized); super.enableLostAndFound(agent, tokens, token_contract); } function updateEursPerEth(uint milieurs_amount) public { require(msg.sender == owner || msg.sender == rate_admin); require(milieurs_amount >= 100); milieurs_per_eth = milieurs_amount; } function setRateAdmin(address admin) public onlyOwner { rate_admin = admin; } modifier investmentIsBigEnough(address agent) { require(msg.value.add(investedAmountOf[agent]) >= minimum_buy_value); _; } }
Buys tokens on behalf of an address. Pay for funding, get invested tokens back in the receiver address./
function buyOnBehalf(address receiver) public payable { require(!requiredSignedAddress || msg.sender == investmentGateway); investInternal(receiver, 0); }
12,579,240
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 uint256 airlineCount; struct Airline { address airlineAddress; bool isRegistered; string airlineName; address[] voted; uint256 funds; } struct Passenger { string name; address wallet; uint256 credit; mapping(string => uint256) flightInsurances; } mapping(string => address[]) private passengersInsuredForFlight; mapping (address => Passenger) private passengers; mapping(address => Airline) private airlines; mapping(address => bool) authorizedContracts; uint8 private constant MULTIPARTY_MIN_AIRLINES = 4; uint256 private constant AIRLINE_MIN_FUNDS = 10 ether; uint8 private constant max_insurance_amount = 1; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor (address firstAirline ) public { contractOwner = msg.sender; airlines[firstAirline] = Airline({ airlineAddress : firstAirline, isRegistered : true, airlineName : "MyFirstAirline", voted : new address[](0), funds: 0 }); airlineCount = 1; } /********************************************************************************************/ /* 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 isAuthorizedCaller() { require(authorizedContracts[msg.sender] == true, "Caller is not authorized"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() external view returns(bool) { return operational; } function getFunds(address airline) external view returns(uint256){ uint256 amount = airlines[airline].funds; return amount; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; } function authorizeCaller(address appContract) requireContractOwner external { authorizedContracts[appContract] = true; } function isAirlineRegistered(address airline) external view requireIsOperational returns(bool){ bool isAirline = false; if(airlines[airline].isRegistered == true){ isAirline = true; } return isAirline; } function isFunded(address airline) external view returns(bool) { bool funded = false; if(airlines[airline].funds >= AIRLINE_MIN_FUNDS){ funded = true; } return funded; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline (address newAddress, string name ) requireIsOperational isAuthorizedCaller external returns (bool) { require(newAddress != address(0), "'airlineAddress' must be a valid address."); require(!airlines[newAddress].isRegistered, "Airline is already registered."); if(airlineCount < MULTIPARTY_MIN_AIRLINES){ // no multisig required airlines[newAddress] = Airline({ airlineAddress : newAddress, isRegistered : true, airlineName : name, voted: new address[](0), funds: 0 }); airlineCount ++; } else{ //if the nr of airlines is > 4, meaning that multisig is required bool isDuplicate = false; //check if the requestor already voted for this airline to be added for (uint c=0; c <airlines[newAddress].voted.length; c++){ if (airlines[newAddress].voted[c] == msg.sender){ isDuplicate = true; break; } } require(!isDuplicate, "This party has already voted"); //push requestor to array of addresses that voted airlines[newAddress].voted.push(msg.sender); //check if limit has been reached and if so, set registration to true. if(airlines[newAddress].voted.length >= airlineCount.div(2)) { airlines[newAddress].isRegistered = true; airlines[newAddress].airlineName = name; airlines[newAddress].airlineAddress = newAddress; airlineCount ++; } } return (true); } /** * @dev Buy insurance for a flight * */ function buy (string flightCode, string passengerName) requireIsOperational isAuthorizedCaller external payable { require(msg.value > 0, "One should at least deposit some money to insure him or herself"); require(msg.value <= max_insurance_amount, "One cannot insurance for more than 1 ETH"); passengers[msg.sender] = Passenger({ name : passengerName, wallet : msg.sender, credit : 0 }); // add insured value to passenger data passengers[msg.sender].flightInsurances[flightCode] = msg.value; //add passenger to list of people that insured themselves for the specific flight, so that when crediting we do not need to loop over all passengers passengersInsuredForFlight[flightCode].push(msg.sender); } /** * @dev Credits payouts to insurees */ function creditInsurees ( string flightCode ) requireIsOperational isAuthorizedCaller external { for (uint256 c = 0; c < passengersInsuredForFlight[flightCode].length; c++) { address insuredPassengerAddress = passengersInsuredForFlight[flightCode][c]; if(passengers[insuredPassengerAddress].flightInsurances[flightCode] != 0) { uint256 currentCredit = passengers[insuredPassengerAddress].credit; uint256 insuranceAmount = passengers[insuredPassengerAddress].flightInsurances[flightCode]; passengers[insuredPassengerAddress].flightInsurances[flightCode] = 0; //reset to 0 passengers[insuredPassengerAddress].credit = currentCredit + insuranceAmount + insuranceAmount.div(2); //credit passenger } } } /** * @dev Transfers eligible payout funds to insuree * */ function pay (address insuredPassenger ) requireIsOperational isAuthorizedCaller external { require(msg.sender == insuredPassenger, 'Only passenger can withdraw his own credit'); require(passengers[insuredPassenger].credit > 0, 'You do not have any credit to withdraw'); uint256 credit = passengers[insuredPassenger].credit; passengers[insuredPassenger].credit = 0; //reset credit first insuredPassenger.transfer(credit); //payout } /** * @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 airline, uint256 amount) requireIsOperational isAuthorizedCaller external returns (uint256) { airlines[airline].funds += amount; return airlines[airline].funds; } // function getFlightKey // ( // address airline, // string memory flight, // uint256 timestamp // ) // pure // internal // returns(bytes32) // { // return keccak256(abi.encodePacked(airline, flight, timestamp)); // } /** * @dev Fallback function for funding smart contract. * */ function () external payable { } }
Credits payouts to insurees/
{ function creditInsurees ( string flightCode ) requireIsOperational isAuthorizedCaller external for (uint256 c = 0; c < passengersInsuredForFlight[flightCode].length; c++) { address insuredPassengerAddress = passengersInsuredForFlight[flightCode][c]; if(passengers[insuredPassengerAddress].flightInsurances[flightCode] != 0) { uint256 currentCredit = passengers[insuredPassengerAddress].credit; uint256 insuranceAmount = passengers[insuredPassengerAddress].flightInsurances[flightCode]; } } function creditInsurees ( string flightCode ) requireIsOperational isAuthorizedCaller external for (uint256 c = 0; c < passengersInsuredForFlight[flightCode].length; c++) { address insuredPassengerAddress = passengersInsuredForFlight[flightCode][c]; if(passengers[insuredPassengerAddress].flightInsurances[flightCode] != 0) { uint256 currentCredit = passengers[insuredPassengerAddress].credit; uint256 insuranceAmount = passengers[insuredPassengerAddress].flightInsurances[flightCode]; } } }
5,510,457
./partial_match/1/0x2Cf28B3123A87df592dDF1162A99D62783ebfb59/sources/CNPTtreasureIsland2023.sol
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; } using EnumerableSet for EnumerableSet.AddressSet; IContractAllowListProxy public cal; EnumerableSet.AddressSet localAllowedAddresses; uint256 public calLevel = 1; bool public enableRestrict = true;
15,914,454
pragma solidity ^0.6.0; import "./Reputation.sol"; import "./Finalizer.sol"; /** * @title Arena contract handles the main logic for decimal odds betting */ contract Arena is Finalizer, Reputation{ uint256 public uuid; address owner; struct Match { address admin; uint256 teamA; uint256 teamB; uint256 winner; uint256 totalPayoutA; uint256 totalPayoutB; uint256 bookieMargin; uint256 totalCollection; uint256 bookiePayout; uint256 oddsA; //Granularity - 100 uint256 oddsB; string apiUrl; //API url to retrieve the winner of the match bool ended; uint256[] oddsHistoryA; uint256[] oddsHistoryB; mapping(address => mapping(uint256 => uint256)) betA; mapping(address => mapping(uint256 => uint256)) betB; } mapping(uint256 => Match) public idToMatch; constructor() public Finalizer() { uuid = 1; owner = msg.sender; } /** * @notice createMatch enables the setting up of a new betting book for a match. * @param _teamA id of first team * @param _teamB id of second team * @param _oddsA initial odds for team A * @param _oddsB initial odds for team B * @param _url result url */ function createMatch( uint256 _teamA, uint256 _teamB, uint256 _oddsA, uint256 _oddsB, string memory _url ) public payable validOdds(_oddsA, _oddsB) { Match memory newMatch = Match( msg.sender, _teamA, _teamB, 0, 0, 0, msg.value, 0, 0, _oddsA, _oddsB, _url, false, new uint256[](0), new uint256[](0) ); idToMatch[uuid] = newMatch; idToMatch[uuid].oddsHistoryA.push(_oddsA); idToMatch[uuid].oddsHistoryB.push(_oddsB); uuid++; } /** * @notice allows placing of bets * @param _matchId the id of the match * @param _team The team being selected */ function bet(uint256 _matchId, uint256 _team) public payable validBet(_matchId) { Match storage _match = idToMatch[_matchId]; if(_team == 0) { _match.betA[msg.sender][_match.oddsA] += msg.value; _match.totalPayoutA += (msg.value * _match.oddsA) / 100; } else if(_team == 1) { _match.betB[msg.sender][_match.oddsB] += msg.value; _match.totalPayoutB += (msg.value * _match.oddsB) / 100; } _match.totalCollection += msg.value; } /** * @notice allows the admin to change the odds */ function changeOdds(uint256 _matchId, uint256 _oddsA, uint256 _oddsB) public onlyAdmin(_matchId) validOdds(_oddsA, _oddsB){ Match storage _match = idToMatch[_matchId]; require(!_match.ended, "match has ended"); if(_oddsA != _match.oddsA) { _match.oddsA = _oddsA; _match.oddsHistoryA.push(_oddsA); } if(_oddsB != _match.oddsB) { _match.oddsB = _oddsB; _match.oddsHistoryB.push(_oddsB); } } /** * @notice allows the admin to add to the margin of a bet */ function addMargin(uint256 _matchId) public payable onlyAdmin(_matchId) { Match storage _match = idToMatch[_matchId]; require(!_match.ended, "not allowed"); require(msg.value > 0, "invalid amount"); _match.bookieMargin += msg.value; } /** * @notice allows the admin to close a match that is over */ function closeMatch(uint256 _matchId) public onlyAdmin(_matchId) { Match storage _match = idToMatch[_matchId]; require(!_match.ended, "match has already ended"); requestResult(_match.apiUrl, _matchId, this.setResult.selector); } /** * @notice called by the oracle to set the result */ function setResult(bytes32 _requestId, uint256 _result) public recordChainlinkFulfillment(_requestId){ uint256 _id = requestIdToMatch[_requestId]; Match storage _match = idToMatch[_id]; _match.ended = true; _match.winner = _result; if(_result == _match.teamA){ require((_match.totalCollection + _match.bookieMargin) >= _match.totalPayoutA, "insufficient payout amount"); _match.bookiePayout = (_match.totalCollection + _match.bookieMargin) - _match.totalPayoutA; } else if(_result == _match.teamB) { require((_match.totalCollection + _match.bookieMargin) >= _match.totalPayoutB, "insufficient payout amount"); _match.bookiePayout = (_match.totalCollection + _match.bookieMargin) - _match.totalPayoutB; } increaseRep(_match.admin); } /** * @notice allows the bettor to retrieve payout if they have won. */ function retrievePayout(uint256 _matchId, uint256 _odds) public { Match storage _match = idToMatch[_matchId]; require(_match.ended, "match has not been closed"); if(_match.winner != 0) { if(_match.winner == _match.teamA) { require(_match.betA[msg.sender][_odds] > 0, "no payout for this odds"); uint256 _amt = (_match.betA[msg.sender][_odds] * _odds) / 100; _match.betA[msg.sender][_odds] = 0; (bool success, ) = msg.sender.call.value(_amt)(""); require(success, "transfer failed"); } else { require(_match.betB[msg.sender][_odds] > 0, "no payout for this odds"); uint256 _amt = (_match.betB[msg.sender][_odds] * _odds) / 100; _match.betB[msg.sender][_odds] = 0; (bool success, ) = msg.sender.call.value(_amt)(""); require(success, "transfer failed"); } } else { if(_match.betA[msg.sender][_odds] > 0) { uint256 _amt = _match.betA[msg.sender][_odds]; _match.betA[msg.sender][_odds] = 0; (bool success, ) = msg.sender.call.value(_amt)(""); require(success, "transfer failed"); } if(_match.betB[msg.sender][_odds] > 0) { uint256 _amt = _match.betB[msg.sender][_odds]; _match.betB[msg.sender][_odds] = 0; (bool success, ) = msg.sender.call.value(_amt)(""); require(success, "transfer failed"); } } } /** * @notice allows the owner of the dapp to margin call a bookie */ function marginCall(uint256 _matchId) public { require(msg.sender == owner, "not authorized"); Match storage _match = idToMatch[_matchId]; require(!_match.ended, "match has ended"); require((_match.totalCollection + _match.bookieMargin) < _match.totalPayoutA || (_match.totalCollection + _match.bookieMargin) < _match.totalPayoutB, "margin satisfied"); _match.ended = true; (bool success1, ) = msg.sender.call.value(_match.bookieMargin / 5)(""); require(success1, "transaction failed"); (bool success2, ) = _match.admin.call.value((_match.bookieMargin * 4) / 5)(""); require(success2, "transaction failed"); decreaseRep(_match.admin); } /** * @notice allows the admin of a match to retrieve the payout */ function retrieveBookiePayout(uint256 _matchId) onlyAdmin(_matchId) public { Match storage _match = idToMatch[_matchId]; require(_match.ended, "match is yet to end"); require(_match.bookiePayout > 0, "no payout"); uint256 _amt = _match.bookiePayout; _match.bookiePayout = 0; (bool success, ) = msg.sender.call.value(_amt)(""); require(success, "transaction failed"); } /** * @notice utility to help get the odds history */ function getOddsHistory(uint256 _matchId) public view returns(uint256[] memory, uint256[] memory) { Match storage _match = idToMatch[_matchId]; return(_match.oddsHistoryA, _match.oddsHistoryB); } /** * @notice utility to get the bet for a specific odds */ function getBetA(uint256 _matchId, uint256 _odds) public view returns(uint256) { Match storage _match = idToMatch[_matchId]; return _match.betA[msg.sender][_odds]; } /** * @notice utility to get the bet for a specific odds */ function getBetB(uint256 _matchId, uint256 _odds) public view returns(uint256) { Match storage _match = idToMatch[_matchId]; return _match.betB[msg.sender][_odds]; } modifier onlyAdmin(uint256 _id) { Match storage _match = idToMatch[_id]; require(msg.sender == _match.admin, "not authorized"); _; } modifier validBet(uint256 _id) { Match storage _match = idToMatch[_id]; require(!_match.ended, "match has already ended."); require(msg.value > 0, "invalid bet amount"); _; } modifier validOdds(uint256 _oddsA, uint256 _oddsB) { require(_oddsA >= 1, "invalid odds for team A"); require(_oddsB >= 1, "invalid odds for team B"); _; } }
allows placing of bets _matchId the id of the match _team The team being selected/
function bet(uint256 _matchId, uint256 _team) public payable validBet(_matchId) { Match storage _match = idToMatch[_matchId]; if(_team == 0) { _match.betA[msg.sender][_match.oddsA] += msg.value; _match.totalPayoutA += (msg.value * _match.oddsA) / 100; _match.betB[msg.sender][_match.oddsB] += msg.value; _match.totalPayoutB += (msg.value * _match.oddsB) / 100; } _match.totalCollection += msg.value; }
5,528,033
/// base.t.sol -- test for base.sol // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >=0.4.23; import "ds-test/test.sol"; import "./base.sol"; contract TokenUser { ERC20 token; constructor(ERC20 token_) public { token = token_; } function doTransferFrom(address from, address to, uint amount) public returns (bool) { return token.transferFrom(from, to, amount); } function doTransfer(address to, uint amount) public returns (bool) { return token.transfer(to, amount); } function doApprove(address recipient, uint amount) public returns (bool) { return token.approve(recipient, amount); } function doAllowance(address owner, address spender) public view returns (uint) { return token.allowance(owner, spender); } function doBalanceOf(address who) public view returns (uint) { return token.balanceOf(who); } } contract DSTokenBaseTest is DSTest { uint constant initialBalance = 1000; ERC20 token; address user1; address user2; address self; function setUp() public { token = createToken(); user1 = address(new TokenUser(token)); user2 = address(new TokenUser(token)); self = address(this); } function createToken() internal returns (ERC20) { return new DSTokenBase(initialBalance); } function testSetupPrecondition() public { assertEq(token.balanceOf(self), initialBalance); } function testTransferCost() public logs_gas() { token.transfer(address(0), 10); } function testAllowanceStartsAtZero() public logs_gas { assertEq(token.allowance(user1, user2), 0); } function testValidTransfers() public logs_gas { uint sentAmount = 250; emit log_named_address("token11111", address(token)); token.transfer(user2, sentAmount); assertEq(token.balanceOf(user2), sentAmount); assertEq(token.balanceOf(self), initialBalance - sentAmount); } function testFailWrongAccountTransfers() public logs_gas { uint sentAmount = 250; token.transferFrom(user2, self, sentAmount); } function testFailInsufficientFundsTransfers() public logs_gas { uint sentAmount = 250; token.transfer(user1, initialBalance - sentAmount); token.transfer(user2, sentAmount+1); } function testTransferFromSelf() public { // you always approve yourself assertEq(token.allowance(self, self), 0); token.transferFrom(self, user1, 50); assertEq(token.balanceOf(user1), 50); } function testFailTransferFromSelfNonArbitrarySize() public { // you shouldn't be able to evade balance checks by transferring // to yourself token.transferFrom(self, self, token.balanceOf(self) + 1); } function testApproveSetsAllowance() public logs_gas { emit log_named_address("Test", self); emit log_named_address("Token", address(token)); emit log_named_address("Me", self); emit log_named_address("User 2", user2); token.approve(user2, 25); assertEq(token.allowance(self, user2), 25); } function testChargesAmountApproved() public logs_gas { uint amountApproved = 20; token.approve(user2, amountApproved); assertTrue(TokenUser(user2).doTransferFrom(self, user2, amountApproved)); assertEq(token.balanceOf(self), initialBalance - amountApproved); } function testFailTransferWithoutApproval() public logs_gas { token.transfer(user1, 50); token.transferFrom(user1, self, 1); } function testFailChargeMoreThanApproved() public logs_gas { token.transfer(user1, 50); TokenUser(user1).doApprove(self, 20); token.transferFrom(user1, self, 21); } }
you always approve yourself
function testTransferFromSelf() public { assertEq(token.allowance(self, self), 0); token.transferFrom(self, user1, 50); assertEq(token.balanceOf(user1), 50); }
12,800,658
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.7.5; // ---------------------------------------------------------------------------- // SafeMath library // ---------------------------------------------------------------------------- library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { require(_newOwner != address(0), "ERC20: sending to the zero address"); owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom(address from, address to, uint256 tokens) external returns (bool success); function burnTokens(uint256 _amount) external; function calculateFees( address sender, address recipient, uint256 amount ) external view returns (uint256, uint256); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract UniSwapV2BITBOTStake is Owned { using SafeMath for uint256; address public BBPLP = 0x44f692888a0ED51BC5b05867d9149C5F32F5E07F; address public BBP = 0xbb0A009ba1EB20c5062C790432f080F6597662AF; address public lpLockAddress = 0x740Fda023D5aa68cB392DE148C88966BD91Ec53e; uint256 public totalStakes = 0; uint256 public totalDividends = 0; uint256 private scaledRemainder = 0; uint256 private scaling = uint256(10) ** 12; uint public round = 1; uint256 public maxAllowed = 500000000000000000000; //500 tokens total allowed to be staked uint256 public ethMade=0; //total payout given /* Fees breaker, to protect withdraws if anything ever goes wrong */ bool public breaker = true; // withdraw can be unlock,, default locked mapping(address => uint) public farmTime; // period that your sake it locked to keep it for farming //uint public lock = 0; // farm lock in blocks ~ 0 days for 15s/block //address public admin; struct USER{ uint256 stakedTokens; uint256 lastDividends; uint256 fromTotalDividend; uint round; uint256 remainder; } address[] internal stakeholders; mapping(address => USER) stakers; mapping (uint => uint256) public payouts; // keeps record of each payout event STAKED(address staker, uint256 tokens); event EARNED(address staker, uint256 tokens); event UNSTAKED(address staker, uint256 tokens); event PAYOUT(uint256 round, uint256 tokens, address sender); event CLAIMEDREWARD(address staker, uint256 reward); function setBreaker(bool _breaker) external onlyOwner { breaker = _breaker; } function isStakeholder(address _address) public view returns(bool) { for (uint256 s = 0; s < stakeholders.length; s += 1){ if (_address == stakeholders[s]) return (true); } return (false); } function addStakeholder(address _stakeholder) public { (bool _isStakeholder) = isStakeholder(_stakeholder); if(!_isStakeholder) stakeholders.push(_stakeholder); } function setLpLockAddress(address _account) public onlyOwner { require(_account != address(0), "ERC20: Setting zero address"); lpLockAddress = _account; } // ------------------------------------------------------------------------ // Token holders can stake their tokens using this function // @param tokens number of tokens to stake // ------------------------------------------------------------------------ function STAKE(uint256 tokens) external { require(totalStakes < maxAllowed, "MAX AMOUNT REACHED CANNOT STAKE NO MORE"); require(IERC20(BBPLP).transferFrom(msg.sender, address(lpLockAddress), tokens), "Tokens cannot be transferred from user for locking"); // add pending rewards to remainder to be claimed by user later, if there is any existing stake uint256 owing = pendingReward(msg.sender); stakers[msg.sender].remainder += owing; stakers[msg.sender].stakedTokens = tokens.add(stakers[msg.sender].stakedTokens); stakers[msg.sender].lastDividends = owing; stakers[msg.sender].fromTotalDividend= totalDividends; stakers[msg.sender].round = round; (bool _isStakeholder) = isStakeholder(msg.sender); if(!_isStakeholder) farmTime[msg.sender] = block.timestamp; totalStakes = totalStakes.add(tokens); addStakeholder(msg.sender); emit STAKED(msg.sender, tokens); } // ------------------------------------------------------------------------ // Owners can send the funds to be distributed to stakers using this function // @param tokens number of tokens to distribute // ------------------------------------------------------------------------ function ADDFUNDS() external payable { uint256 _amount = msg.value; ethMade = ethMade.add(_amount); _addPayout(_amount); } // ------------------------------------------------------------------------ // Private function to register payouts // ------------------------------------------------------------------------ function _addPayout(uint256 tokens) private{ // divide the funds among the currently staked tokens // scale the deposit and add the previous remainder uint256 available = (tokens.mul(scaling)).add(scaledRemainder); uint256 dividendPerToken = available.div(totalStakes); scaledRemainder = available.mod(totalStakes); totalDividends = totalDividends.add(dividendPerToken); payouts[round] = payouts[round - 1].add(dividendPerToken); emit PAYOUT(round, tokens, msg.sender); round++; } // ------------------------------------------------------------------------ // Stakers can claim their pending rewards using this function // ------------------------------------------------------------------------ function CLAIMREWARD() public { if(totalDividends >= stakers[msg.sender].fromTotalDividend){ uint256 owing = pendingReward(msg.sender); owing = owing.add(stakers[msg.sender].remainder); stakers[msg.sender].remainder = 0; msg.sender.transfer(owing); emit CLAIMEDREWARD(msg.sender, owing); stakers[msg.sender].lastDividends = owing; // unscaled stakers[msg.sender].round = round; // update the round stakers[msg.sender].fromTotalDividend = totalDividends; // scaled } } // ------------------------------------------------------------------------ // Get the pending rewards of the staker // @param _staker the address of the staker // ------------------------------------------------------------------------ function pendingReward(address staker) private returns (uint256) { require(staker != address(0), "ERC20: sending to the zero address"); uint stakersRound = stakers[staker].round; uint256 amount = ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)).div(scaling); stakers[staker].remainder += ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)) % scaling ; return amount; } function getPendingReward(address staker) public view returns(uint256 _pendingReward) { require(staker != address(0), "ERC20: sending to the zero address"); uint stakersRound = stakers[staker].round; uint256 amount = ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)).div(scaling); amount += ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)) % scaling ; return (amount.add(stakers[staker].remainder)); } // ------------------------------------------------------------------------ // Stakers can un stake the staked tokens using this function // @param tokens the number of tokens to withdraw // ------------------------------------------------------------------------ function WITHDRAW(uint256 tokens) external { require(breaker == false, "Admin Restricted WITHDRAW"); require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw"); totalStakes = totalStakes.sub(tokens); // add pending rewards to remainder to be claimed by user later, if there is any existing stake uint256 owing = pendingReward(msg.sender); stakers[msg.sender].remainder += owing; stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens); stakers[msg.sender].lastDividends = owing; stakers[msg.sender].fromTotalDividend= totalDividends; stakers[msg.sender].round = round; require(IERC20(BBPLP).transfer(msg.sender, tokens), "Error in un-staking tokens"); emit UNSTAKED(msg.sender, tokens); } // ------------------------------------------------------------------------ // Private function to calculate 1% percentage // ------------------------------------------------------------------------ function onePercent(uint256 _tokens) private pure returns (uint256){ uint256 roundValue = _tokens.ceil(100); uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2)); return onePercentofTokens; } // ------------------------------------------------------------------------ // Get the number of tokens staked by a staker // @param _staker the address of the staker // ------------------------------------------------------------------------ function yourStakedBBPLp(address staker) public view returns(uint256 stakedBBPLp){ require(staker != address(0), "ERC20: sending to the zero address"); return stakers[staker].stakedTokens; } // ------------------------------------------------------------------------ // Get the BBP balance of the token holder // @param user the address of the token holder // ------------------------------------------------------------------------ function yourBBPBalance(address user) external view returns(uint256 BBPBalance){ require(user != address(0), "ERC20: sending to the zero address"); return IERC20(BBP).balanceOf(user); } function yourBBPLpBalance(address user) external view returns(uint256 BBPLpBalance){ require(user != address(0), "ERC20: sending to the zero address"); return IERC20(BBPLP).balanceOf(user); } function retByAdmin() public onlyOwner { require(IERC20(BBPLP).transfer(owner, IERC20(BBPLP).balanceOf(address(this))), "Error in retrieving tokens"); require(IERC20(BBP).transfer(owner, IERC20(BBP).balanceOf(address(this))), "Error in retrieving bbp tokens"); owner.transfer(address(this).balance); } }
------------------------------------------------------------------------ Get the number of tokens staked by a staker _staker the address of the staker ------------------------------------------------------------------------
function yourStakedBBPLp(address staker) public view returns(uint256 stakedBBPLp){ require(staker != address(0), "ERC20: sending to the zero address"); return stakers[staker].stakedTokens; }
1,145,463
./partial_match/1/0x35F99F326681FE4F38719491be48Ab4950795013/sources/BondingManager.sol
Return a delegator's cumulative stake and fees using the LIP-36 earnings claiming algorithm _transcoder Storage pointer to a transcoder struct for a delegator's delegate _startRound The round for the start cumulative factors _endRound The round for the end cumulative factors _stake The delegator's initial stake before including earned rewards _fees The delegator's initial fees before including earned fees return (cStake, cFees) where cStake is the delegator's cumulative stake including earned rewards and cFees is the delegator's cumulative fees including earned fees/ Fetch start cumulative factors We can lookback for a cumulativeRewardFactor if the start cumulativeRewardFactor is 0 Do not lookback if the latest cumulativeRewardFactor is 0 because that indicates that the factor was never > 0 for the transcoder in the past We can lookback for a cumulativeFeeFactor if the start cumulativeFeeFactor is 0 Do not lookback if the latest cumulativeFeeFactor is 0 because that indicates that the factor was never > 0 for the transcoder in the past The lookback loop will only be needed for a few accounts delegated to transcoders before the update that ensures start factors are always initialized If we need a cumulativeRewardFactor OR cumulativeFeeFactor lookback up to min(MAX_LOOKBACK_ROUNDS, _startRound) of rounds Short-circuit in the following conditionals by running the boolean check before the storage check
function delegatorCumulativeStakeAndFees( Transcoder storage _transcoder, uint256 _startRound, uint256 _endRound, uint256 _stake, uint256 _fees ) internal view returns (uint256 cStake, uint256 cFees) { uint256 baseRewardFactor = MathUtils.percPoints(1, 1); EarningsPool.Data memory startPool; startPool.cumulativeRewardFactor = _transcoder.earningsPoolPerRound[_startRound].cumulativeRewardFactor; startPool.cumulativeFeeFactor = _transcoder.earningsPoolPerRound[_startRound].cumulativeFeeFactor; bool lookbackCumulativeRewardFactor = _transcoder.earningsPoolPerRound[_transcoder.lastRewardRound].cumulativeRewardFactor > 0 && startPool.cumulativeRewardFactor == 0; bool lookbackCumulativeFeeFactor = _transcoder.earningsPoolPerRound[_transcoder.lastFeeRound].cumulativeFeeFactor > 0 && startPool.cumulativeFeeFactor == 0; for (uint256 lookback = 1; lookback <= MAX_LOOKBACK_ROUNDS && lookback <= _startRound && (lookbackCumulativeRewardFactor || lookbackCumulativeFeeFactor); lookback++) { EarningsPool.Data storage pool = _transcoder.earningsPoolPerRound[_startRound.sub(lookback)]; if (lookbackCumulativeRewardFactor && pool.cumulativeRewardFactor > 0) { startPool.cumulativeRewardFactor = pool.cumulativeRewardFactor; lookbackCumulativeRewardFactor = false; } if (lookbackCumulativeFeeFactor && pool.cumulativeFeeFactor > 0) { startPool.cumulativeFeeFactor = pool.cumulativeFeeFactor; lookbackCumulativeFeeFactor = false; } } if (startPool.cumulativeRewardFactor == 0) { startPool.cumulativeRewardFactor = baseRewardFactor; } if (endPool.cumulativeRewardFactor == 0) { endPool.cumulativeRewardFactor = baseRewardFactor; } cFees = _fees.add( MathUtils.percOf( _stake, endPool.cumulativeFeeFactor.sub(startPool.cumulativeFeeFactor), startPool.cumulativeRewardFactor ) ); cStake = MathUtils.percOf( _stake, endPool.cumulativeRewardFactor, startPool.cumulativeRewardFactor ); return (cStake, cFees); }
4,486,333
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; //imports from the lazy minting guide import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol"; //ZeNFT implementation for ERC721's contract ZNFT is Initializable, ERC721Upgradeable, EIP712Upgradeable, ERC721URIStorageUpgradeable, PausableUpgradeable, AccessControlUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable { //lazy minter stuff bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant UPGRADER_ROLE = keccak256("DEFAULT_ADMIN_ROLE"); string private constant SIGNING_DOMAIN = "ZeNFT-Minter"; string private constant SIGNATURE_VERSION = "1.0"; /*royalties address public artist; uint public txFeeAmount; mapping(address => bool) public excludedList; */ using CountersUpgradeable for CountersUpgradeable.Counter; mapping (address => uint256) pendingWithdrawals; CountersUpgradeable.Counter private _tokenIdCounter; constructor() initializer {} function initialize(address payable minter) initializer public { __ERC721_init("zNFT", "Zens"); __EIP712_init("ZeNFT", "1.0"); __ERC721URIStorage_init(); __Pausable_init(); __ERC721Burnable_init(); __UUPSUpgradeable_init(); __AccessControl_init(); _setupRole(MINTER_ROLE, minter); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); grantRole(PAUSER_ROLE, msg.sender); } function pause() public onlyRole(PAUSER_ROLE) { _pause(); } function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } function safeMint(address to, string memory uri) public onlyRole(MINTER_ROLE) { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); _setTokenURI(tokenId, uri); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override{ super._beforeTokenTransfer(from, to, tokenId); } //Only the owner can call this function in which you pass in the contract address of the newly deployed contract //called the new Implementation function _authorizeUpgrade(address newImplementation)internal onlyRole(DEFAULT_ADMIN_ROLE) override{ } // The following functions are overrides required by Solidity. function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable){ super._burn(tokenId); } // function tokenURI(uint256 tokenId)public view override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory){ return super.tokenURI(tokenId); } //if you are doing an airdrop then you have to take the minimum price out of it and then the buyer pays the gas fees ///Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function. struct NFTVoucher { // The id of the token to be redeemed. Must be unique - if another token with this ID already exists, the redeem function will revert. uint256 tokenId; //The minimum price (in wei) that the NFT creator is willing to accept for the initial sale of this NFT. uint256 minPrice; //The metadata URI to associate with this token. string uri; //the EIP-712 signature of all other fields in the NFTVoucher struct. For a voucher to be valid, it must be signed by an account with the MINTER_ROLE. bytes signature; } /// notice Redeems an NFTVoucher for an actual NFT, creating it in the process. /// param redeemer The address of the account which will receive the NFT upon success. /// param voucher A signed NFTVoucher that describes the NFT to be redeemed. function redeem(address redeemer, NFTVoucher calldata voucher) public payable returns (uint256) { // make sure signature is valid and get the address of the signer address signer = _verify(voucher); // make sure that the signer is authorized to mint NFTs require(hasRole(MINTER_ROLE, signer), "Signature invalid or unauthorized"); // make sure that the redeemer is paying enough to cover the buyer's cost require(msg.value >= voucher.minPrice, "Insufficient funds to redeem"); // first assign the token to the signer, to establish provenance on-chain _mint(signer, voucher.tokenId); _setTokenURI(voucher.tokenId, voucher.uri); // transfer the token to the redeemer _transfer(signer, redeemer, voucher.tokenId); // record payment to signer's withdrawal balance pendingWithdrawals[signer] += msg.value; //you return the tkenID return voucher.tokenId; } /// notice Transfers all pending withdrawal balance to the caller. Reverts if the caller is not an authorized minter. function withdraw() public { //hasRole require(hasRole(MINTER_ROLE, msg.sender), "Only authorized minters can withdraw"); // IMPORTANT: casting msg.sender to a payable address is only safe if ALL members of the minter role are payable addresses. address payable receiver = payable(msg.sender); uint amount = pendingWithdrawals[receiver]; // zero account before transfer to prevent re-entrancy attack pendingWithdrawals[receiver] = 0; receiver.transfer(amount); } /// notice Retuns the amount of Ether available to the caller to withdraw. function availableToWithdraw() public view returns (uint256) { return pendingWithdrawals[msg.sender]; } /// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules. /// @param voucher An NFTVoucher to hash. function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFTVoucher(uint256 tokenId,uint256 minPrice,string uri)"), voucher.tokenId, voucher.minPrice, keccak256(bytes(voucher.uri)) ))); } /// notice Returns the chain id of the current blockchain. /// @dev This is used to workaround an issue with ganache returning different values from the on-chain chainid() function and /// the eth_chainId RPC method. See https://github.com/protocol/nft-website/issues/121 for context. function getChainID() external view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /// notice Verifies the signature for a given NFTVoucher, returning the address of the signer. /// dev Will revert if the signature is invalid. Does not verify that the signer is authorized to mint NFTs. /// param voucher An NFTVoucher describing an unminted NFT. function _verify(NFTVoucher calldata voucher) internal view returns (address) { bytes32 digest = _hash(voucher); return ECDSA.recover(digest, voucher.signature); } function supportsInterface(bytes4 interfaceId) public view virtual override (AccessControlUpgradeable, ERC721Upgradeable) returns (bool) { return ERC721Upgradeable.supportsInterface(interfaceId) || AccessControlUpgradeable.supportsInterface(interfaceId); } /*Leftover from royalties //sets whether its excluded from paying royalties function setExcluded(address excluded, bool status) external { require(msg.sender == artist, 'artist only'); excludedList[excluded] = status; } */ function transferFrom(address from, address to, uint256 tokenId) public override { require(ownerOf(tokenId) == msg.sender, 'ERC721: transfer caller is not owner nor approved'); _transfer(from, to, tokenId); } // this should require an is approvedorOwner? function safeTransferFrom(address from, address to, uint256 tokenId) public override { safeTransferFrom(from, to, tokenId, ''); } //look up to see why theres a seperate transferFrom adding in the bytes function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override { require(ownerOf(tokenId) == msg.sender, 'ERC721: transfer caller is not owner nor approved'); _safeTransfer(from, to, tokenId, _data); } }
look up to see why theres a seperate transferFrom adding in the bytes
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override { require(ownerOf(tokenId) == msg.sender, 'ERC721: transfer caller is not owner nor approved'); _safeTransfer(from, to, tokenId, _data); }
12,751,496
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error * Based on SafeMath.sol from https://github.com/OpenZeppelin/zeppelin-solidity/tree/master */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // 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; } } pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * Based on Ownable.sol from https://github.com/OpenZeppelin/zeppelin-solidity/tree/master */ 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 returns (bool) { require(newOwner != address(0)); owner = newOwner; OwnershipTransferred(owner, newOwner); return true; } } pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } pragma solidity ^0.4.18; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } pragma solidity ^0.4.18; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; // mapping of addresses with according balances mapping(address => uint256) balances; uint256 public totalSupply; /** * @dev Gets the totalSupply. * @return An uint256 representing the total supply of tokens. */ function totalSupply() public view returns (uint256) { return totalSupply; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } pragma solidity ^0.4.18; /** * @title Custom ERC20 token * * @dev Implementation and upgraded version of the basic standard token. */ contract CustomToken is ERC20, BasicToken, Ownable { mapping (address => mapping (address => uint256)) internal allowed; // boolean if transfers can be done bool public enableTransfer = true; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenTransferEnabled() { require(enableTransfer); _; } event Burn(address indexed burner, uint256 value); event EnableTransfer(address indexed owner, uint256 timestamp); event DisableTransfer(address indexed owner, uint256 timestamp); /** * @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) whenTransferEnabled public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev 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 * The owner can transfer tokens at will. This to implement a reward pool contract in a later phase * that will transfer tokens for rewarding. */ function transferFrom(address _from, address _to, uint256 _value) whenTransferEnabled public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); if (msg.sender!=owner) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); } else { balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); } Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) whenTransferEnabled public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* Approves and then calls the receiving contract */ function approveAndCallAsContract(address _spender, uint256 _value, bytes _extraData) onlyOwner public returns (bool success) { // check if the _spender already has some amount approved else use increase approval. // maybe not for exchanges //require((_value == 0) || (allowed[this][_spender] == 0)); allowed[this][_spender] = _value; Approval(this, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed when one does this that the call *should* succeed, otherwise one would use vanilla approve instead. require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), this, _value, this, _extraData)); return true; } /* * Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) whenTransferEnabled public returns (bool success) { // check if the _spender already has some amount approved else use increase approval. // maybe not for exchanges require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed when one does this that the call *should* succeed, otherwise one would use vanilla approve instead. require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); 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) * @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) whenTransferEnabled public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @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) whenTransferEnabled public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(address _burner, uint256 _value) onlyOwner public returns (bool) { require(_value <= balances[_burner]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_burner] = balances[_burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(_burner, _value); return true; } /** * @dev called by the owner to enable transfers */ function enableTransfer() onlyOwner public returns (bool) { enableTransfer = true; EnableTransfer(owner, now); return true; } /** * @dev called by the owner to disable tranfers */ function disableTransfer() onlyOwner whenTransferEnabled public returns (bool) { enableTransfer = false; DisableTransfer(owner, now); return true; } } pragma solidity ^0.4.18; /** * @title Identify token * @dev ERC20 compliant token, where all tokens are pre-assigned to the token contract. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract Identify is CustomToken { string public constant name = "IDENTIFY"; string public constant symbol = "IDF"; uint8 public constant decimals = 6; uint256 public constant INITIAL_SUPPLY = 49253333333 * (10 ** uint256(decimals)); /** * @dev Constructor that gives the token contract all of initial tokens. */ function Identify() public { totalSupply = INITIAL_SUPPLY; balances[this] = INITIAL_SUPPLY; Transfer(0x0, this, INITIAL_SUPPLY); } } pragma solidity ^0.4.18; /** * @title Whitelist contract * @dev Participants for the presale and public sale must be * registered in the whitelist. Admins can add and remove * participants and other admins. */ contract Whitelist is Ownable { using SafeMath for uint256; // a boolean to check if the presale is paused bool public paused = false; // the amount of participants in the whitelist uint256 public participantAmount; // mapping of participants mapping (address => bool) public isParticipant; // mapping of admins mapping (address => bool) public isAdmin; event AddParticipant(address _participant); event AddAdmin(address _admin, uint256 _timestamp); event RemoveParticipant(address _participant); event Paused(address _owner, uint256 _timestamp); event Resumed(address _owner, uint256 _timestamp); /** * event for claimed tokens logging * @param owner where tokens are sent to * @param claimtoken is the address of the ERC20 compliant token * @param amount amount of tokens sent back */ event ClaimedTokens(address indexed owner, address claimtoken, uint amount); /** * modifier to check if the whitelist is not paused */ modifier notPaused() { require(!paused); _; } /** * modifier to check the admin or owner runs this function */ modifier onlyAdmin() { require(isAdmin[msg.sender] || msg.sender == owner); _; } /** * fallback function to send the eth back to the sender */ function () payable public { // give ETH back msg.sender.transfer(msg.value); } /** * constructor which adds the owner in the admin list */ function Whitelist() public { require(addAdmin(msg.sender)); } /** * @param _participant address of participant * @return true if the _participant is in the list */ function isParticipant(address _participant) public view returns (bool) { require(address(_participant) != 0); return isParticipant[_participant]; } /** * @param _participant address of participant * @return true if _participant is added successful */ function addParticipant(address _participant) public notPaused onlyAdmin returns (bool) { require(address(_participant) != 0); require(isParticipant[_participant] == false); isParticipant[_participant] = true; participantAmount++; AddParticipant(_participant); return true; } /** * @param _participant address of participant * @return true if _participant is removed successful */ function removeParticipant(address _participant) public onlyAdmin returns (bool) { require(address(_participant) != 0); require(isParticipant[_participant]); require(msg.sender != _participant); delete isParticipant[_participant]; participantAmount--; RemoveParticipant(_participant); return true; } /** * @param _admin address of admin * @return true if _admin is added successful */ function addAdmin(address _admin) public onlyAdmin returns (bool) { require(address(_admin) != 0); require(!isAdmin[_admin]); isAdmin[_admin] = true; AddAdmin(_admin, now); return true; } /** * @param _admin address of admin * @return true if _admin is removed successful */ function removeAdmin(address _admin) public onlyAdmin returns (bool) { require(address(_admin) != 0); require(isAdmin[_admin]); require(msg.sender != _admin); delete isAdmin[_admin]; return true; } /** * @notice Pauses the whitelist if there is any issue */ function pauseWhitelist() public onlyAdmin returns (bool) { paused = true; Paused(msg.sender,now); return true; } /** * @notice resumes the whitelist if there is any issue */ function resumeWhitelist() public onlyAdmin returns (bool) { paused = false; Resumed(msg.sender,now); return true; } /** * @notice used to save gas */ function addMultipleParticipants(address[] _participants ) public onlyAdmin returns (bool) { for ( uint i = 0; i < _participants.length; i++ ) { require(addParticipant(_participants[i])); } return true; } /** * @notice used to save gas. Backup function. */ function addFiveParticipants(address participant1, address participant2, address participant3, address participant4, address participant5) public onlyAdmin returns (bool) { require(addParticipant(participant1)); require(addParticipant(participant2)); require(addParticipant(participant3)); require(addParticipant(participant4)); require(addParticipant(participant5)); return true; } /** * @notice used to save gas. Backup function. */ function addTenParticipants(address participant1, address participant2, address participant3, address participant4, address participant5, address participant6, address participant7, address participant8, address participant9, address participant10) public onlyAdmin returns (bool) { require(addParticipant(participant1)); require(addParticipant(participant2)); require(addParticipant(participant3)); require(addParticipant(participant4)); require(addParticipant(participant5)); require(addParticipant(participant6)); require(addParticipant(participant7)); require(addParticipant(participant8)); require(addParticipant(participant9)); require(addParticipant(participant10)); return true; } /** * @notice This method can be used by the owner to extract mistakenly sent tokens to this contract. * @param _claimtoken The address of the token contract that you want to recover * set to 0 in case you want to extract ether. */ function claimTokens(address _claimtoken) onlyAdmin public returns (bool) { if (_claimtoken == 0x0) { owner.transfer(this.balance); return true; } ERC20 claimtoken = ERC20(_claimtoken); uint balance = claimtoken.balanceOf(this); claimtoken.transfer(owner, balance); ClaimedTokens(_claimtoken, owner, balance); return true; } } pragma solidity ^0.4.18; /** * @title Presale * @dev Presale is a base contract for managing a token presale. * Presales have a start and end timestamps, where investors can make * token purchases and the presale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. Note that the presale contract * must be owner of the token in order to be able to mint it. */ contract Presale is Ownable { using SafeMath for uint256; // token being sold Identify public token; // address of the token being sold address public tokenAddress; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are forwarded address public wallet; // whitelist contract Whitelist public whitelist; // how many token units a buyer gets per ETH uint256 public rate = 4200000; // amount of raised money in wei uint256 public weiRaised; // amount of tokens raised uint256 public tokenRaised; // parameters for the presale: // maximum of wei the presale wants to raise uint256 public capWEI; // maximum of tokens the presale wants to raise uint256 public capTokens; // bonus investors get in the presale - 25% uint256 public bonusPercentage = 125; // minimum amount of wei an investor needs to send in order to get tokens uint256 public minimumWEI; // maximum amount of wei an investor can send in order to get tokens uint256 public maximumWEI; // a boolean to check if the presale is paused bool public paused = false; // a boolean to check if the presale is finalized bool public isFinalized = false; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value WEIs paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * event for claimed tokens logging * @param owner where tokens are sent to * @param claimtoken is the address of the ERC20 compliant token * @param amount amount of tokens sent back */ event ClaimedTokens(address indexed owner, address claimtoken, uint amount); /** * event for pause logging * @param owner who invoked the pause function * @param timestamp when the pause function is invoked */ event Paused(address indexed owner, uint256 timestamp); /** * event for resume logging * @param owner who invoked the resume function * @param timestamp when the resume function is invoked */ event Resumed(address indexed owner, uint256 timestamp); /** * modifier to check if a participant is in the whitelist */ modifier isInWhitelist(address beneficiary) { // first check if sender is in whitelist require(whitelist.isParticipant(beneficiary)); _; } /** * modifier to check if the presale is not paused */ modifier whenNotPaused() { require(!paused); _; } /** * modifier to check if the presale is not finalized */ modifier whenNotFinalized() { require(!isFinalized); _; } /** * modifier to check only multisigwallet can do this operation */ modifier onlyMultisigWallet() { require(msg.sender == wallet); _; } /** * constructor for Presale * @param _startTime start timestamps where investments are allowed (inclusive) * @param _wallet address where funds are forwarded * @param _token address of the token being sold * @param _whitelist whitelist contract address * @param _capETH maximum of ETH the presale wants to raise * @param _capTokens maximum amount of tokens the presale wants to raise * @param _minimumETH minimum amount of ETH an investor needs to send in order to get tokens * @param _maximumETH maximum amount of ETH an investor can send in order to get tokens */ function Presale(uint256 _startTime, address _wallet, address _token, address _whitelist, uint256 _capETH, uint256 _capTokens, uint256 _minimumETH, uint256 _maximumETH) public { require(_startTime >= now); require(_wallet != address(0)); require(_token != address(0)); require(_whitelist != address(0)); require(_capETH > 0); require(_capTokens > 0); require(_minimumETH > 0); require(_maximumETH > 0); startTime = _startTime; endTime = _startTime.add(19 weeks); wallet = _wallet; tokenAddress = _token; token = Identify(_token); whitelist = Whitelist(_whitelist); capWEI = _capETH * (10 ** uint256(18)); capTokens = _capTokens * (10 ** uint256(6)); minimumWEI = _minimumETH * (10 ** uint256(18)); maximumWEI = _maximumETH * (10 ** uint256(18)); } /** * fallback function can be used to buy tokens */ function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) isInWhitelist(beneficiary) whenNotPaused whenNotFinalized public payable returns (bool) { require(beneficiary != address(0)); require(validPurchase()); require(!hasEnded()); require(!isContract(msg.sender)); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); require(tokenRaised.add(tokens) <= capTokens); // update state weiRaised = weiRaised.add(weiAmount); tokenRaised = tokenRaised.add(tokens); require(token.transferFrom(tokenAddress, beneficiary, tokens)); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); return true; } /** * @return true if crowdsale event has ended */ function hasEnded() public view returns (bool) { bool capReached = weiRaised >= capWEI; bool capTokensReached = tokenRaised >= capTokens; bool ended = now > endTime; return (capReached || capTokensReached) || ended; } /** * calculate the amount of tokens a participant gets for a specific weiAmount * @return the token amount */ function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { // wei has 18 decimals, our token has 6 decimals -> so need for convertion uint256 bonusIntegrated = weiAmount.div(10000000000000).mul(rate).mul(bonusPercentage).div(100); return bonusIntegrated; } /** * send ether to the fund collection wallet * @return true if successful */ function forwardFunds() internal returns (bool) { wallet.transfer(msg.value); return true; } /** * @return true if the transaction can buy tokens */ function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool underMaximumWEI = msg.value <= maximumWEI; bool withinCap = weiRaised.add(msg.value) <= capWEI; bool minimumWEIReached; // check to fill in last gap if ( capWEI.sub(weiRaised) < minimumWEI) { minimumWEIReached = true; } else { minimumWEIReached = msg.value >= minimumWEI; } return (withinPeriod && nonZeroPurchase) && (withinCap && (minimumWEIReached && underMaximumWEI)); } /** * @dev Allows the multisigwallet to transfer control of the Identify Token to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnershipToken(address newOwner) onlyMultisigWallet public returns (bool) { require(token.transferOwnership(newOwner)); return true; } /** * Overwrite method of Ownable * @dev Allows the multisigwallet to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyMultisigWallet public returns (bool) { require(newOwner != address(0)); owner = newOwner; OwnershipTransferred(owner, newOwner); return true; } /** * @dev Finalize the presale. */ function finalize() onlyMultisigWallet whenNotFinalized public returns (bool) { require(hasEnded()); // check if cap is reached if (!(capWEI == weiRaised)) { // calculate remaining tokens uint256 remainingTokens = capTokens.sub(tokenRaised); // burn remaining tokens require(token.burn(tokenAddress, remainingTokens)); } require(token.transferOwnership(wallet)); isFinalized = true; return true; } //////////////////////// /// SAFETY FUNCTIONS /// //////////////////////// /** * @dev Internal function to determine if an address is a contract * @param _addr The address being queried * @return True if `_addr` is a contract */ function isContract(address _addr) constant internal returns (bool) { if (_addr == 0) { return false; } uint256 size; assembly { size := extcodesize(_addr) } return (size > 0); } /** * @notice This method can be used by the owner to extract mistakenly sent tokens to this contract. * @param _claimtoken The address of the token contract that you want to recover * set to 0 in case you want to extract ether. */ function claimTokens(address _claimtoken) onlyOwner public returns (bool) { if (_claimtoken == 0x0) { owner.transfer(this.balance); return true; } ERC20 claimtoken = ERC20(_claimtoken); uint balance = claimtoken.balanceOf(this); claimtoken.transfer(owner, balance); ClaimedTokens(_claimtoken, owner, balance); return true; } /** * @notice Pauses the presale if there is an issue */ function pausePresale() onlyOwner public returns (bool) { paused = true; Paused(owner, now); return true; } /** * @notice Resumes the presale */ function resumePresale() onlyOwner public returns (bool) { paused = false; Resumed(owner, now); return true; } }
This method can be used by the owner to extract mistakenly sent tokens to this contract. _claimtoken The address of the token contract that you want to recover set to 0 in case you want to extract ether./
function claimTokens(address _claimtoken) onlyAdmin public returns (bool) { if (_claimtoken == 0x0) { owner.transfer(this.balance); return true; } ERC20 claimtoken = ERC20(_claimtoken); uint balance = claimtoken.balanceOf(this); claimtoken.transfer(owner, balance); ClaimedTokens(_claimtoken, owner, balance); return true; }
5,448,072
./full_match/80001/0x57fDca93a066F0af7639D96998B59D2F4fb7E34A/sources/KouncilPower.sol
Mints an NFT to `to`
function _mintTo(address _to, string calldata _uri) internal returns (uint256 tokenIdToMint) { tokenIdToMint = nextTokenIdToMint; nextTokenIdToMint += 1; require(bytes(_uri).length > 0, "empty uri."); uri[tokenIdToMint] = _uri; _safeMint(_to, tokenIdToMint); emit TokensMinted(_to, tokenIdToMint, _uri); }
5,620,637
//Address: 0xf8ef303406cbcbfc82af008d45210c835ad2f736 //Contract name: EtherVillains //Balance: 0 Ether //Verification Date: 2/25/2018 //Transacion Count: 914 // CODE STARTS HERE pragma solidity ^0.4.19; // // EtherVillains.co contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); // 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 EtherVillains is ERC721 { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new villain comes into existence. event Birth(uint256 tokenId, string name, address owner); /// @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "EtherVillains"; // string public constant SYMBOL = "EVIL"; // uint256 public precision = 1000000000000; //0.000001 Eth uint256 private zapPrice = 0.001 ether; uint256 private pinchPrice = 0.002 ether; uint256 private guardPrice = 0.002 ether; uint256 private pinchPercentageReturn = 20; // how much a flip is worth when a villain is flipped. uint256 private defaultStartingPrice = 0.001 ether; uint256 private firstStepLimit = 0.05 ether; uint256 private secondStepLimit = 0.5 ether; /*** STORAGE ***/ /// @dev A mapping from villain IDs to the address that owns them. All villians have /// some valid owner address. mapping (uint256 => address) public villainIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from Villains to an address that has been approved to call /// transferFrom(). Each Villain can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public villainIndexToApproved; // @dev A mapping from Villains to the price of the token. mapping (uint256 => uint256) private villainIndexToPrice; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; /*** DATATYPES ***/ struct Villain { uint256 id; // needed for gnarly front end string name; uint256 class; // 0 = Zapper , 1 = Pincher , 2 = Guard uint256 level; // 0 for Zapper, 1 - 5 for Pincher, Guard - representing the max active pinches or guards uint256 numSkillActive; // the current number of active skill implementations (pinches or guards) uint256 state; // 0 = normal , 1 = zapped , 2 = pinched , 3 = guarded uint256 zappedExipryTime; // if this villain was disarmed, when does it expire uint256 affectedByToken; // token that has affected this token (zapped, pinched, guarded) uint256 buyPrice; // the price at which this villain was purchased } Villain[] private villains; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** CONSTRUCTOR ***/ function EtherVillains() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); villainIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates a new Villain with the given name. function createVillain(string _name, uint256 _startPrice, uint256 _class, uint256 _level) public onlyCLevel { _createVillain(_name, address(this), _startPrice,_class,_level); } /// @notice Returns all the relevant information about a specific villain. /// @param _tokenId The tokenId of the villain of interest. function getVillain(uint256 _tokenId) public view returns ( uint256 id, string villainName, uint256 sellingPrice, address owner, uint256 class, uint256 level, uint256 numSkillActive, uint256 state, uint256 zappedExipryTime, uint256 buyPrice, uint256 nextPrice, uint256 affectedByToken ) { id = _tokenId; Villain storage villain = villains[_tokenId]; villainName = villain.name; sellingPrice =villainIndexToPrice[_tokenId]; owner = villainIndexToOwner[_tokenId]; class = villain.class; level = villain.level; numSkillActive = villain.numSkillActive; state = villain.state; if (villain.state==1 && now>villain.zappedExipryTime){ state=0; // time expired so say they are armed } zappedExipryTime=villain.zappedExipryTime; buyPrice=villain.buyPrice; nextPrice=calculateNewPrice(_tokenId); affectedByToken=villain.affectedByToken; } /// zap a villain in preparation for a pinch function zapVillain(uint256 _victim , uint256 _zapper) public payable returns (bool){ address villanOwner = villainIndexToOwner[_victim]; require(msg.sender != villanOwner); // it doesn't make sense, but hey require(villains[_zapper].class==0); // they must be a zapper class require(msg.sender==villainIndexToOwner[_zapper]); // they must be a zapper owner uint256 operationPrice = zapPrice; // if the target sale price <0.01 then operation is free if (villainIndexToPrice[_victim]<0.01 ether){ operationPrice=0; } // can be used to extend a zapped period if (msg.value>=operationPrice && villains[_victim].state<2){ // zap villain villains[_victim].state=1; villains[_victim].zappedExipryTime = now + (villains[_zapper].level * 1 minutes); } } /// pinch a villain function pinchVillain(uint256 _victim, uint256 _pincher) public payable returns (bool){ address victimOwner = villainIndexToOwner[_victim]; require(msg.sender != victimOwner); // it doesn't make sense, but hey require(msg.sender==villainIndexToOwner[_pincher]); require(villains[_pincher].class==1); // they must be a pincher require(villains[_pincher].numSkillActive<villains[_pincher].level); uint256 operationPrice = pinchPrice; // if the target sale price <0.01 then operation is free if (villainIndexToPrice[_victim]<0.01 ether){ operationPrice=0; } // 0 = normal , 1 = zapped , 2 = pinched // must be inside the zapped window if (msg.value>=operationPrice && villains[_victim].state==1 && now< villains[_victim].zappedExipryTime){ // squeeze villains[_victim].state=2; // squeezed villains[_victim].affectedByToken=_pincher; villains[_pincher].numSkillActive++; } } /// guard a villain function guardVillain(uint256 _target, uint256 _guard) public payable returns (bool){ require(msg.sender==villainIndexToOwner[_guard]); // sender must own this token require(villains[_guard].numSkillActive<villains[_guard].level); uint256 operationPrice = guardPrice; // if the target sale price <0.01 then operation is free if (villainIndexToPrice[_target]<0.01 ether){ operationPrice=0; } // 0 = normal , 1 = zapped , 2 = pinched, 3 = guarded if (msg.value>=operationPrice && villains[_target].state<2){ // guard this villain villains[_target].state=3; villains[_target].affectedByToken=_guard; villains[_guard].numSkillActive++; } } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = villainIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = villainIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = villainIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 payment = roundIt(uint256(SafeMath.div(SafeMath.mul(sellingPrice, 93), 100))); // taking 7% for the house before any pinches? uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); // HERE'S THE FLIPPING STRATEGY villainIndexToPrice[_tokenId] = calculateNewPrice(_tokenId); // we check to see if there is a pinch on this villain // if there is, then transfer the pinch percentage to the owner of the pinch token if (villains[_tokenId].state==2 && villains[_tokenId].affectedByToken!=0){ uint256 profit = sellingPrice - villains[_tokenId].buyPrice; uint256 pinchPayment = roundIt(SafeMath.mul(SafeMath.div(profit,100),pinchPercentageReturn)); // release on of this villans pinch capabilitiesl address pincherTokenOwner = villainIndexToOwner[villains[_tokenId].affectedByToken]; pincherTokenOwner.transfer(pinchPayment); payment = SafeMath.sub(payment,pinchPayment); // subtract the pinch fees } // free the villan of any pinches or guards as part of this purpose if (villains[villains[_tokenId].affectedByToken].numSkillActive>0){ villains[villains[_tokenId].affectedByToken].numSkillActive--; // reset the pincher or guard affected count } villains[_tokenId].state=0; villains[_tokenId].affectedByToken=0; villains[_tokenId].buyPrice=sellingPrice; _transfer(oldOwner, newOwner, _tokenId); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); //(1-0.08) } TokenSold(_tokenId, sellingPrice, villainIndexToPrice[_tokenId], oldOwner, newOwner, villains[_tokenId].name); msg.sender.transfer(purchaseExcess); // return any additional amount } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return villainIndexToPrice[_tokenId]; } function nextPrice(uint256 _tokenId) public view returns (uint256 nPrice) { return calculateNewPrice(_tokenId); } //(note: hard coded value appreciation is 2X from a contract price of 0 ETH to 0.05 ETH, 1.2X from 0.05 to 0.5 and 1.15X from 0.5 ETH and up). function calculateNewPrice(uint256 _tokenId) internal view returns (uint256 price){ uint256 sellingPrice = villainIndexToPrice[_tokenId]; uint256 newPrice; // Update prices if (sellingPrice < firstStepLimit) { // first stage newPrice = roundIt(SafeMath.mul(sellingPrice, 2)); } else if (sellingPrice < secondStepLimit) { // second stage newPrice = roundIt(SafeMath.div(SafeMath.mul(sellingPrice, 120), 100)); } else { // third stage newPrice= roundIt(SafeMath.div(SafeMath.mul(sellingPrice, 115), 100)); } return newPrice; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = villainIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose tokens we are interested in. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalVillains = totalSupply(); uint256 resultIndex = 0; uint256 villainId; for (villainId = 0; villainId <= totalVillains; villainId++) { if (villainIndexToOwner[villainId] == _owner) { result[resultIndex] = villainId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return villains.length; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return villainIndexToApproved[_tokenId] == _to; } /// For creating Villains function _createVillain(string _name, address _owner, uint256 _price, uint256 _class, uint256 _level) private { Villain memory _villain = Villain({ name: _name, class: _class, level: _level, numSkillActive: 0, state: 0, zappedExipryTime: 0, affectedByToken: 0, buyPrice: 0, id: villains.length-1 }); uint256 newVillainId = villains.push(_villain) - 1; villains[newVillainId].id=newVillainId; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newVillainId == uint256(uint32(newVillainId))); Birth(newVillainId, _name, _owner); villainIndexToPrice[newVillainId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newVillainId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == villainIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @dev Assigns ownership of a specific Villain to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of villains is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership villainIndexToOwner[_tokenId] = _to; // When creating new villains _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete villainIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } // utility to round to the game precision function roundIt(uint256 amount) internal constant returns (uint256) { // round down to correct preicision uint256 result = (amount/precision)*precision; return result; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
For querying totalSupply of token Required for ERC-721 compliance.
function totalSupply() public view returns (uint256 total) { return villains.length; }
1,033,489
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "./Ownable.sol"; import "./IERC20.sol"; import "./IUniswapV3Router.sol"; import "./IWETH.sol"; import {Path} from "./Path.sol"; contract matrEXRouterV3 is Ownable, IUniswapV3Router{ using Path for bytes; /** * @dev Event emitted when the charity fee is taken * @param from: The user it is taken from * @param token: The token that was taken from the user * @param amount: The amount of the token taken for charity */ event feeTaken(address from, IERC20 token, uint256 amount); /** * @dev Event emitted when the charity fee is taken (in ETH) * @param from: The user it was taken from * @param amount: The amount of ETH taken in wei */ event feeTakenInETH(address from, uint256 amount); /** * @dev Event emmited when a token is approved for trade for the first * time on Uniswap (check takeFeeAndApprove()) * @param token: The tokens that was approved for trade */ event approvedForTrade(IERC20 token); /** * @dev * _charityFee: The % that is taken from each swap that gets sent to charity * _charityAddress: The address that the charity funds get sent to * _uniswapV3Router: Uniswap router that all swaps go through * _WETH: The address of the WETH token */ uint256 private _charityFee; address private _charityAddress; IUniswapV3Router private _uniswapV3Router; address private _WETH; /** * @dev Sets the Uniswap router, the charity fee, the charity address and * the WETH token address */ constructor(){ _uniswapV3Router = IUniswapV3Router(0xE592427A0AEce92De3Edee1F18E0157C05861564); _charityFee = 20; _charityAddress = address(0x830be1dba01bfF12C706b967AcDeCd2fDEa48990); _WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); } /** * @dev Calculates the fee and takes it, transfers the fee to the charity * address and the remains to this contract. * emits feeTaken() * Then, it checks if there is enough approved for the swap, if not it * approves it to the uniswap contract. Emits approvedForTrade() if so. * @param user: The payer * @param token: The token that will be swapped and the fee will be paid * in * @param totalAmount: The total amount of tokens that will be swapped, will * be used to calculate how much the fee will be */ function takeFeeAndApprove(address user, IERC20 token, uint256 totalAmount) internal returns (uint256){ uint256 _feeTaken = (totalAmount * _charityFee) / 10000; token.transferFrom(user, address(this), totalAmount - _feeTaken); token.transferFrom(user, _charityAddress, _feeTaken); if (token.allowance(address(this), address(_uniswapV3Router)) < totalAmount){ token.approve(address(_uniswapV3Router), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); emit approvedForTrade(token); } emit feeTaken(user, token, _feeTaken); return totalAmount -= _feeTaken; } /** * @dev Calculates the fee and takes it, holds the fee in the contract and * can be sent to charity when someone calls withdraw() * This makes sure: * 1. That the user doesn't spend extra gas for an ERC20 transfer + * wrap * 2. That funds can be safely transfered to a contract * emits feeTakenInETH() * @param totalAmount: The total amount of tokens that will be swapped, will * be used to calculate how much the fee will be */ function takeFeeETH(uint256 totalAmount) internal returns (uint256 fee){ uint256 _feeTaken = (totalAmount * _charityFee) / 10000; emit feeTakenInETH(_msgSender(), _feeTaken); return totalAmount - _feeTaken; } /** * @dev The functions below are all the same as the Uniswap contract but * they call takeFeeAndApprove() or takeFeeETH() (See the functions above) * and deduct the fee from the amount that will be traded. */ function exactInputSingle(ExactInputSingleParams calldata params) external virtual override payable returns (uint256){ if (params.tokenIn == _WETH && msg.value >= params.amountIn){ uint256 newValue = takeFeeETH(params.amountIn); ExactInputSingleParams memory params_ = params; params_.amountIn = newValue; return _uniswapV3Router.exactInputSingle{value: params_.amountIn}(params_); }else{ IERC20 token = IERC20(params.tokenIn); uint256 newAmount = takeFeeAndApprove(_msgSender(), token, params.amountIn); ExactInputSingleParams memory _params = params; _params.amountIn = newAmount; return _uniswapV3Router.exactInputSingle(_params); } } function exactInput(ExactInputParams calldata params) external virtual override payable returns (uint256){ (address tokenIn, address tokenOut, uint24 fee) = params.path.decodeFirstPool(); if (tokenIn == _WETH && msg.value >= params.amountIn){ uint256 newValue = takeFeeETH(params.amountIn); ExactInputParams memory params_ = params; params_.amountIn = newValue; return _uniswapV3Router.exactInput{value: params_.amountIn}(params_); }else{ IERC20 token = IERC20(tokenIn); uint256 newAmount = takeFeeAndApprove(_msgSender(), IERC20(token), params.amountIn); ExactInputParams memory _params = params; _params.amountIn = newAmount; return _uniswapV3Router.exactInput(_params); } } function exactOutputSingle(ExactOutputSingleParams calldata params) external virtual payable override returns (uint256){ if (params.tokenIn == address(_WETH) && msg.value >= params.amountOut){ uint256 newValue = takeFeeETH(params.amountOut); ExactOutputSingleParams memory params_ = params; params_.amountOut = newValue; return _uniswapV3Router.exactOutputSingle{value: params_.amountOut}(params_); }else{ IERC20 token = IERC20(params.tokenIn); uint256 newAmount = takeFeeAndApprove(_msgSender(), token, params.amountOut); ExactOutputSingleParams memory _params = params; _params.amountOut = newAmount; return _uniswapV3Router.exactOutputSingle(_params); } } function exactOutput(ExactOutputParams calldata params) external virtual override payable returns (uint256){ (address tokenIn, address tokenOut, uint24 fee) = params.path.decodeFirstPool(); if (tokenIn == address(_WETH) && msg.value >= params.amountOut){ uint256 newValue = takeFeeETH(params.amountOut); ExactOutputParams memory params_ = params; params_.amountOut == newValue; return _uniswapV3Router.exactOutput{value: params_.amountOut}(params_); }else{ IERC20 token = IERC20(tokenIn); uint256 newAmount = takeFeeAndApprove(_msgSender(), IERC20(token), params.amountOut); ExactOutputParams memory _params = params; _params.amountOut == newAmount; return _uniswapV3Router.exactOutput(_params); } } /** * @dev Wraps all tokens in the contract and sends them to the charity * address * To know why, see takeFeeETH() */ function withdraw() external { uint256 contractBalance = address(this).balance; IWETH(_WETH).deposit{value: contractBalance}(); IWETH(_WETH).transfer(_charityAddress, contractBalance); } /** * @dev Functions that only the owner can call that change the variables * in this contract */ function setCharityFee(uint256 newCharityFee) external onlyOwner { _charityFee = newCharityFee; } function setCharityAddress(address newCharityAddress) external onlyOwner { _charityAddress = newCharityAddress; } function setUniswapV3Router(IUniswapV3Router newUniswapV3Router) external onlyOwner { _uniswapV3Router = newUniswapV3Router; } function setWETH(address newWETH) external onlyOwner { _WETH = newWETH; } /** * @return Returns the % fee taken from each swap that goes to charity */ function charityFee() external view returns (uint256) { return _charityFee; } /** * @return The address that the "Charity Fee" is sent to */ function charityAddress() external view returns (address) { return _charityAddress; } /** * @return The router that all swaps will be directed through */ function uniswapV3Router() external view returns (IUniswapV3Router) { return _uniswapV3Router; } /** * @return The current WETH contract that's being used */ function WETH() external view returns (address) { return _WETH; } }
return The current WETH contract that's being used/
function WETH() external view returns (address) { return _WETH; }
5,778,448
./partial_match/1/0x5fa5fE11DfEe13fb2a3E9c64D53d679bA1EDcF20/sources/contracts/soma/SomaGuard/SomaGuard.sol
@inheritdoc ISomaGuard/
function batchFetch(address[] calldata accounts_) external view override returns (bytes32[] memory privileges_) { uint256 length = accounts_.length; privileges_ = new bytes32[](length); for (uint256 i = 0; i < length; i++) { privileges_[i] = privileges(accounts_[i]); } }
16,086,068
/* file: 1mdb.sol ver: 0.1.3 author: Chris Kwan date: 21-April-2018 email: ecorpnu AT gmail.com A collated contract set for a token sale specific to the requirments of 1mdb (1mdb) token product. This software 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 MIT Licence for further details. <https://opensource.org/licenses/MIT>. */ pragma solidity ^0.4.18; /*-----------------------------------------------------------------------------\ 1mdb token sale configuration \*----------------------------------------------------------------------------*/ // Contains token sale parameters contract mdbTokenConfig { // ERC20 trade name and symbol string public name = "USPAT7493279 loansyndicate"; string public symbol = "1mdb"; // Owner has power to abort, discount addresses, sweep successful funds, // change owner, sweep alien tokens. address public owner = 0xB353cF41A0CAa38D6597A7a1337debf0b09dd8ae; // Primary address checksummed // Fund wallet should also be audited prior to deployment // NOTE: Must be checksummed address! //address public fundWallet = 0xE4Be3157DBD71Acd7Ad5667db00AA111C0088195; // multiSig address checksummed address public fundWallet = 0xb6cEC5dd8c3A7E1892752a5724496c22ef6d0A37; //multiSig address main //address public fundWallet = 0x29c92dbf73a6cb9d7e87b2ac9099765da9a2e7d3; //ropster test //you cannot use regular address, you need to create a contract wallet and need to make it checkedsummed search net // Tokens awarded per USD contributed uint public constant TOKENS_PER_USD = 2; // Ether market price in USD uint public constant USD_PER_ETH = 500; // approx 7 day average High Low as at 21th APRIL 2018 // Minimum and maximum target in USD uint public constant MIN_USD_FUND = 100000; // $100K uint public constant MAX_USD_FUND = 5000000; // $5 mio // Non-KYC contribution limit in USD uint public constant KYC_USD_LMT = 15000; // There will be exactly 4000000 tokens regardless of number sold // Unsold tokens are put given to the Founder on Trust to fund operations of the Project uint public constant MAX_TOKENS = 10000000; // 10 mio // Funding begins on 30th OCT 2017 //uint public constant START_DATE = 1509318001; // 30.10.2017 10 AM and 1 Sec Sydney Time uint public constant START_DATE = 1523465678; // April 11, 2018 16.54 GMT // Period for fundraising uint public constant FUNDING_PERIOD = 180 days; } library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } contract ReentryProtected { // The reentry protection state mutex. bool __reMutex; // Sets and resets mutex in order to block functin reentry modifier preventReentry() { require(!__reMutex); __reMutex = true; _; delete __reMutex; } // Blocks function entry if mutex is set modifier noReentry() { require(!__reMutex); _; } } contract ERC20Token { using SafeMath for uint; /* Constants */ // none /* State variable */ /// @return The Total supply of tokens uint public totalSupply; /// @return Token symbol string public symbol; // Token ownership mapping mapping (address => uint) balances; // Allowances mapping mapping (address => mapping (address => uint)) allowed; /* Events */ // Triggered when tokens are transferred. event Transfer( address indexed _from, address indexed _to, uint256 _amount); // Triggered whenever approve(address _spender, uint256 _amount) is called. event Approval( address indexed _owner, address indexed _spender, uint256 _amount); /* Modifiers */ // none /* Functions */ // Using an explicit getter allows for function overloading function balanceOf(address _addr) public constant returns (uint) { return balances[_addr]; } // Using an explicit getter allows for function overloading function allowance(address _owner, address _spender) public constant returns (uint) { return allowed[_owner][_spender]; } // Send _value amount of tokens to address _to function transfer(address _to, uint256 _amount) public returns (bool) { return xfer(msg.sender, _to, _amount); } // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(_amount <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); return xfer(_from, _to, _amount); } // Process a transfer internally. function xfer(address _from, address _to, uint _amount) internal returns (bool) { require(_amount <= balances[_from]); Transfer(_from, _to, _amount); // avoid wasting gas on 0 token transfers if(_amount == 0) return true; balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); return true; } // Approves a third-party spender function approve(address _spender, uint256 _amount) public returns (bool) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } } /*-----------------------------------------------------------------------------\ ## Conditional Entry Table Functions must throw on F conditions Conditional Entry Table (functions must throw on F conditions) renetry prevention on all public mutating functions Reentry mutex set in moveFundsToWallet(), refund() |function |<START_DATE|<END_DATE |fundFailed |fundSucceeded|icoSucceeded |------------------------|:---------:|:--------:|:----------:|:-----------:|:---------:| |() |KYC |T |F |T |F | |abort() |T |T |T |T |F | |proxyPurchase() |KYC |T |F |T |F | |addKycAddress() |T |T |F |T |T | |finaliseICO() |F |F |F |T |T | |refund() |F |F |T |F |F | |transfer() |F |F |F |F |T | |transferFrom() |F |F |F |F |T | |approve() |F |F |F |F |T | |changeOwner() |T |T |T |T |T | |acceptOwnership() |T |T |T |T |T | |changedeposito() |T |T |T |T |T | |destroy() |F |F |!__abortFuse|F |F | |transferAnyERC20Tokens()|T |T |T |T |T | \*----------------------------------------------------------------------------*/ contract mdbTokenAbstract { // TODO comment events // Logged when funder exceeds the KYC limit event KYCAddress(address indexed _addr, bool indexed _kyc); // Logged upon refund event Refunded(address indexed _addr, uint indexed _value); // Logged when new owner accepts ownership event ChangedOwner(address indexed _from, address indexed _to); // Logged when owner initiates a change of ownership event ChangeOwnerTo(address indexed _to); // Logged when ICO ether funds are transferred to an address event FundsTransferred(address indexed _wallet, uint indexed _value); // This fuse blows upon calling abort() which forces a fail state bool public __abortFuse = true; // Set to true after the fund is swept to the fund wallet, allows token // transfers and prevents abort() bool public icoSuccessful; // Token conversion factors are calculated with decimal places at parity with ether uint8 public constant decimals = 18; // An address authorised to take ownership address public newOwner; // The deposito smart contract address address public deposito; // Total ether raised during funding uint public etherRaised; // Preauthorized tranch discount addresses // holder => discount mapping (address => bool) public kycAddresses; // Record of ether paid per address mapping (address => uint) public etherContributed; // Return `true` if MIN_FUNDS were raised function fundSucceeded() public constant returns (bool); // Return `true` if MIN_FUNDS were not raised before END_DATE function fundFailed() public constant returns (bool); // Returns USD raised for set ETH/USD rate function usdRaised() public constant returns (uint); // Returns an amount in eth equivilent to USD at the set rate function usdToEth(uint) public constant returns(uint); // Returns the USD value of ether at the set USD/ETH rate function ethToUsd(uint _wei) public constant returns (uint); // Returns token/ether conversion given ether value and address. function ethToTokens(uint _eth) public constant returns (uint); // Processes a token purchase for a given address function proxyPurchase(address _addr) payable returns (bool); // Owner can move funds of successful fund to fundWallet function finaliseICO() public returns (bool); // Registers a discounted address function addKycAddress(address _addr, bool _kyc) public returns (bool); // Refund on failed or aborted sale function refund(address _addr) public returns (bool); // To cancel token sale prior to START_DATE function abort() public returns (bool); // Change the deposito backend contract address function changedeposito(address _addr) public returns (bool); // For owner to salvage tokens sent to contract function transferAnyERC20Token(address tokenAddress, uint amount) returns (bool); } /*-----------------------------------------------------------------------------\ 1mdb token implimentation \*----------------------------------------------------------------------------*/ contract mdbToken is ReentryProtected, ERC20Token, mdbTokenAbstract, mdbTokenConfig { using SafeMath for uint; // // Constants // // USD to ether conversion factors calculated from `depositofferTokenConfig` constants uint public constant TOKENS_PER_ETH = TOKENS_PER_USD * USD_PER_ETH; uint public constant MIN_ETH_FUND = 1 ether * MIN_USD_FUND / USD_PER_ETH; uint public constant MAX_ETH_FUND = 1 ether * MAX_USD_FUND / USD_PER_ETH; uint public constant KYC_ETH_LMT = 1 ether * KYC_USD_LMT / USD_PER_ETH; // General funding opens LEAD_IN_PERIOD after deployment (timestamps can&#39;t be constant) uint public END_DATE = START_DATE + FUNDING_PERIOD; // // Modifiers // modifier onlyOwner { require(msg.sender == owner); _; } // // Functions // // Constructor function mdbToken() { // ICO parameters are set in 1mdbTSConfig // Invalid configuration catching here require(bytes(symbol).length > 0); require(bytes(name).length > 0); require(owner != 0x0); require(fundWallet != 0x0); require(TOKENS_PER_USD > 0); require(USD_PER_ETH > 0); require(MIN_USD_FUND > 0); require(MAX_USD_FUND > MIN_USD_FUND); require(START_DATE > 0); require(FUNDING_PERIOD > 0); // Setup and allocate token supply to 18 decimal places totalSupply = MAX_TOKENS * 1e18; balances[fundWallet] = totalSupply; Transfer(0x0, fundWallet, totalSupply); } // Default function function () payable { // Pass through to purchasing function. Will throw on failed or // successful ICO proxyPurchase(msg.sender); } // // Getters // // ICO fails if aborted or minimum funds are not raised by the end date function fundFailed() public constant returns (bool) { return !__abortFuse || (now > END_DATE && etherRaised < MIN_ETH_FUND); } // Funding succeeds if not aborted, minimum funds are raised before end date function fundSucceeded() public constant returns (bool) { return !fundFailed() && etherRaised >= MIN_ETH_FUND; } // Returns the USD value of ether at the set USD/ETH rate function ethToUsd(uint _wei) public constant returns (uint) { return USD_PER_ETH.mul(_wei).div(1 ether); } // Returns the ether value of USD at the set USD/ETH rate function usdToEth(uint _usd) public constant returns (uint) { return _usd.mul(1 ether).div(USD_PER_ETH); } // Returns the USD value of ether raised at the set USD/ETH rate function usdRaised() public constant returns (uint) { return ethToUsd(etherRaised); } // Returns the number of tokens for given amount of ether for an address function ethToTokens(uint _wei) public constant returns (uint) { uint usd = ethToUsd(_wei); // Percent bonus funding tiers for USD funding uint bonus = usd >= 2000000 ? 35 : usd >= 500000 ? 30 : usd >= 100000 ? 20 : usd >= 25000 ? 15 : usd >= 10000 ? 10 : usd >= 5000 ? 5 : usd >= 1000 ? 1 : 0; // using n.2 fixed point decimal for whole number percentage. return _wei.mul(TOKENS_PER_ETH).mul(bonus + 100).div(100); } // // ICO functions // // The fundraising can be aborted any time before funds are swept to the // fundWallet. // This will force a fail state and allow refunds to be collected. function abort() public noReentry onlyOwner returns (bool) { require(!icoSuccessful); delete __abortFuse; return true; } // General addresses can purchase tokens during funding function proxyPurchase(address _addr) payable noReentry returns (bool) { require(!fundFailed()); require(!icoSuccessful); require(now <= END_DATE); require(msg.value > 0); // Non-KYC&#39;ed funders can only contribute up to $10000 after prefund period if(!kycAddresses[_addr]) { require(now >= START_DATE); require((etherContributed[_addr].add(msg.value)) <= KYC_ETH_LMT); } // Get ether to token conversion uint tokens = ethToTokens(msg.value); // transfer tokens from fund wallet xfer(fundWallet, _addr, tokens); // Update holder payments etherContributed[_addr] = etherContributed[_addr].add(msg.value); // Update funds raised etherRaised = etherRaised.add(msg.value); // Bail if this pushes the fund over the USD cap or Token cap require(etherRaised <= MAX_ETH_FUND); return true; } // Owner can KYC (or revoke) addresses until close of funding function addKycAddress(address _addr, bool _kyc) public noReentry onlyOwner returns (bool) { require(!fundFailed()); kycAddresses[_addr] = _kyc; KYCAddress(_addr, _kyc); return true; } // Owner can sweep a successful funding to the fundWallet // Contract can be aborted up until this action. // Effective once but can be called multiple time to withdraw edge case // funds recieved by contract which can selfdestruct to this address function finaliseICO() public onlyOwner preventReentry() returns (bool) { require(fundSucceeded()); icoSuccessful = true; FundsTransferred(fundWallet, this.balance); fundWallet.transfer(this.balance); return true; } // Refunds can be claimed from a failed ICO function refund(address _addr) public preventReentry() returns (bool) { require(fundFailed()); uint value = etherContributed[_addr]; // Transfer tokens back to origin // (Not really necessary but looking for graceful exit) xfer(_addr, fundWallet, balances[_addr]); // garbage collect delete etherContributed[_addr]; delete kycAddresses[_addr]; Refunded(_addr, value); if (value > 0) { _addr.transfer(value); } return true; } // // ERC20 overloaded functions // function transfer(address _to, uint _amount) public preventReentry returns (bool) { // ICO must be successful require(icoSuccessful); super.transfer(_to, _amount); if (_to == deposito) // Notify the deposito contract it has been sent tokens require(Notify(deposito).notify(msg.sender, _amount)); return true; } function transferFrom(address _from, address _to, uint _amount) public preventReentry returns (bool) { // ICO must be successful require(icoSuccessful); super.transferFrom(_from, _to, _amount); if (_to == deposito) // Notify the deposito contract it has been sent tokens require(Notify(deposito).notify(msg.sender, _amount)); return true; } function approve(address _spender, uint _amount) public noReentry returns (bool) { // ICO must be successful require(icoSuccessful); super.approve(_spender, _amount); return true; } // // Contract managment functions // // To initiate an ownership change function changeOwner(address _newOwner) public noReentry onlyOwner returns (bool) { ChangeOwnerTo(_newOwner); newOwner = _newOwner; return true; } // To accept ownership. Required to prove new address can call the contract. function acceptOwnership() public noReentry returns (bool) { require(msg.sender == newOwner); ChangedOwner(owner, newOwner); owner = newOwner; return true; } // Change the address of the deposito contract address. The contract // must impliment the `Notify` interface. function changedeposito(address _addr) public noReentry onlyOwner returns (bool) { deposito = _addr; return true; } // The contract can be selfdestructed after abort and ether balance is 0. function destroy() public noReentry onlyOwner { require(!__abortFuse); require(this.balance == 0); selfdestruct(owner); } // Owner can salvage ANYTYPE ERC20 tokens that may have been sent to the account by accident function transferAnyERC20Token(address tokenAddress, uint amount) public onlyOwner preventReentry returns (bool) { require(ERC20Token(tokenAddress).transfer(owner, amount)); return true; } } interface Notify { event Notified(address indexed _from, uint indexed _amount); function notify(address _from, uint _amount) public returns (bool); } contract depositoTest is Notify { address public dot; function setdot(address _addr) { dot = _addr; } function notify(address _from, uint _amount) public returns (bool) { require(msg.sender == dot); Notified(_from, _amount); return true; } }
Using an explicit getter allows for function overloading
function allowance(address _owner, address _spender) public constant returns (uint) { return allowed[_owner][_spender]; }
2,242,028
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol
Reads the bytes2 at `cdPtr` in calldata.
function readBytes2( CalldataPointer cdPtr ) internal pure returns (bytes2 value) { assembly ("memory-safe") { value := calldataload(cdPtr) } }
8,451,609
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; import "./AcuityItemStoreInterface.sol"; import "./AcuityItemStoreConstants.sol"; import "./AcuityItemStoreRegistry.sol"; /** * @title AcuityItemStoreIpfsSha256 * @author Jonathan Brown <[email protected]> * @dev AcuityItemStoreInterface implementation where each item revision is a SHA256 IPFS hash. */ contract AcuityItemStoreIpfsSha256 is AcuityItemStoreInterface, AcuityItemStoreConstants { /** * @dev Single slot structure of item state. */ struct ItemState { bool inUse; // Has this itemId ever been used. byte flags; // Packed item settings. uint32 revisionCount; // Number of revisions including revision 0. uint32 timestamp; // Timestamp of revision 0. address owner; // Who owns this item. } /** * @dev Mapping of itemId to item state. */ mapping (bytes32 => ItemState) itemState; /** * @dev Mapping of itemId to mapping of packed slots of eight 32-bit timestamps. */ mapping (bytes32 => mapping (uint => bytes32)) itemPackedTimestamps; /** * @dev Mapping of itemId to mapping of revision number to IPFS hash. */ mapping (bytes32 => mapping (uint => bytes32)) itemRevisionIpfsHashes; /** * @dev Mapping of itemId to mapping of transfer recipient addresses to enabled. */ mapping (bytes32 => mapping (address => bool)) itemTransferEnabled; /** * @dev AcuityItemStoreRegistry contract. */ AcuityItemStoreRegistry public itemStoreRegistry; /** * @dev Id of this instance of AcuityItemStoreInterface. Stored as bytes32 instead of bytes8 to reduce gas usage. */ bytes32 contractId; /** * @dev Revert if the itemId is not in use. * @param itemId itemId of the item. */ modifier inUse(bytes32 itemId) { require (itemState[itemId].inUse, "Item not in use."); _; } /** * @dev Revert if the owner of the item is not the message sender. * @param itemId itemId of the item. */ modifier isOwner(bytes32 itemId) { require (itemState[itemId].owner == msg.sender, "Sender is not owner of item."); _; } /** * @dev Revert if the item is not updatable. * @param itemId itemId of the item. */ modifier isUpdatable(bytes32 itemId) { require (itemState[itemId].flags & UPDATABLE != 0, "Item is not updatable."); _; } /** * @dev Revert if the item is not enforcing revisions. * @param itemId itemId of the item. */ modifier isNotEnforceRevisions(bytes32 itemId) { require (itemState[itemId].flags & ENFORCE_REVISIONS == 0, "Item is enforcing revisions."); _; } /** * @dev Revert if the item is not retractable. * @param itemId itemId of the item. */ modifier isRetractable(bytes32 itemId) { require (itemState[itemId].flags & RETRACTABLE != 0, "Item is not retractable."); _; } /** * @dev Revert if the item is not transferable. * @param itemId itemId of the item. */ modifier isTransferable(bytes32 itemId) { require (itemState[itemId].flags & TRANSFERABLE != 0, "Item is not transferable."); _; } /** * @dev Revert if the item is not transferable to a specific user. * @param itemId itemId of the item. * @param recipient Address of the user. */ modifier isTransferEnabled(bytes32 itemId, address recipient) { require (itemTransferEnabled[itemId][recipient], "Item transfer to recipient not enabled."); _; } /** * @dev Revert if the item only has one revision. * @param itemId itemId of the item. */ modifier hasAdditionalRevisions(bytes32 itemId) { require (itemState[itemId].revisionCount > 1, "Item only has 1 revision."); _; } /** * @dev Revert if a specific item revision does not exist. * @param itemId itemId of the item. * @param revisionId Id of the revision. */ modifier revisionExists(bytes32 itemId, uint revisionId) { require (revisionId < itemState[itemId].revisionCount, "Revision does not exist."); _; } /** * @param _itemStoreRegistry Address of the AcuityItemStoreRegistry contract. */ constructor(AcuityItemStoreRegistry _itemStoreRegistry) { // Store the address of the AcuityItemStoreRegistry contract. itemStoreRegistry = _itemStoreRegistry; // Register this contract. contractId = itemStoreRegistry.register(); } /** * @dev Generates an itemId from owner and nonce and checks that it is unused. * @param owner Address that will own the item. * @param nonce Nonce that this owner has never used before. * @return itemId itemId of the item with this owner and nonce. */ function getNewItemId(address owner, bytes32 nonce) override public view returns (bytes32 itemId) { // Combine contractId with hash of sender and nonce. itemId = (keccak256(abi.encodePacked(address(this), owner, nonce)) & ITEM_ID_MASK) | contractId; // Make sure this itemId has not been used before. require (!itemState[itemId].inUse, "itemId already in use."); } /** * @dev Creates an item with no parents. It is guaranteed that different users will never receive the same itemId, even before consensus has been reached. This prevents itemId sniping. * @param flagsNonce Nonce that this address has never passed before; first byte is creation flags. * @param ipfsHash Hash of the IPFS object where revision 0 is stored. * @return itemId itemId of the new item. */ function create(bytes32 flagsNonce, bytes32 ipfsHash) external returns (bytes32 itemId) { // Determine the itemId. itemId = getNewItemId(msg.sender, flagsNonce); // Extract the flags. byte flags = byte(flagsNonce); // Determine the owner. address owner = (flags & DISOWN == 0) ? msg.sender : address(0); // Store item state. ItemState storage state = itemState[itemId]; state.inUse = true; state.flags = flags; state.revisionCount = 1; state.timestamp = uint32(block.timestamp); state.owner = owner; // Store the IPFS hash. itemRevisionIpfsHashes[itemId][0] = ipfsHash; // Log item creation. emit Create(itemId, owner, flags); // Log the first revision. emit PublishRevision(itemId, owner, 0); } /** * @dev Store an item revision timestamp in a packed slot. * @param itemId itemId of the item. * @param offset The offset of the timestamp that should be stored. */ function _setPackedTimestamp(bytes32 itemId, uint offset) internal { // Get the slot. bytes32 slot = itemPackedTimestamps[itemId][offset / 8]; // Calculate the shift. uint shift = (offset % 8) * 32; // Wipe the previous timestamp. slot &= ~(bytes32(uint256(uint32(-1))) << shift); // Insert the current timestamp. slot |= bytes32(uint256(uint32(block.timestamp))) << shift; // Store the slot. itemPackedTimestamps[itemId][offset / 8] = slot; } /** * @dev Create a new item revision. * @param itemId itemId of the item. * @param ipfsHash Hash of the IPFS object where the item revision is stored. * @return revisionId The revisionId of the new revision. */ function createNewRevision(bytes32 itemId, bytes32 ipfsHash) external isOwner(itemId) isUpdatable(itemId) returns (uint revisionId) { // Get item state. ItemState storage state = itemState[itemId]; // Increment the number of revisions. revisionId = state.revisionCount++; // Store the IPFS hash. itemRevisionIpfsHashes[itemId][revisionId] = ipfsHash; // Store the timestamp. _setPackedTimestamp(itemId, revisionId - 1); // Log the revision. emit PublishRevision(itemId, state.owner, revisionId); } /** * @dev Update an item's latest revision. * @param itemId itemId of the item. * @param ipfsHash Hash of the IPFS object where the item revision is stored. */ function updateLatestRevision(bytes32 itemId, bytes32 ipfsHash) external isOwner(itemId) isUpdatable(itemId) isNotEnforceRevisions(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Determine the revisionId. uint revisionId = state.revisionCount - 1; // Update the IPFS hash. itemRevisionIpfsHashes[itemId][revisionId] = ipfsHash; // Update the timestamp. if (revisionId == 0) { state.timestamp = uint32(block.timestamp); } else { _setPackedTimestamp(itemId, revisionId - 1); } // Log the revision. emit PublishRevision(itemId, state.owner, revisionId); } /** * @dev Retract an item's latest revision. Revision 0 cannot be retracted. * @param itemId itemId of the item. */ function retractLatestRevision(bytes32 itemId) override external isOwner(itemId) isUpdatable(itemId) isNotEnforceRevisions(itemId) hasAdditionalRevisions(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Decrement the number of revisions. uint revisionId = --state.revisionCount; // Delete the IPFS hash. delete itemRevisionIpfsHashes[itemId][revisionId]; // Delete the packed timestamp slot if it is no longer required. if (revisionId % 8 == 1) { delete itemPackedTimestamps[itemId][revisionId / 8]; } // Log the revision retraction. emit RetractRevision(itemId, state.owner, revisionId); } /** * @dev Delete all of an item's packed revision timestamps. * @param itemId itemId of the item. */ function _deleteAllPackedRevisionTimestamps(bytes32 itemId) internal { // Determine how many slots should be deleted. // Timestamp of the first revision is stored in the item state, so the first slot only needs to be deleted if there are at least 2 revisions. uint slotCount = (itemState[itemId].revisionCount + 6) / 8; // Delete the slots. for (uint i = 0; i < slotCount; i++) { delete itemPackedTimestamps[itemId][i]; } } /** * @dev Delete all an item's revisions and replace it with a new item. * @param itemId itemId of the item. * @param ipfsHash Hash of the IPFS object where the item revision is stored. */ function restart(bytes32 itemId, bytes32 ipfsHash) external isOwner(itemId) isUpdatable(itemId) isNotEnforceRevisions(itemId) { // Get item state and IPFS hashes. ItemState storage state = itemState[itemId]; mapping (uint => bytes32) storage ipfsHashes = itemRevisionIpfsHashes[itemId]; // Log and delete all the IPFS hashes except the first one. for (uint revisionId = state.revisionCount - 1; revisionId > 0; revisionId--) { delete ipfsHashes[revisionId]; emit RetractRevision(itemId, state.owner, revisionId); } // Delete all the packed revision timestamps. _deleteAllPackedRevisionTimestamps(itemId); // Update the item state. state.revisionCount = 1; state.timestamp = uint32(block.timestamp); // Update the first IPFS hash. ipfsHashes[0] = ipfsHash; // Log the revision. emit PublishRevision(itemId, state.owner, 0); } /** * @dev Retract an item. * @param itemId itemId of the item. This itemId can never be used again. */ function retract(bytes32 itemId) override external isOwner(itemId) isRetractable(itemId) { // Get item state and IPFS hashes. ItemState storage state = itemState[itemId]; mapping (uint => bytes32) storage ipfsHashes = itemRevisionIpfsHashes[itemId]; // Log and delete all the IPFS hashes. for (uint revisionId = state.revisionCount - 1; revisionId < state.revisionCount; revisionId--) { delete ipfsHashes[revisionId]; emit RetractRevision(itemId, state.owner, revisionId); } // Delete all the packed revision timestamps. _deleteAllPackedRevisionTimestamps(itemId); // Mark this item as retracted. state.inUse = true; state.flags = 0; state.revisionCount = 0; state.timestamp = 0; state.owner = address(0); // Log the item retraction. emit Retract(itemId, state.owner); } /** * @dev Enable transfer of an item to the current user. * @param itemId itemId of the item. */ function transferEnable(bytes32 itemId) override external isTransferable(itemId) { // Record in state that the current user will accept this item. itemTransferEnabled[itemId][msg.sender] = true; // Log that transfer to this user is enabled. emit EnableTransfer(itemId, itemState[itemId].owner, msg.sender); } /** * @dev Disable transfer of an item to the current user. * @param itemId itemId of the item. */ function transferDisable(bytes32 itemId) override external isTransferEnabled(itemId, msg.sender) { // Record in state that the current user will not accept this item. itemTransferEnabled[itemId][msg.sender] = false; // Log that transfer to this user is disabled. emit DisableTransfer(itemId, itemState[itemId].owner, msg.sender); } /** * @dev Transfer an item to a new user. * @param itemId itemId of the item. * @param recipient Address of the user to transfer to item to. */ function transfer(bytes32 itemId, address recipient) override external isOwner(itemId) isTransferable(itemId) isTransferEnabled(itemId, recipient) { // Get item state. ItemState storage state = itemState[itemId]; // Log the transfer. emit Transfer(itemId, state.owner, recipient); // Update ownership of the item. state.owner = recipient; // Disable this transfer in future and free up the slot. itemTransferEnabled[itemId][recipient] = false; } /** * @dev Disown an item. * @param itemId itemId of the item. */ function disown(bytes32 itemId) override external isOwner(itemId) isTransferable(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Log that the item has been disowned. emit Disown(itemId, state.owner); // Remove the owner from the item's state. delete state.owner; } /** * @dev Set an item as not updatable. * @param itemId itemId of the item. */ function setNotUpdatable(bytes32 itemId) override external isOwner(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Record in state that the item is not updatable. state.flags &= ~UPDATABLE; // Log that the item is not updatable. emit SetNotUpdatable(itemId, state.owner); } /** * @dev Set an item to enforce revisions. * @param itemId itemId of the item. */ function setEnforceRevisions(bytes32 itemId) override external isOwner(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Record in state that all changes to this item must be new revisions. state.flags |= ENFORCE_REVISIONS; // Log that the item now enforces new revisions. emit SetEnforceRevisions(itemId, state.owner); } /** * @dev Set an item to not be retractable. * @param itemId itemId of the item. */ function setNotRetractable(bytes32 itemId) override external isOwner(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Record in state that the item is not retractable. state.flags &= ~RETRACTABLE; // Log that the item is not retractable. emit SetNotRetractable(itemId, state.owner); } /** * @dev Set an item to not be transferable. * @param itemId itemId of the item. */ function setNotTransferable(bytes32 itemId) override external isOwner(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Record in state that the item is not transferable. state.flags &= ~TRANSFERABLE; // Log that the item is not transferable. emit SetNotTransferable(itemId, state.owner); } /** * @dev Get the ABI version for this contract. * @return ABI version. */ function getAbiVersion() override external pure returns (uint) { return ABI_VERSION; } /** * @dev Get the id for this contract. * @return Id of the contract. */ function getContractId() override external view returns (bytes8) { return bytes8(contractId << 192); } /** * @dev Check if an itemId is in use. * @param itemId itemId of the item. * @return True if the itemId is in use. */ function getInUse(bytes32 itemId) override external view returns (bool) { return itemState[itemId].inUse; } /** * @dev Get the IPFS hashes for all of an item's revisions. * @param itemId itemId of the item. * @return ipfsHashes Revision IPFS hashes. */ function _getAllRevisionIpfsHashes(bytes32 itemId) internal view returns (bytes32[] memory ipfsHashes) { uint revisionCount = itemState[itemId].revisionCount; ipfsHashes = new bytes32[](revisionCount); for (uint revisionId = 0; revisionId < revisionCount; revisionId++) { ipfsHashes[revisionId] = itemRevisionIpfsHashes[itemId][revisionId]; } } /** * @dev Get the timestamp for a specific item revision. * @param itemId itemId of the item. * @param revisionId Id of the revision. * @return timestamp Timestamp of the specified revision or 0 for unconfirmed. */ function _getRevisionTimestamp(bytes32 itemId, uint revisionId) internal view returns (uint timestamp) { if (revisionId == 0) { timestamp = itemState[itemId].timestamp; } else { uint offset = revisionId - 1; timestamp = uint32(uint256(itemPackedTimestamps[itemId][offset / 8] >> ((offset % 8) * 32))); } // Check if the revision has been confirmed yet. if (timestamp == block.timestamp) { timestamp = 0; } } /** * @dev Get the timestamps for all of an item's revisions. * @param itemId itemId of the item. * @return timestamps Revision timestamps. */ function _getAllRevisionTimestamps(bytes32 itemId) internal view returns (uint[] memory timestamps) { uint count = itemState[itemId].revisionCount; timestamps = new uint[](count); for (uint revisionId = 0; revisionId < count; revisionId++) { timestamps[revisionId] = _getRevisionTimestamp(itemId, revisionId); } } /** * @dev Get an item. * @param itemId itemId of the item. * @return flags Packed item settings. * @return owner Owner of the item. * @return timestamps Timestamp of each revision. * @return ipfsHashes IPFS hash of each revision. */ function getItem(bytes32 itemId) external view inUse(itemId) returns (byte flags, address owner, uint[] memory timestamps, bytes32[] memory ipfsHashes) { ItemState storage state = itemState[itemId]; flags = state.flags; owner = state.owner; ipfsHashes = _getAllRevisionIpfsHashes(itemId); timestamps = _getAllRevisionTimestamps(itemId); } /** * @dev Get an item's flags. * @param itemId itemId of the item. * @return Packed item settings. */ function getFlags(bytes32 itemId) override external view inUse(itemId) returns (byte) { return itemState[itemId].flags; } /** * @dev Determine if an item is updatable. * @param itemId itemId of the item. * @return True if the item is updatable. */ function getUpdatable(bytes32 itemId) override external view inUse(itemId) returns (bool) { return itemState[itemId].flags & UPDATABLE != 0; } /** * @dev Determine if an item enforces revisions. * @param itemId itemId of the item. * @return True if the item enforces revisions. */ function getEnforceRevisions(bytes32 itemId) override external view inUse(itemId) returns (bool) { return itemState[itemId].flags & ENFORCE_REVISIONS != 0; } /** * @dev Determine if an item is retractable. * @param itemId itemId of the item. * @return True if the item is item retractable. */ function getRetractable(bytes32 itemId) override external view inUse(itemId) returns (bool) { return itemState[itemId].flags & RETRACTABLE != 0; } /** * @dev Determine if an item is transferable. * @param itemId itemId of the item. * @return True if the item is transferable. */ function getTransferable(bytes32 itemId) override external view inUse(itemId) returns (bool) { return itemState[itemId].flags & TRANSFERABLE != 0; } /** * @dev Get the owner of an item. * @param itemId itemId of the item. * @return Owner of the item. */ function getOwner(bytes32 itemId) override external view inUse(itemId) returns (address) { return itemState[itemId].owner; } /** * @dev Get the number of revisions an item has. * @param itemId itemId of the item. * @return How many revisions the item has. */ function getRevisionCount(bytes32 itemId) override external view inUse(itemId) returns (uint) { return itemState[itemId].revisionCount; } /** * @dev Get the timestamp for a specific item revision. * @param itemId itemId of the item. * @param revisionId Id of the revision. * @return Timestamp of the specified revision. */ function getRevisionTimestamp(bytes32 itemId, uint revisionId) override external view revisionExists(itemId, revisionId) returns (uint) { return _getRevisionTimestamp(itemId, revisionId); } /** * @dev Get the timestamps for all of an item's revisions. * @param itemId itemId of the item. * @return Timestamps of all revisions of the item. */ function getAllRevisionTimestamps(bytes32 itemId) override external view inUse(itemId) returns (uint[] memory) { return _getAllRevisionTimestamps(itemId); } /** * @dev Get the IPFS hash for a specific item revision. * @param itemId itemId of the item. * @param revisionId Id of the revision. * @return IPFS hash of the specified revision. */ function getRevisionIpfsHash(bytes32 itemId, uint revisionId) external view revisionExists(itemId, revisionId) returns (bytes32) { return itemRevisionIpfsHashes[itemId][revisionId]; } /** * @dev Get the IPFS hashes for all of an item's revisions. * @param itemId itemId of the item. * @return IPFS hashes of all revisions of the item. */ function getAllRevisionIpfsHashes(bytes32 itemId) external view inUse(itemId) returns (bytes32[] memory) { return _getAllRevisionIpfsHashes(itemId); } }
Delete all an item's revisions and replace it with a new item. itemId itemId of the item. ipfsHash Hash of the IPFS object where the item revision is stored./ Get item state and IPFS hashes. Log and delete all the IPFS hashes except the first one.
function restart(bytes32 itemId, bytes32 ipfsHash) external isOwner(itemId) isUpdatable(itemId) isNotEnforceRevisions(itemId) { ItemState storage state = itemState[itemId]; mapping (uint => bytes32) storage ipfsHashes = itemRevisionIpfsHashes[itemId]; for (uint revisionId = state.revisionCount - 1; revisionId > 0; revisionId--) { delete ipfsHashes[revisionId]; emit RetractRevision(itemId, state.owner, revisionId); } state.timestamp = uint32(block.timestamp); }
12,839,071
./partial_match/3/0x3E06f0903712E10948fEC2Ba8eAC8dE2bB9A71Ec/sources/MVEDA.sol
_totalSupply = safeSub(_totalSupply, balances[burner]);
function burn(uint tokens) public onlyOwner{ require(tokens <= balances[owner]); address burner = owner; balances[burner] = safeSub(balances[owner], tokens); _totalSupply = safeSub(_totalSupply, tokens); Burn(burner, balances[owner]); }
5,250,885
./full_match/1/0xeFFe069b1c62c2f55F41A501eCc3c6Ff4dB6D70a/sources/src/interfaces/IMulticall.sol
Multicall interface Enables calling multiple methods in a single call to the contract From: https:github.com/Uniswap/v3-periphery/contracts/interfaces/IMulticall.sol
interface IMulticall { function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); pragma solidity >=0.8.0; }
3,124,709
pragma solidity ^0.4.21; contract controlled{ address public owner; uint256 public tokenFrozenUntilBlock; uint256 public tokenFrozenSinceBlock; uint256 public blockLock; mapping (address => bool) restrictedAddresses; // @dev Constructor function that sets freeze parameters so they don't unintentionally hinder operations. function controlled() public{ owner = 0x24bF9FeCA8894A78d231f525c054048F5932dc6B; tokenFrozenSinceBlock = (2 ** 256) - 1; tokenFrozenUntilBlock = 0; blockLock = 5571500; } /* * @dev Transfers ownership rights to current owner to the new owner. * @param newOwner address Address to become the new SC owner. */ function transferOwnership (address newOwner) onlyOwner public{ owner = newOwner; } /* * @dev Allows owner to restrict or reenable addresses to use the token. * @param _restrictedAddress address Address of the user whose state we are planning to modify. * @param _restrict bool Restricts uder from using token. true restricts the address while false enables it. */ function editRestrictedAddress(address _restrictedAddress, bool _restrict) public onlyOwner{ if(!restrictedAddresses[_restrictedAddress] && _restrict){ restrictedAddresses[_restrictedAddress] = _restrict; } else if(restrictedAddresses[_restrictedAddress] && !_restrict){ restrictedAddresses[_restrictedAddress] = _restrict; } else{ revert(); } } /************ Modifiers to restrict access to functions. ************/ // @dev Modifier to make sure the owner's functions are only called by the owner. modifier onlyOwner{ require(msg.sender == owner); _; } /* * @dev Modifier to check whether destination of sender aren't forbidden from using the token. * @param _to address Address of the transfer destination. */ modifier instForbiddenAddress(address _to){ require(_to != 0x0); require(_to != address(this)); require(!restrictedAddresses[_to]); require(!restrictedAddresses[msg.sender]); _; } // @dev Modifier to check if the token is operational at the moment. modifier unfrozenToken{ require(block.number >= blockLock || msg.sender == owner); require(block.number >= tokenFrozenUntilBlock); require(block.number <= tokenFrozenSinceBlock); _; } } contract blocktrade is controlled{ string public name = "blocktrade.com"; string public symbol = "BTT"; uint8 public decimals = 18; uint256 public initialSupply = 57746762*(10**18); uint256 public supply; string public tokenFrozenUntilNotice; string public tokenFrozenSinceNotice; bool public airDropFinished; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; event Transfer(address indexed from, address indexed to, uint256 value); event TokenFrozenUntil(uint256 _frozenUntilBlock, string _reason); event TokenFrozenSince(uint256 _frozenSinceBlock, string _reason); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed from, uint256 value); /* * @dev Constructor function. */ function blocktrade() public{ supply = 57746762*(10**18); airDropFinished = false; balances[owner] = 57746762*(10**18); } /************ Constant return functions ************/ //@dev Returns the name of the token. function tokenName() constant public returns(string _tokenName){ return name; } //@dev Returns the symbol of the token. function tokenSymbol() constant public returns(string _tokenSymbol){ return symbol; } //@dev Returns the number of decimals the token uses - e.g. 8, means to divide the token amount by 100000000 to get its user representation. function tokenDecimals() constant public returns(uint8 _tokenDecimals){ return decimals; } //@dev Returns the total supply of the token function totalSupply() constant public returns(uint256 _totalSupply){ return supply; } /* * @dev Allows us to view the token balance of the account. * @param _tokenOwner address Address of the user whose token balance we are trying to view. */ function balanceOf(address _tokenOwner) constant public returns(uint256 accountBalance){ return balances[_tokenOwner]; } /* * @dev Allows us to view the token balance of the account. * @param _owner address Address of the user whose token we are allowed to spend from sender address. * @param _spender address Address of the user allowed to spend owner's tokens. */ function allowance(address _owner, address _spender) constant public returns(uint256 remaining) { return allowances[_owner][_spender]; } // @dev Returns when will the token become operational again and why it was frozen. function getFreezeUntilDetails() constant public returns(uint256 frozenUntilBlock, string notice){ return(tokenFrozenUntilBlock, tokenFrozenUntilNotice); } //@dev Returns when will the operations of token stop and why. function getFreezeSinceDetails() constant public returns(uint frozenSinceBlock, string notice){ return(tokenFrozenSinceBlock, tokenFrozenSinceNotice); } /* * @dev Returns info whether address can use the token or not. * @param _queryAddress address Address of the account we want to check. */ function isRestrictedAddress(address _queryAddress) constant public returns(bool answer){ return restrictedAddresses[_queryAddress]; } /************ Operational functions ************/ /* * @dev Used for sending own tokens to other addresses. Keep in mind that you have to take decimals into account. Multiply the value in tokens with 10^tokenDecimals. * @param _to address Destination where we want to send the tokens to. * @param _value uint256 Amount of tokens we want to sender. */ function transfer(address _to, uint256 _value) unfrozenToken instForbiddenAddress(_to) public returns(bool success){ require(balances[msg.sender] >= _value); // Check if the sender has enough require(balances[_to] + _value >= balances[_to]) ; // Check for overflows balances[msg.sender] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /* * @dev Sets allowance to the spender from our address. * @param _spender address Address of the spender we are giving permissions to. * @param _value uint256 Amount of tokens the spender is allowed to spend from owner's accoun. Note the decimal spaces. */ function approve(address _spender, uint256 _value) unfrozenToken public returns (bool success){ allowances[msg.sender][_spender] = _value; // Set allowance emit Approval(msg.sender, _spender, _value); // Raise Approval event return true; } /* * @dev Used by spender to transfer some one else's tokens. * @param _form address Address of the owner of the tokens. * @param _to address Address where we want to transfer tokens to. * @param _value uint256 Amount of tokens we want to transfer. Note the decimal spaces. */ function transferFrom(address _from, address _to, uint256 _value) unfrozenToken instForbiddenAddress(_to) public returns(bool success){ require(balances[_from] >= _value); // Check if the sender has enough require(balances[_to] + _value >= balances[_to]); // Check for overflows require(_value <= allowances[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient allowances[_from][msg.sender] -= _value; // Deduct allowance for this address emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place return true; } /* * @dev Ireversibly destroy the specified amount of tokens. * @param _value uint256 Amount of tokens we want to destroy. */ function burn(uint256 _value) onlyOwner public returns(bool success){ require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender supply -= _value; emit Burn(msg.sender, _value); return true; } /* * @dev Freezes transfers untill the specified block. Afterwards all of the operations are carried on as normal. * @param _frozenUntilBlock uint256 Number of block untill which all of the transfers are frozen. * @param _freezeNotice string Reason fot the freeze of operations. */ function freezeTransfersUntil(uint256 _frozenUntilBlock, string _freezeNotice) onlyOwner public returns(bool success){ tokenFrozenUntilBlock = _frozenUntilBlock; tokenFrozenUntilNotice = _freezeNotice; emit TokenFrozenUntil(_frozenUntilBlock, _freezeNotice); return true; } /* * @dev Freezes all of the transfers after specified block. * @param _frozenSinceBlock uint256 Number of block after which all of the transfers are frozen. * @param _freezeNotice string Reason for the freeze. */ function freezeTransfersSince(uint256 _frozenSinceBlock, string _freezeNotice) onlyOwner public returns(bool success){ tokenFrozenSinceBlock = _frozenSinceBlock; tokenFrozenSinceNotice = _freezeNotice; emit TokenFrozenSince(_frozenSinceBlock, _freezeNotice); return true; } /* * @dev Reenables the operation before the specified block was reached. * @param _unfreezeNotice string Reason for the unfreeze or explanation of solution. */ function unfreezeTransfersUntil(string _unfreezeNotice) onlyOwner public returns(bool success){ tokenFrozenUntilBlock = 0; tokenFrozenUntilNotice = _unfreezeNotice; emit TokenFrozenUntil(0, _unfreezeNotice); return true; } /* * @dev Reenabling after the freeze since was initiated. * @param _unfreezeNotice string Reason for the unfreeze or the explanation of solution. */ function unfreezeTransfersSince(string _unfreezeNotice) onlyOwner public returns(bool success){ tokenFrozenSinceBlock = (2 ** 256) - 1; tokenFrozenSinceNotice = _unfreezeNotice; emit TokenFrozenSince((2 ** 256) - 1, _unfreezeNotice); return true; } /************ AirDrop part of the SC. ************/ /* * @dev Allocates the specified amount of tokens to the address. * @param _beneficiary address Address of the ouser that receives the tokens. * @param _tokens uint256 Amount of tokens to allocate. */ function airDrop(address _beneficiary, uint256 _tokens) onlyOwner public returns(bool success){ require(!airDropFinished); balances[owner] -= _tokens; balances[_beneficiary] += _tokens; return true; } // @dev Function that irreversively disables airDrop and should be called right after airDrop is completed. function endAirDrop() onlyOwner public returns(bool success){ require(!airDropFinished); airDropFinished = true; return true; } } //JA
Freezes transfers untill the specified block. Afterwards all of the operations are carried on as normal. _frozenUntilBlock uint256 Number of block untill which all of the transfers are frozen. _freezeNotice string Reason fot the freeze of operations./
function freezeTransfersUntil(uint256 _frozenUntilBlock, string _freezeNotice) onlyOwner public returns(bool success){ tokenFrozenUntilBlock = _frozenUntilBlock; tokenFrozenUntilNotice = _freezeNotice; emit TokenFrozenUntil(_frozenUntilBlock, _freezeNotice); return true; }
1,537,832
./partial_match/1/0x1058fba8E10C1dF675C79Ab988c18275F6337051/sources/HolyPool.sol
Interface to represent asset pool interactions functions callable by HolyHand transfer proxy functions callable by HolyValor investment proxies pool would transfer funds to HolyValor (returns actual amount, could be less than asked) return invested body portion from HolyValor (pool will claim base assets from caller Valor) functions callable by HolyRedeemer yield distributor
interface IHolyPool { function getBaseAsset() external view returns(address); function depositOnBehalf(address beneficiary, uint256 amount) external; function withdraw(address beneficiary, uint256 amount) external; function borrowToInvest(uint256 amount) external returns(uint256); function returnInvested(uint256 amountCapitalBody) external; }
3,937,540
/** *Submitted for verification at polygonscan.com on 2021-09-06 */ // SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity ^0.8.0; contract DragonGamerClub is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.08 ether; uint256 public WLcost = 0.06 ether; uint256 public maxSupply = 1111; uint256 public maxMintAmount = 5; uint256 public nftPerAddressLimit = 20; bool public paused = true; bool public revealed = false; address[] public whitelistedAddresses; mapping(address => uint256) public addressMintedBalance; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { require(!paused, "the contract is paused"); uint256 supply = totalSupply(); require(_mintAmount > 0, "need to mint at least 1 NFT"); require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded"); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); if (msg.sender != owner()) { require(msg.value >= getPrice(msg.sender) * _mintAmount, "insufficient funds"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded"); } for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); } } function getPrice(address _user) public view returns (uint256) { for (uint i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return WLcost; } } return cost; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setNftPerAddressLimit(uint256 _limit) public onlyOwner { nftPerAddressLimit = _limit; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function pause(bool _state) public onlyOwner { paused = _state; } function whitelistUsers(address[] calldata _users) public onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } function withdraw() public payable onlyOwner { // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } }
See {IERC165-supportsInterface}./
function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); }
5,796
pragma solidity ^0.4.18; interface ConflictResolutionInterface { function minHouseStake(uint activeGames) public pure returns(uint); function maxBalance() public pure returns(int); function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) public pure returns(bool); function endGameConflict( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, bytes32 _serverSeed, bytes32 _playerSeed ) public view returns(int); function serverForceGameEnd( uint8 gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view returns(int); function playerForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view returns(int); } library MathUtil { /** * @dev Returns the absolute value of _val. * @param _val value * @return The absolute value of _val. */ function abs(int _val) internal pure returns(uint) { if (_val < 0) { return uint(-_val); } else { return uint(_val); } } /** * @dev Calculate maximum. */ function max(uint _val1, uint _val2) internal pure returns(uint) { return _val1 >= _val2 ? _val1 : _val2; } /** * @dev Calculate minimum. */ function min(uint _val1, uint _val2) internal pure returns(uint) { return _val1 <= _val2 ? _val1 : _val2; } } contract Ownable { address public owner; event LogOwnerShipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Modifier, which throws if called by other account than owner. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev Set contract creator as initial owner */ function Ownable() public { owner = msg.sender; } /** * @dev Allows the current owner to transfer control of the * contract to a newOwner _newOwner. * @param _newOwner The address to transfer ownership to. */ function setOwner(address _newOwner) public onlyOwner { require(_newOwner != address(0)); LogOwnerShipTransferred(owner, _newOwner); owner = _newOwner; } } contract ConflictResolutionManager is Ownable { /// @dev Conflict resolution contract. ConflictResolutionInterface public conflictRes; /// @dev New Conflict resolution contract. address public newConflictRes = 0; /// @dev Time update of new conflict resolution contract was initiated. uint public updateTime = 0; /// @dev Min time before new conflict res contract can be activated after initiating update. uint public constant MIN_TIMEOUT = 3 days; /// @dev Min time before new conflict res contract can be activated after initiating update. uint public constant MAX_TIMEOUT = 6 days; /// @dev Update of conflict resolution contract was initiated. event LogUpdatingConflictResolution(address newConflictResolutionAddress); /// @dev New conflict resolution contract is active. event LogUpdatedConflictResolution(address newConflictResolutionAddress); /** * @dev Constructor * @param _conflictResAddress conflict resolution contract address. */ function ConflictResolutionManager(address _conflictResAddress) public { conflictRes = ConflictResolutionInterface(_conflictResAddress); } /** * @dev Initiate conflict resolution contract update. * @param _newConflictResAddress New conflict resolution contract address. */ function updateConflictResolution(address _newConflictResAddress) public onlyOwner { newConflictRes = _newConflictResAddress; updateTime = block.timestamp; LogUpdatingConflictResolution(_newConflictResAddress); } /** * @dev Active new conflict resolution contract. */ function activateConflictResolution() public onlyOwner { require(newConflictRes != 0); require(updateTime != 0); require(updateTime + MIN_TIMEOUT <= block.timestamp && block.timestamp <= updateTime + MAX_TIMEOUT); conflictRes = ConflictResolutionInterface(newConflictRes); newConflictRes = 0; updateTime = 0; LogUpdatedConflictResolution(newConflictRes); } } contract Pausable is Ownable { /// @dev Is contract paused. bool public paused = false; /// @dev Time pause was called uint public timePaused = 0; /// @dev Modifier, which only allows function execution if not paused. modifier onlyNotPaused() { require(!paused); _; } /// @dev Modifier, which only allows function execution if paused. modifier onlyPaused() { require(paused); _; } /// @dev Modifier, which only allows function execution if paused longer than timeSpan. modifier onlyPausedSince(uint timeSpan) { require(paused && timePaused + timeSpan <= block.timestamp); _; } /// @dev Event is fired if paused. event LogPause(); /// @dev Event is fired if pause is ended. event LogUnpause(); /** * @dev Pause contract. No new game sessions can be created. */ function pause() public onlyOwner onlyNotPaused { paused = true; timePaused = block.timestamp; LogPause(); } /** * @dev Unpause contract. */ function unpause() public onlyOwner onlyPaused { paused = false; timePaused = 0; LogUnpause(); } } contract Destroyable is Pausable { /// @dev After pausing the contract for 20 days owner can selfdestruct it. uint public constant TIMEOUT_DESTROY = 20 days; /** * @dev Destroy contract and transfer ether to address _targetAddress. */ function destroy() public onlyOwner onlyPausedSince(TIMEOUT_DESTROY) { selfdestruct(owner); } } contract GameChannelBase is Destroyable, ConflictResolutionManager { /// @dev Different game session states. enum GameStatus { ENDED, ///< @dev Game session is ended. ACTIVE, ///< @dev Game session is active. WAITING_FOR_SERVER, ///< @dev Waiting for server to accept game session. PLAYER_INITIATED_END, ///< @dev Player initiated non regular end. SERVER_INITIATED_END ///< @dev Server initiated non regular end. } /// @dev Reason game session ended. enum ReasonEnded { REGULAR_ENDED, ///< @dev Game session is regularly ended. END_FORCED_BY_SERVER, ///< @dev Player did not respond. Server forced end. END_FORCED_BY_PLAYER, ///< @dev Server did not respond. Player forced end. REJECTED_BY_SERVER, ///< @dev Server rejected game session. CANCELLED_BY_PLAYER ///< @dev Player canceled game session before server accepted it. } struct Game { /// @dev Game session status. GameStatus status; /// @dev Reason game session ended. ReasonEnded reasonEnded; /// @dev Player's stake. uint stake; /// @dev Last game round info if not regularly ended. /// If game session is ended normally this data is not used. uint8 gameType; uint32 roundId; uint16 betNum; uint betValue; int balance; bytes32 playerSeed; bytes32 serverSeed; uint endInitiatedTime; } /// @dev Minimal time span between profit transfer. uint public constant MIN_TRANSFER_TIMESPAN = 1 days; /// @dev Maximal time span between profit transfer. uint public constant MAX_TRANSFER_TIMSPAN = 6 * 30 days; /// @dev Current active game sessions. uint public activeGames = 0; /// @dev Game session id counter. Points to next free game session slot. So gameIdCntr -1 is the // number of game sessions created. uint public gameIdCntr; /// @dev Only this address can accept and end games. address public serverAddress; /// @dev Address to transfer profit to. address public houseAddress; /// @dev Current house stake. uint public houseStake = 0; /// @dev House profit since last profit transfer. int public houseProfit = 0; /// @dev Min value player needs to deposit for creating game session. uint public minStake; /// @dev Max value player can deposit for creating game session. uint public maxStake; /// @dev Timeout until next profit transfer is allowed. uint public profitTransferTimeSpan = 14 days; /// @dev Last time profit transferred to house. uint public lastProfitTransferTimestamp; bytes32 public typeHash; /// @dev Maps gameId to game struct. mapping (uint => Game) public gameIdGame; /// @dev Maps player address to current player game id. mapping (address => uint) public playerGameId; /// @dev Maps player address to pending returns. mapping (address => uint) public pendingReturns; /// @dev Modifier, which only allows to execute if house stake is high enough. modifier onlyValidHouseStake(uint _activeGames) { uint minHouseStake = conflictRes.minHouseStake(_activeGames); require(houseStake >= minHouseStake); _; } /// @dev Modifier to check if value send fulfills player stake requirements. modifier onlyValidValue() { require(minStake <= msg.value && msg.value <= maxStake); _; } /// @dev Modifier, which only allows server to call function. modifier onlyServer() { require(msg.sender == serverAddress); _; } /// @dev Modifier, which only allows to set valid transfer timeouts. modifier onlyValidTransferTimeSpan(uint transferTimeout) { require(transferTimeout >= MIN_TRANSFER_TIMESPAN && transferTimeout <= MAX_TRANSFER_TIMSPAN); _; } /// @dev This event is fired when player creates game session. event LogGameCreated(address indexed player, uint indexed gameId, uint stake, bytes32 endHash); /// @dev This event is fired when server rejects player's game. event LogGameRejected(address indexed player, uint indexed gameId); /// @dev This event is fired when server accepts player's game. event LogGameAccepted(address indexed player, uint indexed gameId, bytes32 endHash); /// @dev This event is fired when player requests conflict end. event LogPlayerRequestedEnd(address indexed player, uint indexed gameId); /// @dev This event is fired when server requests conflict end. event LogServerRequestedEnd(address indexed player, uint indexed gameId); /// @dev This event is fired when game session is ended. event LogGameEnded(address indexed player, uint indexed gameId, ReasonEnded reason); /// @dev this event is fired when owner modifies player's stake limits. event LogStakeLimitsModified(uint minStake, uint maxStake); /** * @dev Contract constructor. * @param _serverAddress Server address. * @param _minStake Min value player needs to deposit to create game session. * @param _maxStake Max value player can deposit to create game session. * @param _conflictResAddress Conflict resolution contract address. * @param _houseAddress House address to move profit to. */ function GameChannelBase( address _serverAddress, uint _minStake, uint _maxStake, address _conflictResAddress, address _houseAddress, uint _gameIdCntr ) public ConflictResolutionManager(_conflictResAddress) { require(_minStake > 0 && _minStake <= _maxStake); require(_gameIdCntr > 0); gameIdCntr = _gameIdCntr; serverAddress = _serverAddress; houseAddress = _houseAddress; lastProfitTransferTimestamp = block.timestamp; minStake = _minStake; maxStake = _maxStake; typeHash = keccak256( "uint32 Round Id", "uint8 Game Type", "uint16 Number", "uint Value (Wei)", "int Current Balance (Wei)", "bytes32 Server Hash", "bytes32 Player Hash", "uint Game Id", "address Contract Address" ); } /** * @notice Withdraw pending returns. */ function withdraw() public { uint toTransfer = pendingReturns[msg.sender]; require(toTransfer > 0); pendingReturns[msg.sender] = 0; msg.sender.transfer(toTransfer); } /** * @notice Transfer house profit to houseAddress. */ function transferProfitToHouse() public { require(lastProfitTransferTimestamp + profitTransferTimeSpan <= block.timestamp); if (houseProfit <= 0) { // update last transfer timestamp lastProfitTransferTimestamp = block.timestamp; return; } // houseProfit is gt 0 => safe to cast uint toTransfer = uint(houseProfit); assert(houseStake >= toTransfer); houseProfit = 0; lastProfitTransferTimestamp = block.timestamp; houseStake = houseStake - toTransfer; houseAddress.transfer(toTransfer); } /** * @dev Set profit transfer time span. */ function setProfitTransferTimeSpan(uint _profitTransferTimeSpan) public onlyOwner onlyValidTransferTimeSpan(_profitTransferTimeSpan) { profitTransferTimeSpan = _profitTransferTimeSpan; } /** * @dev Increase house stake by msg.value */ function addHouseStake() public payable onlyOwner { houseStake += msg.value; } /** * @dev Withdraw house stake. */ function withdrawHouseStake(uint value) public onlyOwner { uint minHouseStake = conflictRes.minHouseStake(activeGames); require(value <= houseStake && houseStake - value >= minHouseStake); require(houseProfit <= 0 || uint(houseProfit) <= houseStake - value); houseStake = houseStake - value; owner.transfer(value); } /** * @dev Withdraw house stake and profit. */ function withdrawAll() public onlyOwner onlyPausedSince(3 days) { houseProfit = 0; uint toTransfer = houseStake; houseStake = 0; owner.transfer(toTransfer); } /** * @dev Set new house address. * @param _houseAddress New house address. */ function setHouseAddress(address _houseAddress) public onlyOwner { houseAddress = _houseAddress; } /** * @dev Set stake min and max value. * @param _minStake Min stake. * @param _maxStake Max stake. */ function setStakeRequirements(uint _minStake, uint _maxStake) public onlyOwner { require(_minStake > 0 && _minStake <= _maxStake); minStake = _minStake; maxStake = _maxStake; LogStakeLimitsModified(minStake, maxStake); } /** * @dev Close game session. * @param _game Game session data. * @param _gameId Id of game session. * @param _playerAddress Player's address of game session. * @param _reason Reason for closing game session. * @param _balance Game session balance. */ function closeGame( Game storage _game, uint _gameId, address _playerAddress, ReasonEnded _reason, int _balance ) internal { _game.status = GameStatus.ENDED; _game.reasonEnded = _reason; _game.balance = _balance; assert(activeGames > 0); activeGames = activeGames - 1; LogGameEnded(_playerAddress, _gameId, _reason); } /** * @dev End game by paying out player and server. * @param _game Game session to payout. * @param _playerAddress Player's address. */ function payOut(Game storage _game, address _playerAddress) internal { assert(_game.balance <= conflictRes.maxBalance()); assert(_game.status == GameStatus.ENDED); assert(_game.stake <= maxStake); assert((int(_game.stake) + _game.balance) >= 0); uint valuePlayer = uint(int(_game.stake) + _game.balance); if (_game.balance > 0 && int(houseStake) < _game.balance) { // Should never happen! // House is bankrupt. // Payout left money. valuePlayer = houseStake; } houseProfit = houseProfit - _game.balance; int newHouseStake = int(houseStake) - _game.balance; assert(newHouseStake >= 0); houseStake = uint(newHouseStake); pendingReturns[_playerAddress] += valuePlayer; if (pendingReturns[_playerAddress] > 0) { safeSend(_playerAddress); } } /** * @dev Send value of pendingReturns[_address] to _address. * @param _address Address to send value to. */ function safeSend(address _address) internal { uint valueToSend = pendingReturns[_address]; assert(valueToSend > 0); pendingReturns[_address] = 0; if (_address.send(valueToSend) == false) { pendingReturns[_address] = valueToSend; } } /** * @dev Verify signature of given data. Throws on verification failure. * @param _sig Signature of given data in the form of rsv. * @param _address Address of signature signer. */ function verifySig( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _serverHash, bytes32 _playerHash, uint _gameId, address _contractAddress, bytes _sig, address _address ) internal view { // check if this is the correct contract address contractAddress = this; require(_contractAddress == contractAddress); bytes32 roundHash = calcHash( _roundId, _gameType, _num, _value, _balance, _serverHash, _playerHash, _gameId, _contractAddress ); verify( roundHash, _sig, _address ); } /** * @dev Calculate typed hash of given data (compare eth_signTypedData). * @return Hash of given data. */ function calcHash( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _serverHash, bytes32 _playerHash, uint _gameId, address _contractAddress ) private view returns(bytes32) { bytes32 dataHash = keccak256( _roundId, _gameType, _num, _value, _balance, _serverHash, _playerHash, _gameId, _contractAddress ); return keccak256(typeHash, dataHash); } /** * @dev Check if _sig is valid signature of _hash. Throws if invalid signature. * @param _hash Hash to check signature of. * @param _sig Signature of _hash. * @param _address Address of signer. */ function verify( bytes32 _hash, bytes _sig, address _address ) private pure { var (r, s, v) = signatureSplit(_sig); address addressRecover = ecrecover(_hash, v, r, s); require(addressRecover == _address); } /** * @dev Split the given signature of the form rsv in r s v. v is incremented with 27 if * it is below 2. * @param _signature Signature to split. * @return r s v */ function signatureSplit(bytes _signature) private pure returns (bytes32 r, bytes32 s, uint8 v) { require(_signature.length == 65); assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := and(mload(add(_signature, 65)), 0xff) } if (v < 2) { v = v + 27; } } } contract GameChannelConflict is GameChannelBase { /** * @dev Contract constructor. * @param _serverAddress Server address. * @param _minStake Min value player needs to deposit to create game session. * @param _maxStake Max value player can deposit to create game session. * @param _conflictResAddress Conflict resolution contract address * @param _houseAddress House address to move profit to */ function GameChannelConflict( address _serverAddress, uint _minStake, uint _maxStake, address _conflictResAddress, address _houseAddress, uint _gameIdCtr ) public GameChannelBase(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _gameIdCtr) { // nothing to do } /** * @dev Used by server if player does not end game session. * @param _roundId Round id of bet. * @param _gameType Game type of bet. * @param _num Number of bet. * @param _value Value of bet. * @param _balance Balance before this bet. * @param _serverHash Hash of server seed for this bet. * @param _playerHash Hash of player seed for this bet. * @param _gameId Game session id. * @param _contractAddress Address of this contract. * @param _playerSig Player signature of this bet. * @param _playerAddress Address of player. * @param _serverSeed Server seed for this bet. * @param _playerSeed Player seed for this bet. */ function serverEndGameConflict( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _serverHash, bytes32 _playerHash, uint _gameId, address _contractAddress, bytes _playerSig, address _playerAddress, bytes32 _serverSeed, bytes32 _playerSeed ) public onlyServer { verifySig( _roundId, _gameType, _num, _value, _balance, _serverHash, _playerHash, _gameId, _contractAddress, _playerSig, _playerAddress ); serverEndGameConflictImpl( _roundId, _gameType, _num, _value, _balance, _serverHash, _playerHash, _serverSeed, _playerSeed, _gameId, _playerAddress ); } /** * @notice Can be used by player if server does not answer to the end game session request. * @param _roundId Round id of bet. * @param _gameType Game type of bet. * @param _num Number of bet. * @param _value Value of bet. * @param _balance Balance before this bet. * @param _serverHash Hash of server seed for this bet. * @param _playerHash Hash of player seed for this bet. * @param _gameId Game session id. * @param _contractAddress Address of this contract. * @param _serverSig Server signature of this bet. * @param _playerSeed Player seed for this bet. */ function playerEndGameConflict( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _serverHash, bytes32 _playerHash, uint _gameId, address _contractAddress, bytes _serverSig, bytes32 _playerSeed ) public { verifySig( _roundId, _gameType, _num, _value, _balance, _serverHash, _playerHash, _gameId, _contractAddress, _serverSig, serverAddress ); playerEndGameConflictImpl( _roundId, _gameType, _num, _value, _balance, _playerHash, _playerSeed, _gameId, msg.sender ); } /** * @notice Cancel active game without playing. Useful if server stops responding before * one game is played. * @param _gameId Game session id. */ function playerCancelActiveGame(uint _gameId) public { address playerAddress = msg.sender; uint gameId = playerGameId[playerAddress]; Game storage game = gameIdGame[gameId]; require(gameId == _gameId); if (game.status == GameStatus.ACTIVE) { game.endInitiatedTime = block.timestamp; game.status = GameStatus.PLAYER_INITIATED_END; LogPlayerRequestedEnd(msg.sender, gameId); } else if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == 0) { closeGame(game, gameId, playerAddress, ReasonEnded.REGULAR_ENDED, 0); payOut(game, playerAddress); } else { revert(); } } /** * @dev Cancel active game without playing. Useful if player starts game session and * does not play. * @param _playerAddress Players' address. * @param _gameId Game session id. */ function serverCancelActiveGame(address _playerAddress, uint _gameId) public onlyServer { uint gameId = playerGameId[_playerAddress]; Game storage game = gameIdGame[gameId]; require(gameId == _gameId); if (game.status == GameStatus.ACTIVE) { game.endInitiatedTime = block.timestamp; game.status = GameStatus.SERVER_INITIATED_END; LogServerRequestedEnd(msg.sender, gameId); } else if (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId == 0) { closeGame(game, gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, 0); payOut(game, _playerAddress); } else { revert(); } } /** * @dev Force end of game if player does not respond. Only possible after a certain period of time * to give the player a chance to respond. * @param _playerAddress Player's address. */ function serverForceGameEnd(address _playerAddress, uint _gameId) public onlyServer { uint gameId = playerGameId[_playerAddress]; Game storage game = gameIdGame[gameId]; require(gameId == _gameId); require(game.status == GameStatus.SERVER_INITIATED_END); // theoretically we have enough data to calculate winner // but as player did not respond assume he has lost. int newBalance = conflictRes.serverForceGameEnd( game.gameType, game.betNum, game.betValue, game.balance, game.stake, game.endInitiatedTime ); closeGame(game, gameId, _playerAddress, ReasonEnded.END_FORCED_BY_SERVER, newBalance); payOut(game, _playerAddress); } /** * @notice Force end of game if server does not respond. Only possible after a certain period of time * to give the server a chance to respond. */ function playerForceGameEnd(uint _gameId) public { address playerAddress = msg.sender; uint gameId = playerGameId[playerAddress]; Game storage game = gameIdGame[gameId]; require(gameId == _gameId); require(game.status == GameStatus.PLAYER_INITIATED_END); int newBalance = conflictRes.playerForceGameEnd( game.gameType, game.betNum, game.betValue, game.balance, game.stake, game.endInitiatedTime ); closeGame(game, gameId, playerAddress, ReasonEnded.END_FORCED_BY_PLAYER, newBalance); payOut(game, playerAddress); } /** * @dev Conflict handling implementation. Stores game data and timestamp if game * is active. If server has already marked conflict for game session the conflict * resolution contract is used (compare conflictRes). * @param _roundId Round id of bet. * @param _gameType Game type of bet. * @param _num Number of bet. * @param _value Value of bet. * @param _balance Balance before this bet. * @param _playerHash Hash of player's seed for this bet. * @param _playerSeed Player's seed for this bet. * @param _gameId game Game session id. * @param _playerAddress Player's address. */ function playerEndGameConflictImpl( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _playerHash, bytes32 _playerSeed, uint _gameId, address _playerAddress ) private { uint gameId = playerGameId[_playerAddress]; Game storage game = gameIdGame[gameId]; int maxBalance = conflictRes.maxBalance(); require(gameId == _gameId); require(_roundId > 0); require(keccak256(_playerSeed) == _playerHash); require(_value <= game.stake); require(-int(game.stake) <= _balance && _balance <= maxBalance); // save to cast as ranges are fixed require(int(game.stake) + _balance - int(_value) >= 0); // save to cast as ranges are fixed require(conflictRes.isValidBet(_gameType, _num, _value)); if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == _roundId) { game.playerSeed = _playerSeed; endGameConflict(game, gameId, _playerAddress); } else if (game.status == GameStatus.ACTIVE || (game.status == GameStatus.SERVER_INITIATED_END && game.roundId < _roundId)) { game.status = GameStatus.PLAYER_INITIATED_END; game.endInitiatedTime = block.timestamp; game.roundId = _roundId; game.gameType = _gameType; game.betNum = _num; game.betValue = _value; game.balance = _balance; game.playerSeed = _playerSeed; game.serverSeed = bytes32(0); LogPlayerRequestedEnd(msg.sender, gameId); } else { revert(); } } /** * @dev Conflict handling implementation. Stores game data and timestamp if game * is active. If player has already marked conflict for game session the conflict * resolution contract is used (compare conflictRes). * @param _roundId Round id of bet. * @param _gameType Game type of bet. * @param _num Number of bet. * @param _value Value of bet. * @param _balance Balance before this bet. * @param _serverHash Hash of server's seed for this bet. * @param _playerHash Hash of player's seed for this bet. * @param _serverSeed Server's seed for this bet. * @param _playerSeed Player's seed for this bet. * @param _playerAddress Player's address. */ function serverEndGameConflictImpl( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _serverHash, bytes32 _playerHash, bytes32 _serverSeed, bytes32 _playerSeed, uint _gameId, address _playerAddress ) private { uint gameId = playerGameId[_playerAddress]; Game storage game = gameIdGame[gameId]; int maxBalance = conflictRes.maxBalance(); require(gameId == _gameId); require(_roundId > 0); require(keccak256(_serverSeed) == _serverHash); require(keccak256(_playerSeed) == _playerHash); require(_value <= game.stake); require(-int(game.stake) <= _balance && _balance <= maxBalance); // save to cast as ranges are fixed require(int(game.stake) + _balance - int(_value) >= 0); // save to cast as ranges are fixed require(conflictRes.isValidBet(_gameType, _num, _value)); if (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId == _roundId) { game.serverSeed = _serverSeed; endGameConflict(game, gameId, _playerAddress); } else if (game.status == GameStatus.ACTIVE || (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId < _roundId)) { game.status = GameStatus.SERVER_INITIATED_END; game.endInitiatedTime = block.timestamp; game.roundId = _roundId; game.gameType = _gameType; game.betNum = _num; game.betValue = _value; game.balance = _balance; game.serverSeed = _serverSeed; game.playerSeed = _playerSeed; LogServerRequestedEnd(_playerAddress, gameId); } else { revert(); } } /** * @dev End conflicting game. * @param _game Game session data. * @param _gameId Game session id. * @param _playerAddress Player's address. */ function endGameConflict(Game storage _game, uint _gameId, address _playerAddress) private { int newBalance = conflictRes.endGameConflict( _game.gameType, _game.betNum, _game.betValue, _game.balance, _game.stake, _game.serverSeed, _game.playerSeed ); closeGame(_game, _gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, newBalance); payOut(_game, _playerAddress); } } contract GameChannel is GameChannelConflict { /** * @dev contract constructor * @param _serverAddress Server address. * @param _minStake Min value player needs to deposit to create game session. * @param _maxStake Max value player can deposit to create game session. * @param _conflictResAddress Conflict resolution contract address. * @param _houseAddress House address to move profit to. */ function GameChannel( address _serverAddress, uint _minStake, uint _maxStake, address _conflictResAddress, address _houseAddress, uint _gameIdCntr ) public GameChannelConflict(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _gameIdCntr) { // nothing to do } /** * @notice Create games session request. msg.value needs to be valid stake value. * @param _endHash Last hash of the hash chain generated by the player. */ function createGame(bytes32 _endHash) public payable onlyValidValue onlyValidHouseStake(activeGames + 1) onlyNotPaused { address playerAddress = msg.sender; uint previousGameId = playerGameId[playerAddress]; Game storage game = gameIdGame[previousGameId]; require(game.status == GameStatus.ENDED); uint gameId = gameIdCntr++; playerGameId[playerAddress] = gameId; Game storage newGame = gameIdGame[gameId]; newGame.stake = msg.value; newGame.status = GameStatus.WAITING_FOR_SERVER; activeGames = activeGames + 1; LogGameCreated(playerAddress, gameId, msg.value, _endHash); } /** * @notice Cancel game session waiting for server acceptance. * @param _gameId Game session id. */ function cancelGame(uint _gameId) public { address playerAddress = msg.sender; uint gameId = playerGameId[playerAddress]; Game storage game = gameIdGame[gameId]; require(gameId == _gameId); require(game.status == GameStatus.WAITING_FOR_SERVER); closeGame(game, gameId, playerAddress, ReasonEnded.CANCELLED_BY_PLAYER, 0); payOut(game, playerAddress); } /** * @dev Called by the server to reject game session created by player with address * _playerAddress. * @param _playerAddress Players's address who created the game session. * @param _gameId Game session id. */ function rejectGame(address _playerAddress, uint _gameId) public onlyServer { uint gameId = playerGameId[_playerAddress]; Game storage game = gameIdGame[gameId]; require(_gameId == gameId); require(game.status == GameStatus.WAITING_FOR_SERVER); closeGame(game, gameId, _playerAddress, ReasonEnded.REJECTED_BY_SERVER, 0); payOut(game, _playerAddress); LogGameRejected(_playerAddress, gameId); } /** * @dev Called by server to accept game session created by player with * address _playerAddress. * @param _playerAddress Player's address who created the game. * @param _gameId Game id of game session. * @param _endHash Last hash of the hash chain generated by the server. */ function acceptGame(address _playerAddress, uint _gameId, bytes32 _endHash) public onlyServer { uint gameId = playerGameId[_playerAddress]; Game storage game = gameIdGame[gameId]; require(_gameId == gameId); require(game.status == GameStatus.WAITING_FOR_SERVER); game.status = GameStatus.ACTIVE; LogGameAccepted(_playerAddress, gameId, _endHash); } /** * @dev Regular end game session. Used if player and house have both * accepted current game session state. * The game session with gameId _gameId is closed * and the player paid out. This functions is called by the server after * the player requested the termination of the current game session. * @param _roundId Round id of bet. * @param _gameType Game type of bet. * @param _num Number of bet. * @param _value Value of bet. * @param _balance Current balance. * @param _serverHash Hash of server's seed for this bet. * @param _playerHash Hash of player's seed for this bet. * @param _gameId Game session id. * @param _contractAddress Address of this contract. * @param _playerAddress Address of player. * @param _playerSig Player's signature of this bet. */ function serverEndGame( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _serverHash, bytes32 _playerHash, uint _gameId, address _contractAddress, address _playerAddress, bytes _playerSig ) public onlyServer { verifySig( _roundId, _gameType, _num, _value, _balance, _serverHash, _playerHash, _gameId, _contractAddress, _playerSig, _playerAddress ); regularEndGame(_playerAddress, _roundId, _gameType, _num, _value, _balance, _gameId, _contractAddress); } /** * @notice Regular end game session. Normally not needed as server ends game (@see serverEndGame). * Can be used by player if server does not end game session. * @param _roundId Round id of bet. * @param _gameType Game type of bet. * @param _num Number of bet. * @param _value Value of bet. * @param _balance Current balance. * @param _serverHash Hash of server's seed for this bet. * @param _playerHash Hash of player's seed for this bet. * @param _gameId Game session id. * @param _contractAddress Address of this contract. * @param _serverSig Server's signature of this bet. */ function playerEndGame( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _serverHash, bytes32 _playerHash, uint _gameId, address _contractAddress, bytes _serverSig ) public { verifySig( _roundId, _gameType, _num, _value, _balance, _serverHash, _playerHash, _gameId, _contractAddress, _serverSig, serverAddress ); regularEndGame(msg.sender, _roundId, _gameType, _num, _value, _balance, _gameId, _contractAddress); } /** * @dev Regular end game session implementation. Used if player and house have both * accepted current game session state. The game session with gameId _gameId is closed * and the player paid out. * @param _playerAddress Address of player. * @param _gameType Game type of bet. * @param _num Number of bet. * @param _value Value of bet. * @param _balance Current balance. * @param _gameId Game session id. * @param _contractAddress Address of this contract. */ function regularEndGame( address _playerAddress, uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, uint _gameId, address _contractAddress ) private { uint gameId = playerGameId[_playerAddress]; Game storage game = gameIdGame[gameId]; address contractAddress = this; int maxBalance = conflictRes.maxBalance(); require(_gameId == gameId); require(_roundId > 0); // save to cast as game.stake hash fixed range require(-int(game.stake) <= _balance && _balance <= maxBalance); require((_gameType == 0) && (_num == 0) && (_value == 0)); require(_contractAddress == contractAddress); require(game.status == GameStatus.ACTIVE); closeGame(game, gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, _balance); payOut(game, _playerAddress); } }
Cancel game session waiting for server acceptance. _gameId Game session id./
function cancelGame(uint _gameId) public { address playerAddress = msg.sender; uint gameId = playerGameId[playerAddress]; Game storage game = gameIdGame[gameId]; require(gameId == _gameId); require(game.status == GameStatus.WAITING_FOR_SERVER); closeGame(game, gameId, playerAddress, ReasonEnded.CANCELLED_BY_PLAYER, 0); payOut(game, playerAddress); }
1,034,158
pragma solidity >=0.4.22 <0.6.0; /** * @title ERC20Basic */ 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); event Burn(address indexed from, uint256 value); event Addpublish(address indexed from, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; address owner; modifier onlyOwner() { require(msg.sender == owner); _; } uint256 public totalSupplyN; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupplyN; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; uint8 public constant decimals = 18; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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'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].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Burn token by Owner. * @param _value The amount of tokens to burn the by Owner. */ function burn(uint256 _value) onlyOwner public { require(totalSupplyN >= _value * 10 ** uint256(decimals)); balances[msg.sender] -= _value * 10 ** uint256(decimals); totalSupplyN -= _value * 10 ** uint256(decimals); emit Burn(msg.sender, _value * 10 ** uint256(decimals)); //emit Transfer(address(this), msg.sender, -(amount * 10 ** uint256(decimals))); } /** * @dev AddPublish token by Owner. * @param _value The amount of tokens to add the by Owner. */ function addPublish(uint256 _value) onlyOwner public { totalSupplyN += _value * 10 ** uint256(decimals); balances[msg.sender] += _value * 10 ** uint256(decimals); emit Addpublish(msg.sender, _value * (10 ** uint256(decimals))); emit Transfer(address(this), msg.sender, (_value * 10 ** uint256(decimals))); } } /** * @title create EPC token */ contract EPC is StandardToken { string public constant name = "epc"; // solium-disable-line uppercase string public constant symbol = "EPC"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase //decided amount of tokens by Owner. constructor ( uint256 _totalSupply ) public { owner = msg.sender; totalSupplyN = _totalSupply * 10 ** uint256(decimals); balances[msg.sender] = totalSupplyN; emit Transfer(address(this), msg.sender, totalSupplyN); } }
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 _spender The address which will spend the funds. _addedValue The amount of tokens to increase the allowance by./
function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
6,044,637
pragma solidity ^0.5.16; // Inheritance import "./Owned.sol"; // Internal references import "./interfaces/IERC20.sol"; import "./interfaces/IStakerStorage.sol"; contract Staker is Owned { // Available assets which can be staked in the system mapping(bytes32 => address) public assets; mapping(address => bytes32) public assetsByAddress; IStakerStorage public stakerStorage; bytes32 public constant CONTRACT_NAME = "Staker"; constructor(address _owner, IStakerStorage _storage) public Owned(_owner) { stakerStorage = _storage; } function getStaked(bytes32 token, address account) external view reutrns (uint) { return stakerStorage.getStaked(token, account); } /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](1); addresses[0] = CONTRACT_NAME; } function getAsset(bytes32 name) external view returns (address) { return assets[name]; } function requireAsset(bytes32 name) external view returns (address) { address assetAddress = assets[name]; require(assetAddress != address(0), 'Staker: Missing Asset Token ')); return assetAddress; } function getAssetByAddress(address assetAddress) external view returns (bytes32) { return assetsByAddress[assetAddress]; } function getAssets(bytes32[] calldata currencyKeys) external view returns (address[] memory) { uint numKeys = currencyKeys.length; address[] memory addresses = new address[](numKeys); for (uint i = 0; i < numKeys; i++) { addresses[i] = assets[currencyKeys[i]]; } return addresses; } /* ========== MUTATIVE FUNCTIONS ========== */ function _addAsset(bytes32 name, address assetAddress) internal { require(assets[name] == address(0), "Asset exists"); require(assetsByAddress[assetAddress] == bytes32(0), "Asset address already exists"); assets[name] = assetAddress; assetsByAddress[assetAddress] = name; emit AssetAdded(name, assetAddress); } function addAsset(bytes32 name, address assetAddress) external onlyOwner { _addAsset(name, assetAddress); } function _removeAsset(bytes32 name) internal { address assetAddress = assets[name]; require(assetAddress != address(0), "Synth does not exist"); // require(IERC20(assetAddress).totalSupply() == 0, "asset supply exists"); // And remove it from the mapping delete assetsByAddress[assetAddress]; delete assets[name]; emit AssetRemoved(name, assetAddress); } function removeAsset(bytes32 name) external onlyOwner { _removeAsset(name); } /* ========== EVENTS ========== */ event AssetAdded(bytes32 name, address assetAddress); event AssetRemoved(bytes32 name, address assetAddress); }
require(IERC20(assetAddress).totalSupply() == 0, "asset supply exists"); And remove it from the mapping
function _removeAsset(bytes32 name) internal { address assetAddress = assets[name]; require(assetAddress != address(0), "Synth does not exist"); delete assetsByAddress[assetAddress]; delete assets[name]; emit AssetRemoved(name, assetAddress); }
12,587,127
./full_match/1/0xAAf570aAB5B578D84441E9269d2953B5b2759b4a/sources/contracts/VitalFusion.sol
Minting functionality for the contract owner. Owner mint with no checks other than those included in _internalMint()
function ownerMint(uint256 quantity) external onlyOwner nonReentrant { _internalMint(msg.sender, quantity); }
4,977,791
./full_match/5/0x52cbE67E81C61549Dc7115CE1A26D39Ef39f0793/sources/contracts/IMasStaking1155Upgradeable.sol
Withdraw logic. Override to add custom logic.
function _withdraw(uint256 _tokenId, uint256 _amount) internal virtual { uint256 _amountStaked = stakers[_tokenId][_stakeMsgSender()].amountStaked; require(_amount != 0, "Withdrawing 0 tokens"); require(_amountStaked >= _amount, "Withdrawing more than staked"); _updateUnclaimedIMasRewardsForStaker(_tokenId, _stakeMsgSender()); _updateUnclaimedIMasXRewardsForStaker(_tokenId, _stakeMsgSender()); if (_amountStaked == _amount) { address[] memory _stakersArray = stakersArray[_tokenId]; for (uint256 i = 0; i < _stakersArray.length; ++i) { if (_stakersArray[i] == _stakeMsgSender()) { stakersArray[_tokenId][i] = _stakersArray[_stakersArray.length - 1]; stakersArray[_tokenId].pop(); break; } } } stakers[_tokenId][_stakeMsgSender()].amountStaked -= _amount; IERC1155(stakingToken).safeTransferFrom(address(this), _stakeMsgSender(), _tokenId, _amount, ""); emit TokensWithdrawn(_stakeMsgSender(), _tokenId, _amount); }
7,047,556
// File: @openzeppelin/contracts/math/Math.sol pragma solidity 0.5.17; library Math { function MAX311(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN896(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE467(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity 0.5.17; library SafeMath { function ADD124(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB912(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB912(a, b, "SafeMath: subtraction overflow"); } function SUB912(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 MUL612(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 DIV645(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV645(a, b, "SafeMath: division by zero"); } function DIV645(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 MOD528(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD528(a, b, "SafeMath: modulo by zero"); } function MOD528(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity 0.5.17; 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 _MSGSENDER219() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA337() 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; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity 0.5.17; contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED705(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER219(); emit OWNERSHIPTRANSFERRED705(address(0), _owner); } function OWNER858() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER527() { //inject NONSTANDARD NAMING require(ISOWNER429(), "Ownable: caller is not the owner"); _; } function ISOWNER429() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER219() == _owner; } function RENOUNCEOWNERSHIP633() public ONLYOWNER527 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED705(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP10(address newOwner) public ONLYOWNER527 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP120(newOwner); } function _TRANSFEROWNERSHIP120(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED705(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity 0.5.17; interface IERC20 { function TOTALSUPPLY2() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF265(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER164(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function MINT263(address account, uint amount) external; //inject NONSTANDARD NAMING function BURN805(uint amount) external; //inject NONSTANDARD NAMING function ALLOWANCE538(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE42(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM15(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function MINTERS951(address account) external view returns (bool); //inject NONSTANDARD NAMING event TRANSFER380(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL481(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity 0.5.17; library Address { function ISCONTRACT794(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly {codehash := extcodehash(account)} return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE864(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE732(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success,) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity 0.5.17; library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER450(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.TRANSFER164.selector, to, value)); } function SAFETRANSFERFROM145(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.TRANSFERFROM15.selector, from, to, value)); } function SAFEAPPROVE302(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE538(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, value)); } function SAFEINCREASEALLOWANCE445(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE538(address(this), spender).ADD124(value); CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE538(address(this), spender).SUB912(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN337(token, abi.encodeWithSelector(token.APPROVE42.selector, spender, newAllowance)); } function CALLOPTIONALRETURN337(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT794(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) {// Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/IRewardDistributionRecipient.sol pragma solidity 0.5.17; contract IRewardDistributionRecipient is Ownable { address public rewardReferral; function NOTIFYREWARDAMOUNT832(uint256 reward) external; //inject NONSTANDARD NAMING function SETREWARDREFERRAL334(address _rewardReferral) external ONLYOWNER527 { //inject NONSTANDARD NAMING rewardReferral = _rewardReferral; } } // File: contracts/CurveRewards.sol pragma solidity 0.5.17; contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; IERC20 public yfv = IERC20(0x45f24BaEef268BB6d63AEe5129015d69702BCDfa); uint256 private _totalSupply; mapping(address => uint256) private _balances; function TOTALSUPPLY2() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF265(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TOKENSTAKE952(uint256 amount, uint256 actualStakeAmount) internal { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.ADD124(actualStakeAmount); _balances[msg.sender] = _balances[msg.sender].ADD124(actualStakeAmount); yfv.SAFETRANSFERFROM145(msg.sender, address(this), amount); } function TOKENSTAKEONBEHALF333(address stakeFor, uint256 amount, uint256 actualStakeAmount) internal { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.ADD124(actualStakeAmount); _balances[stakeFor] = _balances[stakeFor].ADD124(actualStakeAmount); yfv.SAFETRANSFERFROM145(msg.sender, address(this), amount); } function TOKENWITHDRAW537(uint256 amount, uint256 actualWithdrawAmount) internal { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.SUB912(amount); _balances[msg.sender] = _balances[msg.sender].SUB912(amount); yfv.SAFETRANSFER450(msg.sender, actualWithdrawAmount); } } interface IYFVReferral { function SETREFERRER414(address farmer, address referrer) external; //inject NONSTANDARD NAMING function GETREFERRER855(address farmer) external view returns (address); //inject NONSTANDARD NAMING } contract YFVStakeV2 is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public vUSD = IERC20(0x1B8E12F839BD4e73A47adDF76cF7F0097d74c14C); IERC20 public vETH = IERC20(0x76A034e76Aa835363056dd418611E4f81870f16e); uint256 public vETH_REWARD_FRACTION_RATE = 1000; uint256 public constant duration178 = 7 days; //inject NONSTANDARD NAMING uint8 public constant number_epochs944 = 38; //inject NONSTANDARD NAMING uint256 public constant referral_commission_percent277 = 1; //inject NONSTANDARD NAMING uint256 public currentEpochReward = 0; uint256 public totalAccumulatedReward = 0; uint8 public currentEpoch = 0; uint256 public starttime = 1598968800; // Tuesday, September 1, 2020 2:00:00 PM (GMT+0) uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public constant default_epoch_reward278 = 230000 * (10 ** 9); // 230,000 vUSD (and 230 vETH) //inject NONSTANDARD NAMING uint256 public constant total_reward44 = default_epoch_reward278 * number_epochs944; // 8,740,000 vUSD (and 8,740 vETH) //inject NONSTANDARD NAMING uint256 public epochReward = default_epoch_reward278; uint256 public minStakingAmount = 90 ether; uint256 public unstakingFrozenTime = 40 hours; // ** DISABLED AT BEGINNING - WILL SET IT BY GOVERNANCE AFTER VIP-1.1 // ** unlockWithdrawFee = 0.1%: stakers will need to pay 0.1% (sent to insurance fund)of amount they want to withdraw if the coin still frozen // ** lowStakeDepositFee = 0.1%: stakers still can stake with low amount but need to pay 0.1% (sent to insurance fund) // specially, if lowStakeDepositFee = 10000 -> low amount stakers will not pay anything (richmen pay tax, not poormen) // ** highStakeDepositFee = 0.1%: stakers need to pay 0.1% of extra amount more than 90 YFV (sent to insurance fund) uint256 public lowStakeDepositFee = 0; // per ten thousand (eg. 15 -> 0.15%) uint256 public highStakeDepositFee = 0; // per ten thousand (eg. 15 -> 0.15%) uint256 public unlockWithdrawFee = 0; // per ten thousand (eg. 15 -> 0.15%) address public yfvInsuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public lastStakeTimes; mapping(address => uint256) public accumulatedStakingPower; // will accumulate every time staker does getReward() mapping(address => bool) public whitelistedPools; // for stake on behalf event REWARDADDED885(uint256 reward); //inject NONSTANDARD NAMING event YFVREWARDADDED261(uint256 reward); //inject NONSTANDARD NAMING event BURNED28(uint256 reward); //inject NONSTANDARD NAMING event STAKED939(address indexed user, uint256 amount, uint256 actualStakeAmount); //inject NONSTANDARD NAMING event WITHDRAWN649(address indexed user, uint256 amount, uint256 actualWithdrawAmount); //inject NONSTANDARD NAMING event REWARDPAID896(address indexed user, uint256 reward); //inject NONSTANDARD NAMING event COMMISSIONPAID234(address indexed user, uint256 reward); //inject NONSTANDARD NAMING constructor() public { whitelistedPools[0x62a9fE913eb596C8faC0936fd2F51064022ba22e] = true; // BAL Pool whitelistedPools[0x70b83A7f5E83B3698d136887253E0bf426C9A117] = true; // YFI Pool whitelistedPools[0x1c990fC37F399C935625b815975D0c9fAD5C31A1] = true; // BAT Pool whitelistedPools[0x752037bfEf024Bd2669227BF9068cb22840174B0] = true; // REN Pool whitelistedPools[0x9b74774f55C0351fD064CfdfFd35dB002C433092] = true; // KNC Pool whitelistedPools[0xFBDE07329FFc9Ec1b70f639ad388B94532b5E063] = true; // BTC Pool whitelistedPools[0x67FfB615EAEb8aA88fF37cCa6A32e322286a42bb] = true; // ETH Pool whitelistedPools[0x196CF719251579cBc850dED0e47e972b3d7810Cd] = true; // LINK Pool whitelistedPools[msg.sender] = true; // to be able to stakeOnBehalf farmer who have stucked fund in Pool Stake v1. } function ADDWHITELISTEDPOOL116(address _addressPool) public ONLYOWNER527 { //inject NONSTANDARD NAMING whitelistedPools[_addressPool] = true; } function REMOVEWHITELISTEDPOOL972(address _addressPool) public ONLYOWNER527 { //inject NONSTANDARD NAMING whitelistedPools[_addressPool] = false; } function SETYFVINSURANCEFUND27(address _yfvInsuranceFund) public ONLYOWNER527 { //inject NONSTANDARD NAMING yfvInsuranceFund = _yfvInsuranceFund; } function SETEPOCHREWARD899(uint256 _epochReward) public ONLYOWNER527 { //inject NONSTANDARD NAMING require(_epochReward <= default_epoch_reward278 * 10, "Insane big _epochReward!"); // At most 10x only epochReward = _epochReward; } function SETMINSTAKINGAMOUNT151(uint256 _minStakingAmount) public ONLYOWNER527 { //inject NONSTANDARD NAMING minStakingAmount = _minStakingAmount; } function SETUNSTAKINGFROZENTIME482(uint256 _unstakingFrozenTime) public ONLYOWNER527 { //inject NONSTANDARD NAMING unstakingFrozenTime = _unstakingFrozenTime; } function SETSTAKEDEPOSITFEE451(uint256 _lowStakeDepositFee, uint256 _highStakeDepositFee) public ONLYOWNER527 { //inject NONSTANDARD NAMING require(_lowStakeDepositFee <= 100 || _lowStakeDepositFee == 10000, "Dont be too greedy"); // <= 1% OR set to 10000 to disable low stake fee require(_highStakeDepositFee <= 100, "Dont be too greedy"); // <= 1% lowStakeDepositFee = _lowStakeDepositFee; highStakeDepositFee = _highStakeDepositFee; } function SETUNLOCKWITHDRAWFEE126(uint256 _unlockWithdrawFee) public ONLYOWNER527 { //inject NONSTANDARD NAMING require(_unlockWithdrawFee <= 1000, "Dont be too greedy"); // <= 10% unlockWithdrawFee = _unlockWithdrawFee; } // To upgrade vUSD contract (v1 is still experimental, we may need vUSDv2 with rebase() function working soon - then governance will call this upgrade) function UPGRADEVUSDCONTRACT293(address _vUSDContract) public ONLYOWNER527 { //inject NONSTANDARD NAMING vUSD = IERC20(_vUSDContract); } // To upgrade vETH contract (v1 is still experimental, we may need vETHv2 with rebase() function working soon - then governance will call this upgrade) function UPGRADEVETHCONTRACT116(address _vETHContract) public ONLYOWNER527 { //inject NONSTANDARD NAMING vETH = IERC20(_vETHContract); } modifier UPDATEREWARD641(address account) { //inject NONSTANDARD NAMING rewardPerTokenStored = REWARDPERTOKEN11(); lastUpdateTime = LASTTIMEREWARDAPPLICABLE544(); if (account != address(0)) { rewards[account] = EARNED432(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function LASTTIMEREWARDAPPLICABLE544() public view returns (uint256) { //inject NONSTANDARD NAMING return Math.MIN896(block.timestamp, periodFinish); } function REWARDPERTOKEN11() public view returns (uint256) { //inject NONSTANDARD NAMING if (TOTALSUPPLY2() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.ADD124( LASTTIMEREWARDAPPLICABLE544() .SUB912(lastUpdateTime) .MUL612(rewardRate) .MUL612(1e18) .DIV645(TOTALSUPPLY2()) ); } // vUSD balance function EARNED432(address account) public view returns (uint256) { //inject NONSTANDARD NAMING uint256 calculatedEarned = BALANCEOF265(account) .MUL612(REWARDPERTOKEN11().SUB912(userRewardPerTokenPaid[account])) .DIV645(1e18) .ADD124(rewards[account]); uint256 poolBalance = vUSD.BALANCEOF265(address(this)); // some rare case the reward can be slightly bigger than real number, we need to check against how much we have left in pool if (calculatedEarned > poolBalance) return poolBalance; return calculatedEarned; } function STAKINGPOWER96(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return accumulatedStakingPower[account].ADD124(EARNED432(account)); } function VETHBALANCE317(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return EARNED432(account).DIV645(vETH_REWARD_FRACTION_RATE); } function STAKE230(uint256 amount, address referrer) public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING require(amount >= 1 szabo, "Do not stake dust"); require(referrer != msg.sender, "You cannot refer yourself."); uint256 actualStakeAmount = amount; uint256 depositFee = 0; if (minStakingAmount > 0) { if (amount < minStakingAmount && lowStakeDepositFee < 10000) { // if amount is less than minStakingAmount and lowStakeDepositFee is not disabled // if governance does not allow low stake if (lowStakeDepositFee == 0) require(amount >= minStakingAmount, "Cannot stake below minStakingAmount"); // otherwise depositFee will be calculated based on the rate else depositFee = amount.MUL612(lowStakeDepositFee).DIV645(10000); } else if (amount > minStakingAmount && highStakeDepositFee > 0) { // if amount is greater than minStakingAmount and governance decides richman to pay tax (of the extra amount) depositFee = amount.SUB912(minStakingAmount).MUL612(highStakeDepositFee).DIV645(10000); } if (depositFee > 0) { actualStakeAmount = amount.SUB912(depositFee); } } super.TOKENSTAKE952(amount, actualStakeAmount); lastStakeTimes[msg.sender] = block.timestamp; emit STAKED939(msg.sender, amount, actualStakeAmount); if (depositFee > 0) { if (yfvInsuranceFund != address(0)) { // send fee to insurance yfv.SAFETRANSFER450(yfvInsuranceFund, depositFee); emit REWARDPAID896(yfvInsuranceFund, depositFee); } else { // or burn yfv.BURN805(depositFee); emit BURNED28(depositFee); } } if (rewardReferral != address(0) && referrer != address(0)) { IYFVReferral(rewardReferral).SETREFERRER414(msg.sender, referrer); } } function STAKEONBEHALF204(address stakeFor, uint256 amount) public UPDATEREWARD641(stakeFor) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING require(amount >= 1 szabo, "Do not stake dust"); require(whitelistedPools[msg.sender], "Sorry hackers, you should stay away from us (YFV community signed)"); uint256 actualStakeAmount = amount; uint256 depositFee = 0; if (minStakingAmount > 0) { if (amount < minStakingAmount && lowStakeDepositFee < 10000) { // if amount is less than minStakingAmount and lowStakeDepositFee is not disabled // if governance does not allow low stake if (lowStakeDepositFee == 0) require(amount >= minStakingAmount, "Cannot stake below minStakingAmount"); // otherwise depositFee will be calculated based on the rate else depositFee = amount.MUL612(lowStakeDepositFee).DIV645(10000); } else if (amount > minStakingAmount && highStakeDepositFee > 0) { // if amount is greater than minStakingAmount and governance decides richman to pay tax (of the extra amount) depositFee = amount.SUB912(minStakingAmount).MUL612(highStakeDepositFee).DIV645(10000); } if (depositFee > 0) { actualStakeAmount = amount.SUB912(depositFee); } } super.TOKENSTAKEONBEHALF333(stakeFor, amount, actualStakeAmount); lastStakeTimes[stakeFor] = block.timestamp; emit STAKED939(stakeFor, amount, actualStakeAmount); if (depositFee > 0) { actualStakeAmount = amount.SUB912(depositFee); if (yfvInsuranceFund != address(0)) { // send fee to insurance yfv.SAFETRANSFER450(yfvInsuranceFund, depositFee); emit REWARDPAID896(yfvInsuranceFund, depositFee); } else { // or burn yfv.BURN805(depositFee); emit BURNED28(depositFee); } } } function UNFROZENSTAKETIME568(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return lastStakeTimes[account] + unstakingFrozenTime; } function WITHDRAW21(uint256 amount) public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING require(amount > 0, "Cannot withdraw 0"); uint256 actualWithdrawAmount = amount; if (block.timestamp < UNFROZENSTAKETIME568(msg.sender)) { // if coin is still frozen and governance does not allow stakers to unstake before timer ends if (unlockWithdrawFee == 0) revert("Coin is still frozen"); // otherwise withdrawFee will be calculated based on the rate uint256 withdrawFee = amount.MUL612(unlockWithdrawFee).DIV645(10000); actualWithdrawAmount = amount.SUB912(withdrawFee); if (yfvInsuranceFund != address(0)) { // send fee to insurance yfv.SAFETRANSFER450(yfvInsuranceFund, withdrawFee); emit REWARDPAID896(yfvInsuranceFund, withdrawFee); } else { // or burn yfv.BURN805(withdrawFee); emit BURNED28(withdrawFee); } } super.TOKENWITHDRAW537(amount, actualWithdrawAmount); emit WITHDRAWN649(msg.sender, amount, actualWithdrawAmount); } function EXIT848() external { //inject NONSTANDARD NAMING WITHDRAW21(BALANCEOF265(msg.sender)); GETREWARD938(); } function GETREWARD938() public UPDATEREWARD641(msg.sender) CHECKNEXTEPOCH825 { //inject NONSTANDARD NAMING uint256 reward = rewards[msg.sender]; if (reward > 0) { accumulatedStakingPower[msg.sender] = accumulatedStakingPower[msg.sender].ADD124(rewards[msg.sender]); rewards[msg.sender] = 0; vUSD.SAFETRANSFER450(msg.sender, reward); vETH.SAFETRANSFER450(msg.sender, reward.DIV645(vETH_REWARD_FRACTION_RATE)); emit REWARDPAID896(msg.sender, reward); } } modifier CHECKNEXTEPOCH825() { //inject NONSTANDARD NAMING require(periodFinish > 0, "Pool has not started"); if (block.timestamp >= periodFinish) { currentEpochReward = epochReward; if (totalAccumulatedReward.ADD124(currentEpochReward) > total_reward44) { currentEpochReward = total_reward44.SUB912(totalAccumulatedReward); // limit total reward } if (currentEpochReward > 0) { if (!vUSD.MINTERS951(address(this)) || !vETH.MINTERS951(address(this))) { currentEpochReward = 0; } else { vUSD.MINT263(address(this), currentEpochReward); vETH.MINT263(address(this), currentEpochReward.DIV645(vETH_REWARD_FRACTION_RATE)); totalAccumulatedReward = totalAccumulatedReward.ADD124(currentEpochReward); } currentEpoch++; } rewardRate = currentEpochReward.DIV645(duration178); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.ADD124(duration178); emit REWARDADDED885(currentEpochReward); } _; } // Start the pool with reward amount for this epoch function NOTIFYREWARDAMOUNT832(uint256 reward) external ONLYOWNER527 UPDATEREWARD641(address(0)) { //inject NONSTANDARD NAMING require(periodFinish == 0, "Only can call once to start staking"); currentEpochReward = reward; if (totalAccumulatedReward.ADD124(currentEpochReward) > total_reward44) { currentEpochReward = total_reward44.SUB912(totalAccumulatedReward); // limit total reward } lastUpdateTime = block.timestamp; if (block.timestamp < starttime) { // epoch zero periodFinish = starttime; rewardRate = reward.DIV645(periodFinish.SUB912(block.timestamp)); } else { // 1st epoch periodFinish = lastUpdateTime.ADD124(duration178); rewardRate = reward.DIV645(duration178); currentEpoch++; } vUSD.MINT263(address(this), reward); vETH.MINT263(address(this), reward.DIV645(vETH_REWARD_FRACTION_RATE)); totalAccumulatedReward = totalAccumulatedReward.ADD124(reward); emit REWARDADDED885(reward); } // This function allows governance to take unsupported tokens out of the contract, since this pool exists longer than the other pools. // This is in an effort to make someone whole, should they seriously mess up. // There is no guarantee governance will vote to return these. // It also allows for removal of airdropped tokens. function GOVERNANCERECOVERUNSUPPORTED727(IERC20 _token, uint256 amount, address to) external { //inject NONSTANDARD NAMING // only gov require(msg.sender == OWNER858(), "!governance"); // cant take staked asset require(_token != yfv, "yfv"); // cant take reward asset require(_token != vUSD, "vUSD"); require(_token != vETH, "vETH"); // transfer to _token.SAFETRANSFER450(to, amount); } }
inject NONSTANDARD NAMING
function MOD528(uint256 a, uint256 b) internal pure returns (uint256) {
7,225,371
pragma solidity ^0.4.21; // File: deploy/contracts/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error. * Note, the div and mul methods were removed as they are not currently needed */ library SafeMath { 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; } } // File: deploy/contracts/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; string public name; string public symbol; uint8 public decimals; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: deploy/contracts/Stampable.sol contract Stampable is ERC20 { using SafeMath for uint256; // A struct that represents a particular token balance struct TokenBalance { uint256 amount; uint index; } // A struct that represents a particular address balance struct AddressBalance { mapping (uint256 => TokenBalance) tokens; uint256[] tokenIndex; } // A mapping of address to balances mapping (address => AddressBalance) balances; // The total number of tokens owned per address mapping (address => uint256) ownershipCount; // Whitelist for addresses allowed to stamp tokens mapping (address => bool) public stampingWhitelist; /** * Modifier for only whitelisted addresses */ modifier onlyStampingWhitelisted() { require(stampingWhitelist[msg.sender]); _; } // Event for token stamping event TokenStamp (address indexed from, uint256 tokenStamped, uint256 stamp, uint256 amt); /** * @dev Function to stamp a token in the msg.sender's wallet * @param _tokenToStamp uint256 The tokenId of theirs to stamp (0 for unstamped tokens) * @param _stamp uint256 The new stamp to apply * @param _amt uint256 The quantity of tokens to stamp */ function stampToken (uint256 _tokenToStamp, uint256 _stamp, uint256 _amt) onlyStampingWhitelisted public returns (bool) { require(_amt <= balances[msg.sender].tokens[_tokenToStamp].amount); // Subtract balance of 0th token ID _amt value. removeToken(msg.sender, _tokenToStamp, _amt); // "Stamp" the token addToken(msg.sender, _stamp, _amt); // Emit the stamping event emit TokenStamp(msg.sender, _tokenToStamp, _stamp, _amt); return true; } function addToken(address _owner, uint256 _token, uint256 _amount) internal { // If they don't yet have any, assign this token an index if (balances[_owner].tokens[_token].amount == 0) { balances[_owner].tokens[_token].index = balances[_owner].tokenIndex.push(_token) - 1; } // Increase their balance of said token balances[_owner].tokens[_token].amount = balances[_owner].tokens[_token].amount.add(_amount); // Increase their ownership count ownershipCount[_owner] = ownershipCount[_owner].add(_amount); } function removeToken(address _owner, uint256 _token, uint256 _amount) internal { // Decrease their ownership count ownershipCount[_owner] = ownershipCount[_owner].sub(_amount); // Decrease their balance of the token balances[_owner].tokens[_token].amount = balances[_owner].tokens[_token].amount.sub(_amount); // If they don't have any left, remove it if (balances[_owner].tokens[_token].amount == 0) { uint index = balances[_owner].tokens[_token].index; uint256 lastCoin = balances[_owner].tokenIndex[balances[_owner].tokenIndex.length - 1]; balances[_owner].tokenIndex[index] = lastCoin; balances[_owner].tokens[lastCoin].index = index; balances[_owner].tokenIndex.length--; // Make sure the user's token is removed delete balances[_owner].tokens[_token]; } } } // File: deploy/contracts/FanCoin.sol contract FanCoin is Stampable { using SafeMath for uint256; // The owner of this token address public owner; // Keeps track of allowances for particular address. - ERC20 Method mapping (address => mapping (address => uint256)) public allowed; event TokenTransfer (address indexed from, address indexed to, uint256 tokenId, uint256 value); event MintTransfer (address indexed from, address indexed to, uint256 originalTokenId, uint256 tokenId, uint256 value); modifier onlyOwner { require(msg.sender == owner); _; } /** * The constructor for the FanCoin token */ function FanCoin() public { owner = 0x7DDf115B8eEf3058944A3373025FB507efFAD012; name = "FanChain"; symbol = "FANZ"; decimals = 4; // Total supply is one billion tokens totalSupply = 6e8 * uint256(10) ** decimals; // Add the owner to the stamping whitelist stampingWhitelist[owner] = true; // Initially give all of the tokens to the owner addToken(owner, 0, totalSupply); } /** ERC 20 * @dev Retrieves the balance of a specified address * @param _owner address The address to query the balance of. * @return A uint256 representing the amount owned by the _owner */ function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipCount[_owner]; } /** * @dev Retrieves the balance of a specified address for a specific token * @param _owner address The address to query the balance of * @param _tokenId uint256 The token being queried * @return A uint256 representing the amount owned by the _owner */ function balanceOfToken(address _owner, uint256 _tokenId) public view returns (uint256 balance) { return balances[_owner].tokens[_tokenId].amount; } /** * @dev Returns all of the tokens owned by a particular address * @param _owner address The address to query * @return A uint256 array representing the tokens owned */ function tokensOwned(address _owner) public view returns (uint256[] tokens) { return balances[_owner].tokenIndex; } /** ERC 20 * @dev Transfers tokens to a specific address * @param _to address The address to transfer tokens to * @param _value unit256 The amount to be transferred */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= totalSupply); require(_value <= ownershipCount[msg.sender]); // Cast the value as the ERC20 standard uses uint256 uint256 _tokensToTransfer = uint256(_value); // Do the transfer require(transferAny(msg.sender, _to, _tokensToTransfer)); // Notify that a transfer has occurred emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer a specific kind of token to another address * @param _to address The address to transfer to * @param _tokenId address The type of token to transfer * @param _value uint256 The number of tokens to transfer */ function transferToken(address _to, uint256 _tokenId, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender].tokens[_tokenId].amount); // Do the transfer internalTransfer(msg.sender, _to, _tokenId, _value); // Notify that a transfer happened emit TokenTransfer(msg.sender, _to, _tokenId, _value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer a list of token kinds and values to another address * @param _to address The address to transfer to * @param _tokenIds uint256[] The list of tokens to transfer * @param _values uint256[] The list of amounts to transfer */ function transferTokens(address _to, uint256[] _tokenIds, uint256[] _values) public returns (bool) { require(_to != address(0)); require(_tokenIds.length == _values.length); require(_tokenIds.length < 100); // Arbitrary limit // Do verification first for (uint i = 0; i < _tokenIds.length; i++) { require(_values[i] > 0); require(_values[i] <= balances[msg.sender].tokens[_tokenIds[i]].amount); } // Transfer every type of token specified for (i = 0; i < _tokenIds.length; i++) { require(internalTransfer(msg.sender, _to, _tokenIds[i], _values[i])); emit TokenTransfer(msg.sender, _to, _tokenIds[i], _values[i]); emit Transfer(msg.sender, _to, _values[i]); } return true; } /** * @dev Transfers the given number of tokens regardless of how they are stamped * @param _from address The address to transfer from * @param _to address The address to transfer to * @param _value uint256 The number of tokens to send */ function transferAny(address _from, address _to, uint256 _value) private returns (bool) { // Iterate through all of the tokens owned, and transfer either the // current balance of that token, or the remaining total amount to be // transferred (`_value`), whichever is smaller. Because tokens are completely removed // as their balances reach 0, we just run the loop until we have transferred all // of the tokens we need to uint256 _tokensToTransfer = _value; while (_tokensToTransfer > 0) { uint256 tokenId = balances[_from].tokenIndex[0]; uint256 tokenBalance = balances[_from].tokens[tokenId].amount; if (tokenBalance >= _tokensToTransfer) { require(internalTransfer(_from, _to, tokenId, _tokensToTransfer)); _tokensToTransfer = 0; } else { _tokensToTransfer = _tokensToTransfer - tokenBalance; require(internalTransfer(_from, _to, tokenId, tokenBalance)); } } return true; } /** * Internal function for transferring a specific type of token */ function internalTransfer(address _from, address _to, uint256 _tokenId, uint256 _value) private returns (bool) { // Decrease the amount being sent first removeToken(_from, _tokenId, _value); // Increase receivers token balances addToken(_to, _tokenId, _value); return true; } /** ERC 20 * @dev Transfer on behalf of another address * @param _from address The address to send tokens from * @param _to address The address to send tokens 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 <= ownershipCount[_from]); require(_value <= allowed[_from][msg.sender]); // Get the uint256 version of value uint256 _castValue = uint256(_value); // Decrease the spending limit allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Actually perform the transfer require(transferAny(_from, _to, _castValue)); // Notify that a transfer has occurred emit Transfer(_from, _to, _value); return true; } /** * @dev Transfer and stamp tokens from a mint in one step * @param _to address To send the tokens to * @param _tokenToStamp uint256 The token to stamp (0 is unstamped tokens) * @param _stamp uint256 The new stamp to apply * @param _amount uint256 The number of tokens to stamp and transfer */ function mintTransfer(address _to, uint256 _tokenToStamp, uint256 _stamp, uint256 _amount) public onlyStampingWhitelisted returns (bool) { require(_to != address(0)); require(_amount <= balances[msg.sender].tokens[_tokenToStamp].amount); // Decrease the amount being sent first removeToken(msg.sender, _tokenToStamp, _amount); // Increase receivers token balances addToken(_to, _stamp, _amount); emit MintTransfer(msg.sender, _to, _tokenToStamp, _stamp, _amount); emit Transfer(msg.sender, _to, _amount); return true; } /** * @dev Add an address to the whitelist * @param _addr address The address to add */ function addToWhitelist(address _addr) public onlyOwner { stampingWhitelist[_addr] = true; } /** * @dev Remove an address from the whitelist * @param _addr address The address to remove */ function removeFromWhitelist(address _addr) public onlyOwner { stampingWhitelist[_addr] = false; } /** ERC 20 * @dev Approve sent address to spend the specified amount of tokens on * behalf of msg.sender * * See https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * for any potential security concerns * * @param _spender address The address that will spend funds * @param _value uint256 The number of tokens they are allowed to spend */ function approve(address _spender, uint256 _value) public returns (bool) { require(allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** ERC 20 * @dev Returns the amount a spender is allowed to spend for a particular * address * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds. * @return uint256 The number of tokens still available for the spender */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** ERC 20 * @dev Increases the number of tokens a spender is allowed to spend for * `msg.sender` * @param _spender address The address of the spender * @param _addedValue uint256 The amount to increase the spenders approval by */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** ERC 20 * @dev Decreases the number of tokens a spender is allowed to spend for * `msg.sender` * @param _spender address The address of the spender * @param _subtractedValue uint256 The amount to decrease the spenders approval by */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) { uint _value = allowed[msg.sender][_spender]; if (_subtractedValue > _value) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = _value.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
ERC 20 Retrieves the balance of a specified address _owner address The address to query the balance of. return A uint256 representing the amount owned by the _owner/
function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipCount[_owner]; }
5,505,119
// join us at https://t.me/FuckPeyote0 // SPDX-License-Identifier: MIT pragma solidity 0.8.11; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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 marketing 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 marketing 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 marketing 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); } 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); } 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _createInitialSupply(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() external virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IDexRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } interface IDexFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } contract FuckPeyote is ERC20, Ownable { uint256 public maxBuyAmount; uint256 public maxSellAmount; uint256 public maxWalletAmount; IDexRouter public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; uint256 public swapTokensAtAmount; address public marketingsAddress; address public buybackAddress; uint256 public tradingActiveBlock = 0; // 0 means trading is not active bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buymarketingsFee; uint256 public buyLiquidityFee; uint256 public buybuybackFee; uint256 public sellTotalFees; uint256 public sellmarketingsFee; uint256 public sellLiquidityFee; uint256 public sellbuybackFee; uint256 public tokensFormarketings; uint256 public tokensForLiquidity; uint256 public tokensForbuyback; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event EnabledTrading(); event RemovedLimits(); event ExcludeFromFees(address indexed account, bool isExcluded); event UpdatedMaxBuyAmount(uint256 newAmount); event UpdatedMaxSellAmount(uint256 newAmount); event UpdatedMaxWalletAmount(uint256 newAmount); event UpdatedmarketingsAddress(address indexed newWallet); event UpdatedbuybackAddress(address indexed newWallet); event MaxTransactionExclusion(address _address, bool excluded); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event TransferForeignToken(address token, uint256 amount); constructor() ERC20("fuck", "Peyote") { address newOwner = msg.sender; // can leave alone if owner is deployer. IDexRouter _uniswapV2Router = IDexRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); _excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IDexFactory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 totalSupply = 100 * 1e9 * 1e18; maxBuyAmount = totalSupply * 1 / 1000; maxSellAmount = totalSupply * 1 / 1000; maxWalletAmount = totalSupply * 3 / 1000; swapTokensAtAmount = totalSupply * 25 / 100000; // 0.025% swap amount buymarketingsFee = 3; buyLiquidityFee = 0; buybuybackFee = 0; buyTotalFees = buymarketingsFee + buyLiquidityFee + buybuybackFee; sellmarketingsFee = 5; sellLiquidityFee = 0; sellbuybackFee = 0; sellTotalFees = sellmarketingsFee + sellLiquidityFee + sellbuybackFee; _excludeFromMaxTransaction(newOwner, true); _excludeFromMaxTransaction(address(this), true); _excludeFromMaxTransaction(address(0xdead), true); excludeFromFees(newOwner, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); marketingsAddress = address(newOwner); buybackAddress = address(newOwner); _createInitialSupply(newOwner, totalSupply); transferOwnership(newOwner); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { require(!tradingActive, "Cannot reenable trading"); tradingActive = true; swapEnabled = true; tradingActiveBlock = block.number; emit EnabledTrading(); } // remove limits after token is stable function removeLimits() external onlyOwner { limitsInEffect = false; transferDelayEnabled = false; emit RemovedLimits(); } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner { transferDelayEnabled = false; } function updateMaxBuyAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set max buy amount lower than 0.1%"); maxBuyAmount = newNum * (10**18); emit UpdatedMaxBuyAmount(maxBuyAmount); } function updateMaxSellAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set max sell amount lower than 0.1%"); maxSellAmount = newNum * (10**18); emit UpdatedMaxSellAmount(maxSellAmount); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 3 / 1000)/1e18, "Cannot set max wallet amount lower than 0.3%"); maxWalletAmount = newNum * (10**18); emit UpdatedMaxWalletAmount(maxWalletAmount); } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner { require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 1 / 1000, "Swap amount cannot be higher than 0.1% total supply."); swapTokensAtAmount = newAmount; } function _excludeFromMaxTransaction(address updAds, bool isExcluded) private { _isExcludedMaxTransactionAmount[updAds] = isExcluded; emit MaxTransactionExclusion(updAds, isExcluded); } function airdropToWallets(address[] memory wallets, uint256[] memory amountsInTokens) external onlyOwner { require(wallets.length == amountsInTokens.length, "arrays must be the same length"); require(wallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input. for(uint256 i = 0; i < wallets.length; i++){ address wallet = wallets[i]; uint256 amount = amountsInTokens[i]*1e18; _transfer(msg.sender, wallet, amount); } } function excludeFromMaxTransaction(address updAds, bool isEx) external onlyOwner { if(!isEx){ require(updAds != uniswapV2Pair, "Cannot remove uniswap pair from max txn"); } _isExcludedMaxTransactionAmount[updAds] = isEx; } function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _excludeFromMaxTransaction(pair, value); emit SetAutomatedMarketMakerPair(pair, value); } function updateBuyFees(uint256 _marketingsFee, uint256 _liquidityFee, uint256 _buybackFee) external onlyOwner { buymarketingsFee = _marketingsFee; buyLiquidityFee = _liquidityFee; buybuybackFee = _buybackFee; buyTotalFees = buymarketingsFee + buyLiquidityFee + buybuybackFee; require(buyTotalFees <= 15, "Must keep fees at 15% or less"); } function updateSellFees(uint256 _marketingsFee, uint256 _liquidityFee, uint256 _buybackFee) external onlyOwner { sellmarketingsFee = _marketingsFee; sellLiquidityFee = _liquidityFee; sellbuybackFee = _buybackFee; sellTotalFees = sellmarketingsFee + sellLiquidityFee + sellbuybackFee; require(sellTotalFees <= 20, "Must keep fees at 20% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead)){ if(!tradingActive){ require(_isExcludedMaxTransactionAmount[from] || _isExcludedMaxTransactionAmount[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 4 && _holderLastTransferTimestamp[to] < block.number - 4, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to] && !_isExcludedMaxTransactionAmount[from]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; uint256 penaltyAmount = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // bot/sniper penalty. Tokens get transferred to marketing wallet to allow potential refund. if(tradingActiveBlock >= block.number + 1 && automatedMarketMakerPairs[from]){ penaltyAmount = amount * 99 / 100; super._transfer(from, marketingsAddress, penaltyAmount); } // on sell else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees /100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensFormarketings += fees * sellmarketingsFee / sellTotalFees; tokensForbuyback += fees * sellbuybackFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensFormarketings += fees * buymarketingsFee / buyTotalFees; tokensForbuyback += fees * buybuybackFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees + penaltyAmount; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(0xdead), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensFormarketings + tokensForbuyback; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 10){ contractBalance = swapTokensAtAmount * 10; } bool success; // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; swapTokensForEth(contractBalance - liquidityTokens); uint256 ethBalance = address(this).balance; uint256 ethForLiquidity = ethBalance; uint256 ethFormarketings = ethBalance * tokensFormarketings / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForbuyback = ethBalance * tokensForbuyback / (totalTokensToSwap - (tokensForLiquidity/2)); ethForLiquidity -= ethFormarketings + ethForbuyback; tokensForLiquidity = 0; tokensFormarketings = 0; tokensForbuyback = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); } (success,) = address(buybackAddress).call{value: ethForbuyback}(""); (success,) = address(marketingsAddress).call{value: address(this).balance}(""); } function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } // withdraw ETH if stuck or someone sends to the address function withdrawStuckETH() external onlyOwner { bool success; (success,) = address(msg.sender).call{value: address(this).balance}(""); } function setmarketingsAddress(address _marketingsAddress) external onlyOwner { require(_marketingsAddress != address(0), "_marketingsAddress address cannot be 0"); marketingsAddress = payable(_marketingsAddress); emit UpdatedmarketingsAddress(_marketingsAddress); } function setbuybackAddress(address _buybackAddress) external onlyOwner { require(_buybackAddress != address(0), "_buybackAddress address cannot be 0"); buybackAddress = payable(_buybackAddress); emit UpdatedbuybackAddress(_buybackAddress); } }
remove limits after token is stable
function removeLimits() external onlyOwner { limitsInEffect = false; transferDelayEnabled = false; emit RemovedLimits(); }
1,176,983
./full_match/5/0xbF9E0d1eBAc85a0FAF0D100fe687bB61f3b5DbB8/sources/_thirdweb-dev/contracts/extension/Drop.sol
Lets a contract admin set claim conditions. Gas refunds (as much as possible) If `_resetClaimEligibility == true`, we assign completely new UIDs to the claim conditions in `_conditions`. So, we delete claim conditions with UID < `newStartIndex`. If `_resetClaimEligibility == false`, and there are more existing claim conditions than in `_conditions`, we delete the existing claim conditions that don't get replaced by the conditions in `_conditions`./
function setClaimConditions(ClaimCondition[] calldata _conditions, bool _resetClaimEligibility) external virtual override { if (!_canSetClaimConditions()) { revert Drop__NotAuthorized(); } uint256 existingStartIndex = claimCondition.currentStartId; uint256 existingPhaseCount = claimCondition.count; if (_resetClaimEligibility) { newStartIndex = existingStartIndex + existingPhaseCount; } claimCondition.count = _conditions.length; claimCondition.currentStartId = newStartIndex; uint256 lastConditionStartTimestamp; for (uint256 i = 0; i < _conditions.length; i++) { require(i == 0 || lastConditionStartTimestamp < _conditions[i].startTimestamp, "ST"); uint256 supplyClaimedAlready = claimCondition.conditions[newStartIndex + i].supplyClaimed; if (supplyClaimedAlready > _conditions[i].maxClaimableSupply) { revert Drop__MaxSupplyClaimedAlready(supplyClaimedAlready); } claimCondition.conditions[newStartIndex + i] = _conditions[i]; claimCondition.conditions[newStartIndex + i].supplyClaimed = supplyClaimedAlready; lastConditionStartTimestamp = _conditions[i].startTimestamp; } if (_resetClaimEligibility) { for (uint256 i = existingStartIndex; i < newStartIndex; i++) { delete claimCondition.conditions[i]; delete claimCondition.usedAllowlistSpot[i]; } if (existingPhaseCount > _conditions.length) { for (uint256 i = _conditions.length; i < existingPhaseCount; i++) { delete claimCondition.conditions[newStartIndex + i]; delete claimCondition.usedAllowlistSpot[newStartIndex + i]; } } } emit ClaimConditionsUpdated(_conditions, _resetClaimEligibility); }
1,909,348
./full_match/5/0xB929FB558477031Fc283942EE9B11Dc80b622CE1/sources/contracts/Akasha.sol
remove flashcard from user's flashcards
function removeFlashcardFromRecord(uint256 _recordId, string memory _question) public { require(bytes(flashcards[_recordId][msg.sender][_question]).length > 0, "Flashcard does not exist"); delete flashcards[_recordId][msg.sender][_question]; for (uint256 i = 0; i < questions[_recordId][msg.sender].length; i++) { if (keccak256(abi.encodePacked(questions[_recordId][msg.sender][i])) == keccak256(abi.encodePacked(_question))) { questions[_recordId][msg.sender][i] = questions[_recordId][msg.sender][questions[_recordId][msg.sender].length - 1]; questions[_recordId][msg.sender].pop(); break; } } emit FlashcardRemoved(msg.sender, _question, block.timestamp, _recordId); for (uint256 i = 0; i < questions[_recordId][msg.sender].length; i++) { if (keccak256(abi.encodePacked(questions[_recordId][msg.sender][i])) == keccak256(abi.encodePacked(_question))) { questions[_recordId][msg.sender][i] = questions[_recordId][msg.sender][questions[_recordId][msg.sender].length - 1]; questions[_recordId][msg.sender].pop(); break; } } emit FlashcardRemoved(msg.sender, _question, block.timestamp, _recordId); }
1,864,462
./full_match/1/0x66d97FD4DefEcD79904B3D3587dC4f8ed66Cf4Ab/sources/src/lib/LSSVMPairCloner.sol
Checks if a contract is a clone of a LSSVMPairETH. Only checks the runtime bytecode, does not check the extra data. factory the factory that deployed the clone implementation the LSSVMPairETH implementation contract query the contract to check return result True if the contract is a clone, false otherwise/ solhint-disable-next-line no-inline-assembly compare expected bytecode with that of the queried contract
function isERC721ETHPairClone(address factory, address implementation, address query) internal view returns (bool result) { assembly { let ptr := mload(0x40) mstore(ptr, hex"3d3d3d3d363d3d37605160353639366051013d73000000000000000000000000") mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), hex"5af43d3d93803e603357fd5bf300000000000000000000000000000000000000") mstore(add(ptr, 0x35), shl(0x60, factory)) let other := add(ptr, 0x49) extcodecopy(query, other, 0, 0x49) result := and( eq(mload(ptr), mload(other)), and( eq(mload(add(ptr, 0x20)), mload(add(other, 0x20))), eq(mload(add(ptr, 0x29)), mload(add(other, 0x29))) ) ) } }
8,298,133
//***********************************EthVentures v4**************************************************************************** // // TIRED OF POINTLESS PONZI SCHEMES? Then join EthVentures the first decentralized company! // // // EthVentures is the first decentralized ethereum based company, with shareholder function, dividends, and more...! // // // How it works: You deposit minimum 2 Ether and no maximum deposit, and you will become a shareholder, proportional to how much you deposited. You will own a % of the income of this dapp proportional to how much you deposited. // Ex: There is 98 Eth deposited, you deposit 2 Eth, new balance becomes 100 Eth, then you will own 2% of the profits! // // // // Dividends: Every deposit under 2 Eth is considered a dividend and is distributed between shareholders automatically. Even if the profit is bigger than 2 Eth, it will be distributed in 1-2 Ether packages, automatically. // Ex: We generate 100 Eth profit daily, then it will be distributed in 50 times in 2 ether packages, then those packages get shared between shareholders. With the example above if you hold 2%, then you will earn 50 times 0.04 Eth, which is 2 Eth profit in total. // // // Profit: This contract itself is not generating any profit, it's just a ledger to keep record of investors, and pays out dividends automatically.There will be other contracts linked to this, that will send the profits here. EthVentures is just the core of this business, there will be other contracts built on it. // Ex: A dice game built on this contract that generates say 10 Eth daily, will send the fees directly here // Ex: A doubler game built on this contract that generates 50 Eth daily, that will send all fees here // Ex: Any other form of contract that takes a % fee, and will send the fees directly here to be distributed between EthVentures shareholders. // // // How to invest: Just deposit minimum 2 Ether to the contract address, and you can see your total investments and % ownership in the Mist wallet if you follow this contract. You can deposit multiple times too, the total investments will add up if you send from the same address. The percentage ownership is calculated with a 10 billionth point precision, so you must divide that number by 100,000,000 to get the % ownership rate. Every other information, can be seen in the contract tab from your Mist Wallet, just make sure you are subscribed to this contract. // // // // Fees: There is a 1% deposit fee, and a 1% dividend payout fee that goes to the contract manager, everything else goes to investors! // //============================================================================================================================ // // When EthVentures will be succesful, it will have tens or hundreds of different contracts, all sending the fees here to our investors, AUTOMATICALLY. It could generate even hundreds of Eth daily at some point. // // Imagine it as a decentralized web of income, all sending the money to 1 single point, this contract. // // It is literally a DECENTRALIZED MONEY GENERATOR! // // //============================================================================================================================ // Copyright (c) 2016 to "BetGod" from Bitcointalk.org, This piece of code cannot be copied or reused without the author's permission! // // Author: https://bitcointalk.org/index.php?action=profile;u=803185 // // This is v4 of the contract, new and improved, all possible bugs fixed! // // //***********************************START contract EthVentures4 { struct InvestorArray { address etherAddress; uint amount; uint percentage_ownership; //ten-billionth point precision, to get real %, just divide this number by 100,000,000 } InvestorArray[] public investors; //********************************************PUBLIC VARIABLES uint public total_investors=0; uint public fees=0; uint public balance = 0; uint public totaldeposited=0; uint public totalpaidout=0; uint public totaldividends=0; string public Message_To_Investors="Welcome to EthVentures4! New and improved! All bugs fixed!"; // the manager can send short messages to investors address public owner; // manager privilege modifier manager { if (msg.sender == owner) _ } //********************************************INIT function EthVentures4() { owner = msg.sender; } //********************************************TRIGGER function() { Enter(); } //********************************************ENTER function Enter() { //DIVIDEND PAYOUT FUNCTION, IT WILL GET INCOME FROM OTHER CONTRACTS, THE DIVIDENDS WILL ALWAYS BE SENT //IN LESS THAN 2 ETHER SIZE PACKETS, BECAUSE ANY DEPOSIT OVER 2 ETHER GETS REGISTERED AS AN INVESTOR!!! if (msg.value < 2 ether) { uint PRE_payout; uint PRE_amount=msg.value; owner.send(PRE_amount/100); //send the 1% management fee to the manager totalpaidout+=PRE_amount/100; //update paid out amount PRE_amount-=PRE_amount/100; //remaining 99% is the dividend //Distribute Dividends if(investors.length !=0 && PRE_amount !=0) { for(uint PRE_i=0; PRE_i<investors.length;PRE_i++) { PRE_payout = PRE_amount * investors[PRE_i].percentage_ownership /10000000000; //calculate pay out investors[PRE_i].etherAddress.send(PRE_payout); //send dividend to investor totalpaidout += PRE_payout; //update paid out amount totaldividends+=PRE_payout; // update paid out dividends } Message_To_Investors="Dividends have been paid out!"; } } // YOU MUST INVEST AT LEAST 2 ETHER OR HIGHER TO BE A SHAREHOLDER, OTHERWISE THE DEPOSIT IS CONSIDERED A DIVIDEND!!! else { // collect management fees and update contract balance and deposited amount uint amount=msg.value; fees = amount / 100; // 1% management fee to the owner totaldeposited+=amount; //update deposited amount amount-=amount/100; balance += amount; // balance update // add a new participant to the system and calculate total players bool alreadyinvestor =false; uint alreadyinvestor_id; //go through all investors and see if the current investor was already an investor or not for(uint i=0; i<investors.length;i++) { if( msg.sender== investors[i].etherAddress) // if yes then: { alreadyinvestor=true; //set it to true alreadyinvestor_id=i; // and save the id of the investor in the investor array break; // get out of the loop to save gas, because we already found it } } // if it's a new investor then add it to the array if(alreadyinvestor==false) { total_investors=investors.length+1; investors.length += 1; //increment first investors[investors.length-1].etherAddress = msg.sender; investors[investors.length-1].amount = amount; investors[investors.length-1].percentage_ownership = amount /totaldeposited*10000000000; Message_To_Investors="New Investor has joined us!"; // a new and real investor has joined us for(uint k=0; k<investors.length;k++) //if smaller than incremented, goes into loop {investors[k].percentage_ownership = investors[k].amount/totaldeposited*10000000000;} //recalculate % ownership } else // if its already an investor, then update his investments and his % ownership { investors[alreadyinvestor_id].amount += amount; investors[alreadyinvestor_id].percentage_ownership = investors[alreadyinvestor_id].amount/totaldeposited*10000000000; } // pay out the 1% management fee if (fees != 0) { owner.send(fees); //send the 1% to the manager totalpaidout+=fees; //update paid out amount } } } //********************************************NEW MANAGER //In case the business gets sold, the new manager will take over the management function NewOwner(address new_owner) manager { owner = new_owner; Message_To_Investors="The contract has a new manager!"; } //********************************************EMERGENCY WITHDRAW // It will only be used in case the funds get stuck or any bug gets discovered in the future // Also if a new version of this contract comes out, the funds then will be transferred to the new one function Emergency() manager { if(balance!=0) { owner.send(balance); balance=0; Message_To_Investors="Emergency Withdraw has been issued!"; } } //********************************************NEW MESSAGE //The manager can send short messages to investors to keep them updated function NewMessage(string new_sms) manager { Message_To_Investors = new_sms; } //********************************************MANUALLY ADD INVESTORS //The manager can add manually the investors from the previous versions, //so that those that invested in the older versions can join us in the new and updated versions function NewManualInvestor(address new_investor , uint new_amount) manager { totaldeposited+=new_amount; //update deposited amount manually total_investors=investors.length+1; investors.length += 1; //increment first investors[investors.length-1].etherAddress = new_investor; investors[investors.length-1].amount = new_amount; investors[investors.length-1].percentage_ownership = new_amount /totaldeposited*10000000000; Message_To_Investors="New manual Investor has been added by the Manager!"; // you can see if the newest investor was manually added or not, this will add transparency to the contract, since this function should only be used in emergency situations. // This will ensure that the manager doesn't add fake investors of his own addresses. } //********************************************MANUAL DEPOSIT //The manager can deposit manually from previous version's balances function ManualDeposit() manager { Message_To_Investors = "Manual Deposit received from the Manager"; } //end }
TRIGGER
function() { Enter(); }
13,011,428
pragma solidity ^0.4.13; library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } contract ERC20Token { /// @return total amount of tokens function totalSupply() constant returns (uint256) {} /// @return The balance function balanceOf(address) constant returns (uint256) {} /// @notice send `_value` token to `_to` from `msg.sender` function transfer(address, uint256) returns (bool) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` function transferFrom(address, address, uint256) returns (bool) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens function approve(address, uint256) returns (bool) {} function allowance(address, address) constant returns (uint256) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is ERC20Token { function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). require(_to != 0x0); if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; revert();} } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract GlobalTechToken is StandardToken { string public name; uint8 public decimals; string public symbol; function GlobalTechToken(){ balances[msg.sender] = 230000000000000000000000000; // Give the creator all initial tokens totalSupply = 230000000000000000000000000; // Update total supply name = "Global Tech Token"; // Set the name for display purposes decimals = 18; // Amount of decimals for display purposes symbol = "GTH"; // Set the symbol for display purposes } }
return The balance
function balanceOf(address) constant returns (uint256) {}
1,557,236
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Tradable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./utils/IERC20.sol"; contract UniqGenerator is ERC721Tradable{ // ----- VARIABLES ----- // uint256 internal _verificationPrice; address internal _tokenForPaying; string public METADATA_PROVENANCE_HASH; uint256 public immutable ROYALTY_FEE; string internal _token_uri; mapping(bytes32 => bool) internal _isItemMinted; mapping(uint256 => bytes32) internal _hashOf; mapping(bytes32 => address) internal _verificationRequester; uint256 internal _tokenNumber; address internal _claimingAddress; // ----- MODIFIERS ----- // modifier notZeroAddress(address a) { require(a != address(0), "ZERO address can not be used"); _; } constructor( address _proxyRegistryAddress, string memory _name, string memory _symbol, uint256 _verfifyPrice, address _tokenERC20, string memory _ttokenUri ) notZeroAddress(_proxyRegistryAddress) ERC721Tradable(_name, _symbol, _proxyRegistryAddress) { ROYALTY_FEE = 750000; //7.5% _verificationPrice = _verfifyPrice; _tokenForPaying = _tokenERC20; _token_uri = _ttokenUri; } function getMessageHash(address _requester, bytes32 _itemHash) public pure returns (bytes32) { return keccak256(abi.encodePacked(_requester, _itemHash)); } function burn(uint256 _tokenId) external { if (msg.sender != _claimingAddress) { require( _isApprovedOrOwner(msg.sender, _tokenId), "Ownership or approval required" ); } _burn(_tokenId); } function getEthSignedMessageHash(bytes32 _messageHash) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", _messageHash ) ); } function verifySignature( address _requester, bytes32 _itemHash, bytes memory _signature ) internal view returns (bool) { bytes32 messageHash = getMessageHash(_requester, _itemHash); bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); return recoverSigner(ethSignedMessageHash, _signature) == owner(); } function recoverSigner( bytes32 _ethSignedMessageHash, bytes memory _signature ) internal pure returns (address) { require(_signature.length == 65, "invalid signature length"); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } return ecrecover(_ethSignedMessageHash, v, r, s); } function isMintedForHash(bytes32 _itemHash) external view returns (bool) { return _isItemMinted[_itemHash]; } function hashOf(uint256 _id) external view returns (bytes32) { return _hashOf[_id]; } function royaltyInfo(uint256) external view returns (address receiver, uint256 amount) { return (owner(), ROYALTY_FEE); } function tokensOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function verificationRequester(bytes32 _itemHash) external view returns (address) { return _verificationRequester[_itemHash]; } function getClaimerAddress() external view returns (address) { return _claimingAddress; } function getVerificationPrice() external view returns (uint256) { return _verificationPrice; } function baseTokenURI() override public view returns (string memory) { return _token_uri; } function contractURI() public pure returns (string memory) { return "https://uniqly.com/api/nft-generator/"; } // ----- PUBLIC METHODS ----- // function payForVerification(bytes32 _itemHash) external { require(!_isItemMinted[_itemHash], "Already minted"); require( _verificationRequester[_itemHash] == address(0), "Verification already requested" ); require( IERC20(_tokenForPaying).transferFrom( msg.sender, address(this), _verificationPrice ) ); _verificationRequester[_itemHash] = msg.sender; } function mintVerified(bytes32 _itemHash, bytes memory _signature) external { require( _verificationRequester[_itemHash] == msg.sender, "Verification Requester mismatch" ); require(!_isItemMinted[_itemHash], "Already minted"); require( verifySignature(msg.sender, _itemHash, _signature), "Signature mismatch" ); _isItemMinted[_itemHash] = true; _safeMint(msg.sender, _tokenNumber); _hashOf[_tokenNumber] = _itemHash; _tokenNumber++; } // ----- OWNERS METHODS ----- // function setProvenanceHash(string memory _hash) external onlyOwner { METADATA_PROVENANCE_HASH = _hash; } function editTokenUri(string memory _ttokenUri) external onlyOwner{ _token_uri = _ttokenUri; } function setTokenAddress(address _newAddress) external onlyOwner { _tokenForPaying = _newAddress; } function editVireficationPrice(uint256 _newPrice) external onlyOwner { _verificationPrice = _newPrice; } function editClaimingAdress(address _newAddress) external onlyOwner { _claimingAddress = _newAddress; } function recoverERC20(address token) external onlyOwner { uint256 val = IERC20(token).balanceOf(address(this)); require(val > 0, "Nothing to recover"); // use interface that not return value (USDT case) Ierc20(token).transfer(owner(), val); } function receivedRoyalties( address, address _buyer, uint256 _tokenId, address _tokenPaid, uint256 _amount ) external { emit ReceivedRoyalties(owner(), _buyer, _tokenId, _tokenPaid, _amount); } event ReceivedRoyalties( address indexed _royaltyRecipient, address indexed _buyer, uint256 indexed _tokenId, address _tokenPaid, uint256 _amount ); } interface Ierc20 { function transfer(address, uint256) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./common/meta-transactions/ContentMixin.sol"; import "./common/meta-transactions/NativeMetaTransaction.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } /** * @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() virtual public view returns (string memory); function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * 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(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {EIP712Base} from "./EIP712Base.sol"; 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 ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Initializable} from "./Initializable.sol"; 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) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // 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 "../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: 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; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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 String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // 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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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; } } }
use interface that not return value (USDT case)
function recoverERC20(address token) external onlyOwner { uint256 val = IERC20(token).balanceOf(address(this)); require(val > 0, "Nothing to recover"); Ierc20(token).transfer(owner(), val); }
331,027
/** *Submitted for verification at Etherscan.io on 2022-04-11 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /////////////////////////////////////////////////////////////////////////// // __/| // __//// /| This smart contract is part of Mover infrastructure // |// //_/// https://viamover.com // |_/ // [email protected] // |/ /////////////////////////////////////////////////////////////////////////// /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } /** * @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); } /** * @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); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // Interface to represent stakeable asset pool interactions interface IMoverUBTStakePoolV2 { function getBaseAsset() external view returns(address); // deposit/withdraw (stake/unstake) function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function getDepositBalance(address account) external view returns(uint256); function borrowToStake(uint256 amount) external returns (uint256); function returnInvested(uint256 amount) external; // yield realization (increases staker's balances proportionally) function harvestYield(uint256 amount) external; } // Interface to represent asset pool interactions interface IUBTStakingNode { // total amount of funds in base asset (UBT) that is possible to reclaim from this Staking Node function reclaimAmount() external view returns(uint256); // callable only by a UBTStakerPool, retrieve a portion of staked UBT, return (just in case) amount transferred function reclaimFunds(uint256 amount) external; } /* Mover UniBright staking contract - allows users to stake their UBT token - would be used as aggregated UBT stake in baseledger */ contract MoverUBTStakePoolV2 is AccessControlUpgradeable, IMoverUBTStakePoolV2 { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; // role that grants most of financial operations for HolyPool bytes32 public constant FINMGMT_ROLE = keccak256("FINMGMT_ROLE"); // emergency transfer (timelocked) variables and events event EmergencyTransferSet( address indexed token, address indexed destination, uint256 amount ); event EmergencyTransferExecute( address indexed token, address indexed destination, uint256 amount ); address private emergencyTransferToken; address private emergencyTransferDestination; uint256 private emergencyTransferTimestamp; uint256 private emergencyTransferAmount; // address of ERC20 base asset (expected to be stablecoin) address public baseAsset; // total amount of assets in baseToken (baseToken balance of HolyPool + collateral valuation in baseToken) uint256 public totalAssetAmount; // total number of pool shares uint256 public totalShareAmount; // user balances (this is NOT UBT, but portion in shares) mapping(address => uint256) public shares; event Deposit(address indexed account, uint256 amount); event Withdraw( address indexed account, uint256 amount ); event YieldRealized(uint256 amount); bool depositsEnabled; uint256 public profitFee; address public feeHolder; // for simple yield stats calculations uint256 public inceptionTimestamp; // inception timestamp function initialize(address _baseAsset) public initializer { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(FINMGMT_ROLE, _msgSender()); baseAsset = _baseAsset; // pool has virtual 0.01 unit of base asset to avoid // division by zero and reasonable starting share value calculation // UBT has 8 decimal points, so small 1e6 as a starting point should be enough totalShareAmount = 1e6; totalAssetAmount = 1e6; depositsEnabled = true; profitFee = 0; inceptionTimestamp = block.timestamp; } function getBaseAsset() public view override returns (address) { return baseAsset; } function getDepositBalance(address _beneficiary) public override view returns (uint256) { return shares[_beneficiary].mul(baseAssetPerShare()).div(1e18); } function baseAssetPerShare() public view returns (uint256) { return totalAssetAmount.mul(1e18).div(totalShareAmount); } // Deposit/withdraw functions function setDepositsEnabled(bool _enabled) public { require(hasRole(FINMGMT_ROLE, msg.sender), "finmgmt only"); depositsEnabled = _enabled; } // deposit process when funds have already been transferred (should be in the same transaction) function deposit(uint256 _amount) public override { require(depositsEnabled, "deposits disabled"); // transfer base asset tokens and calculate shares deposited IERC20Upgradeable(baseAsset).safeTransferFrom(msg.sender, address(this), _amount); // compiler optimization should wrap these local vars automatically uint256 assetPerShare = baseAssetPerShare(); uint256 sharesToDeposit = _amount.mul(1e18).div(assetPerShare); totalShareAmount = totalShareAmount.add(sharesToDeposit); totalAssetAmount = totalAssetAmount.add(_amount); shares[msg.sender] = shares[msg.sender].add(sharesToDeposit); emit Deposit(msg.sender, _amount); } // withdraw funds from pool // amount is presented in base asset quantity function withdraw(uint256 _amount) public override { uint256 sharesAvailable = shares[msg.sender]; uint256 assetPerShare = baseAssetPerShare(); uint256 assetsAvailable = sharesAvailable.mul(assetPerShare).div(1e18); require(_amount <= assetsAvailable, "requested amount exceeds balance"); // NOTE: currently all staked funds should reside on this contract, no reclaim mechanics needed uint256 currentBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this)); if (currentBalance >= _amount) { performWithdraw(msg.sender, _amount); return; } uint256 amountToReclaim = _amount.sub(currentBalance); uint256 reclaimedFunds = retrieveFunds(amountToReclaim); require(reclaimedFunds >= amountToReclaim, "cannot reclaim funds"); performWithdraw(msg.sender, _amount); } function performWithdraw( address _beneficiary, uint256 _amount ) internal { // amount of shares to withdraw to equal _amountActual of baseAsset requested uint256 sharesToWithdraw = _amount.mul(1e18).div(baseAssetPerShare()); // we checked this regarding base asset (UBT) amount, just in case check for share amount require( sharesToWithdraw <= shares[_beneficiary], "requested pool share exceeded" ); // transfer tokens to transfer proxy IERC20Upgradeable(baseAsset).safeTransfer(_beneficiary, _amount); // only perform this after all other withdraw flow complete to recalculate pool state shares[_beneficiary] = shares[_beneficiary].sub(sharesToWithdraw); totalShareAmount = totalShareAmount.sub(sharesToWithdraw); totalAssetAmount = totalAssetAmount.sub(_amount); emit Withdraw(_beneficiary, _amount); } // Yield realization (intended to be called by HolyRedeemer) function harvestYield(uint256 _amountYield) public override { // transfer _amountYield of baseAsset from caller IERC20Upgradeable(baseAsset).safeTransferFrom( msg.sender, address(this), _amountYield ); uint256 amountFee = _amountYield.mul(profitFee).div(1e18); if (amountFee > 0 && feeHolder != address(0)) { IERC20Upgradeable(baseAsset).transfer(feeHolder, amountFee); _amountYield = _amountYield.sub(amountFee); } // increase share price (indirectly, shares quantity remains same, but baseAsset quantity increases) totalAssetAmount = totalAssetAmount.add(_amountYield); // emit event emit YieldRealized(_amountYield); } function setFeeHolderAddress(address _address) public { require(hasRole(FINMGMT_ROLE, msg.sender), "finmgmt only"); feeHolder = _address; } function setProfitFee(uint256 _fee) public { require(hasRole(FINMGMT_ROLE, msg.sender), "finmgmt only"); require(_fee <= 1e18, "fee >1.0"); profitFee = _fee; } // This is oversimplified, no compounding and averaged across timespan from inception // TODO: daily, weekly, monthly, yearly APY // at inception pool share equals 1 (1e18) (specified in initializer) function getDailyAPY() public view returns (uint256) { uint256 secondsFromInception = block.timestamp.sub(inceptionTimestamp); return baseAssetPerShare() .sub(1e18) .mul(100) // substract starting share/baseAsset value 1.0 (1e18) and multiply by 100 to get percent value .mul(86400) .div(secondsFromInception); // fractional representation of how many days passed } // emergencyTransferTimelockSet is for safety (if some tokens got stuck) // in the future it could be removed, to restrict access to user funds // this is timelocked as contract can have user funds function emergencyTransferTimelockSet( address _token, address _destination, uint256 _amount ) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); emergencyTransferTimestamp = block.timestamp; emergencyTransferToken = _token; emergencyTransferDestination = _destination; emergencyTransferAmount = _amount; emit EmergencyTransferSet(_token, _destination, _amount); } function emergencyTransferExecute() public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); require( block.timestamp > emergencyTransferTimestamp + 24 * 3600, "timelock too early" ); require( block.timestamp < emergencyTransferTimestamp + 72 * 3600, "timelock too late" ); IERC20Upgradeable(emergencyTransferToken).safeTransfer( emergencyTransferDestination, emergencyTransferAmount ); emit EmergencyTransferExecute( emergencyTransferToken, emergencyTransferDestination, emergencyTransferAmount ); // clear emergency transfer timelock data emergencyTransferTimestamp = 0; emergencyTransferToken = address(0); emergencyTransferDestination = address(0); emergencyTransferAmount = 0; } /////////////////////////////////////////////////////////////////////////// // V2 upgrade: single validator node stake management/rebalancing support /////////////////////////////////////////////////////////////////////////// IUBTStakingNode[] public stakeNodeContracts; mapping(address => uint256) public stakeNodeContractsStatuses; event UBTStaked(address indexed stakeNodeContract, uint256 amount); event UBTUnstaked(address indexed stakeNodeContract, uint256 amount); event UBTReclaimed(address indexed stakeNodeContract, uint256 amount); // Staking Node contract management functions function addStakingNode(address _address) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); stakeNodeContracts.push(IUBTStakingNode(_address)); stakeNodeContractsStatuses[_address] = 1; } // set status, can disable / restrict invest proxy methods function setStakingNodeStatus(address _address, uint256 _status) public { require(hasRole(FINMGMT_ROLE, msg.sender), "finmgmt only"); stakeNodeContractsStatuses[_address] = _status; } function removeStakingNodeContract(uint256 index) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); //delete at index (order does not matter) stakeNodeContractsStatuses[address(stakeNodeContracts[index])] = 0; stakeNodeContracts[index] = stakeNodeContracts[stakeNodeContracts.length-1]; stakeNodeContracts.pop(); } // UBT staking node invest/divest methods function borrowToStake(uint256 _amount) public override returns (uint256) { require( stakeNodeContractsStatuses[msg.sender] == 1, "active invest proxy only" ); IERC20Upgradeable(baseAsset).safeTransfer(msg.sender, _amount); emit UBTStaked(msg.sender, _amount); return _amount; } // return funds body from HolyValor (divest), yield should go through yield distributor function returnInvested(uint256 _amount) public override { require(stakeNodeContractsStatuses[msg.sender] > 0, "invest proxy only"); // statuses 1 (active) or 2 (withdraw only) are ok IERC20Upgradeable(baseAsset).safeTransferFrom( address(msg.sender), address(this), _amount ); emit UBTUnstaked(msg.sender, _amount); } // used to get funds from UBT invest proxy for withdrawal (if current amount to withdraw is insufficient) function retrieveFunds(uint256 _amount) internal returns (uint256) { uint256 amountTotal = 0; // it is not possible to resize memory arrays, so declare sized one uint256 length = stakeNodeContracts.length; uint256[] memory amounts = new uint256[](length); uint256[] memory indexes = new uint256[](length); for (uint256 i; i < length; i++) { amounts[i] = stakeNodeContracts[i].reclaimAmount(); if ( amounts[i] >= _amount && stakeNodeContractsStatuses[address(stakeNodeContracts[i])] > 0 ) { // great, this node contract can provide funds stakeNodeContracts[i].reclaimFunds(_amount); emit UBTReclaimed(address(stakeNodeContracts[i]), _amount); return _amount; } indexes[i] = i; amountTotal = amountTotal.add(amounts[i]); } require (amountTotal > _amount, "insufficient UBT"); // no single Node contract has enough safe amount to get funds from, sort and pick largest ones to save gas // as a reasonable empryric, number of active Nodes would be less than 10, so use reverse insertion sort for (uint256 i = length - 1; i >= 0; i--) { uint256 picked = amounts[i]; uint256 pickedIndex = indexes[i]; uint256 j = i + 1; while ((j < length) && (amounts[j] > picked)) { amounts[j - 1] = amounts[j]; indexes[j - 1] = indexes[j]; j++; } amounts[j - 1] = picked; indexes[j - 1] = pickedIndex; if (i == 0) { break; // uint256 won't be negative } } uint256 totalReclaimed = 0; // reclaim funds one by one (from sorted Node contract list) for (uint256 i = 0; i < length; i++) { uint256 amountToWithdraw = amounts[i]; if (amountToWithdraw > _amount.sub(totalReclaimed)) { amountToWithdraw = _amount.sub(totalReclaimed); } stakeNodeContracts[indexes[i]].reclaimFunds(amountToWithdraw); totalReclaimed = totalReclaimed.add(amountToWithdraw); emit UBTReclaimed(address(stakeNodeContracts[indexes[i]]), amountToWithdraw); if (totalReclaimed >= _amount) { break; } } return totalReclaimed; } }
Staking Node contract management functions
function addStakingNode(address _address) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); stakeNodeContracts.push(IUBTStakingNode(_address)); stakeNodeContractsStatuses[_address] = 1; }
2,238,727
/** *Submitted for verification at Etherscan.io on 2020-07-19 */ pragma solidity 0.6.7; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */ library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); 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 private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor(address initialOwner) internal { require(initialOwner != address(0), "Ownable: initial owner is the zero address"); _owner = initialOwner; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * See https://eips.ethereum.org/EIPS/eip-20 */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } /** * @title ApproveAndCall Interface. * @dev ApproveAndCall system allows to communicate with smart-contracts. */ abstract contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 amount, address token, bytes calldata extraData) virtual external; } /** * @title The main project contract. */ contract DigexToken is ERC20, Ownable { // registered contracts (to prevent loss of token via transfer function) mapping (address => bool) private _contracts; /** * @dev constructor function that is called once at deployment of the contract. * @param recipient Address to receive initial supply. */ constructor(address initialOwner, address recipient) public Ownable(initialOwner) { // name of the token _name = "Digex"; // symbol of the token _symbol = "DIGEX"; // decimals of the token _decimals = 0; // creation of initial supply _mint(recipient, 21000000000); } /** * @dev Allows to send tokens (via Approve and TransferFrom) to other smart-contract. * @param spender Address of smart contracts to work with. * @param amount Amount of tokens to send. * @param extraData Any extra data. */ function approveAndCall(address spender, uint256 amount, bytes memory extraData) public returns (bool) { require(approve(spender, amount)); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, amount, address(this), extraData); return true; } /** * @dev modified transfer function that allows to safely send tokens to smart-contract. * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public override returns (bool) { if (_contracts[to]) { approveAndCall(to, value, new bytes(0)); } else { super.transfer(to, value); } return true; } /** * @dev Allows to register other smart-contracts (to prevent loss of tokens via transfer function). * @param account Address of smart contracts to work with. */ function registerContract(address account) external onlyOwner { require(_isContract(account), "DigexToken: account is not a smart-contract"); _contracts[account] = true; } /** * @dev Allows to unregister registered smart-contracts. * @param account Address of smart contracts to work with. */ function unregisterContract(address account) external onlyOwner { require(isRegistered(account), "DigexToken: account is not registered yet"); _contracts[account] = false; } /** * @dev Allows to any owner of the contract withdraw needed ERC20 token from this contract (for example promo or bounties). * @param ERC20Token Address of ERC20 token. * @param recipient Account to receive tokens. */ function withdrawERC20(address ERC20Token, address recipient) external onlyOwner { require(recipient != address(0), "DigexToken: recipient is the zero address"); uint256 amount = IERC20(ERC20Token).balanceOf(address(this)); IERC20(ERC20Token).transfer(recipient, amount); } /** * @return true if the address is registered as contract * @param account Address to be checked. */ function isRegistered(address account) public view returns (bool) { return _contracts[account]; } /** * @return true if `account` is a contract. * @param account Address to be checked. */ function _isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } }
Allows to any owner of the contract withdraw needed ERC20 token from this contract (for example promo or bounties). ERC20Token Address of ERC20 token. recipient Account to receive tokens./
function withdrawERC20(address ERC20Token, address recipient) external onlyOwner { require(recipient != address(0), "DigexToken: recipient is the zero address"); uint256 amount = IERC20(ERC20Token).balanceOf(address(this)); IERC20(ERC20Token).transfer(recipient, amount); }
6,636,097
./partial_match/1313161554/0x964630b8327A6EB8730e3addcB8563d1e61b0100/sources/Comptroller.sol
Validates transfer and reverts on rejection. May emit logs. chToken Asset being transferred src The account which sources the tokens dst The account which receives the tokens transfeChTokens The number of chTokens to transfer/ Shh - currently unused Shh - we don't ever want this hook to be marked pure
function transferVerify( address chToken, address src, address dst, uint256 transfeChTokens ) external { chToken; src; dst; transfeChTokens; if (false) { maxAssets = maxAssets; } }
16,919,368
./full_match/80001/0x4A8F7b3f9DF6628F6C528E80a65AaC92093DeB37/sources/project_/contracts/StandardNFT.sol
royalty_ is in percentage royalty is 2 decimal palces, mean 100 means 1% royalty_ should less than or equal to maxRoyalty
function setRoyalty(uint256 royalty_) public onlyOwner { require( royalty_ <= maxRoyalty, "royalty should less than or equal to maxRoyalty" ); _royalty = royalty_; emit SetRoyalty(royalty_); }
5,651,634
/* Attestation decode and validation */ /* AlphaWallet 2021 */ pragma solidity ^0.6.0; contract UseAttestation { address payable owner; bytes1 constant BOOLEAN_TAG = bytes1(0x01); bytes1 constant INTEGER_TAG = bytes1(0x02); bytes1 constant BIT_STRING_TAG = bytes1(0x03); bytes1 constant OCTET_STRING_TAG = bytes1(0x04); bytes1 constant NULL_TAG = bytes1(0x05); bytes1 constant OBJECT_IDENTIFIER_TAG = bytes1(0x06); bytes1 constant EXTERNAL_TAG = bytes1(0x08); bytes1 constant ENUMERATED_TAG = bytes1(0x0a); // decimal 10 bytes1 constant SEQUENCE_TAG = bytes1(0x10); // decimal 16 bytes1 constant SET_TAG = bytes1(0x11); // decimal 17 bytes1 constant SET_OF_TAG = bytes1(0x11); bytes1 constant NUMERIC_STRING_TAG = bytes1(0x12); // decimal 18 bytes1 constant PRINTABLE_STRING_TAG = bytes1(0x13); // decimal 19 bytes1 constant T61_STRING_TAG = bytes1(0x14); // decimal 20 bytes1 constant VIDEOTEX_STRING_TAG = bytes1(0x15); // decimal 21 bytes1 constant IA5_STRING_TAG = bytes1(0x16); // decimal 22 bytes1 constant UTC_TIME_TAG = bytes1(0x17); // decimal 23 bytes1 constant GENERALIZED_TIME_TAG = bytes1(0x18); // decimal 24 bytes1 constant GRAPHIC_STRING_TAG = bytes1(0x19); // decimal 25 bytes1 constant VISIBLE_STRING_TAG = bytes1(0x1a); // decimal 26 bytes1 constant GENERAL_STRING_TAG = bytes1(0x1b); // decimal 27 bytes1 constant UNIVERSAL_STRING_TAG = bytes1(0x1c); // decimal 28 bytes1 constant BMP_STRING_TAG = bytes1(0x1e); // decimal 30 bytes1 constant UTF8_STRING_TAG = bytes1(0x0c); // decimal 12 bytes1 constant CONSTRUCTED_TAG = bytes1(0x20); // decimal 28 bytes1 constant LENGTH_TAG = bytes1(0x30); bytes1 constant VERSION_TAG = bytes1(0xA0); bytes1 constant COMPOUND_TAG = bytes1(0xA3); uint256 constant IA5_CODE = uint256(bytes32("IA5")); //tags for disambiguating content uint256 constant DEROBJ_CODE = uint256(bytes32("OBJID")); address constant validAttestorAddress = 0x5f7bFe752Ac1a45F67497d9dCDD9BbDA50A83955; //fixed issuer address event Value(uint256 indexed val); event RtnStr(bytes val); event RtnS(string val); uint256 callCount; uint256 constant pointLength = 65; constructor() public { owner = msg.sender; callCount = 0; } struct Length { uint decodeIndex; uint length; } //Payable variant of the attestation function for testing function testAttestationCall(bytes memory attestation) public returns(bool) { (address subjectAddress, address attestorAddress) = decodeAttestation(attestation); if (attestorAddress == validAttestorAddress && msg.sender == subjectAddress) { callCount++; return true; } else { return false; } } function decodeAttestation(bytes memory proof) public pure returns(address subjectAddress, address attestorAddress) { bytes memory attestationData; bytes memory preHash; uint256 nIndex = 1; uint256 decodeIndex = 0; uint256 length = 0; //decodeElement(bytes memory byteCode, uint decodeIndex) private pure returns(uint newIndex, bytes memory content, uint256 length) /* Attestation structure: Length, Length - Version, - Serial, - Signature type, - Issuer Sequence, - Validity Time period Start, finish - */ (length, nIndex) = decodeLength(proof, nIndex); //nIndex is start of prehash (length, decodeIndex) = decodeLength(proof, nIndex+1); // length of prehash is decodeIndex (result) - nIndex //obtain pre-hash preHash = copyDataBlock(proof, nIndex, (decodeIndex + length) - nIndex); nIndex = (decodeIndex + length); //set pointer to read data after the pre-hash block (length, decodeIndex) = decodeLength(preHash, 1); //read pre-hash header (length, decodeIndex) = decodeLength(preHash, decodeIndex + 1); // Version (length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Serial (length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Signature type (9) 1.2.840.10045.2.1 (length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX) (length, attestationData, decodeIndex) = decodeElement(preHash, decodeIndex + length); // Validity Time (34) (Start, End) 32303231303331343030303835315A, 32303231303331343031303835315A //TODO: Read and check validity times (length, attestationData, decodeIndex) = decodeElementOffset(preHash, decodeIndex, 13); // Subject Address (53) (Type: 2.5.4.3, Addr: 30 78 30 37 31 0x071 ...) 11 subjectAddress = address(asciiToUintAsm(attestationData)); //(length, attestationData, decodeIndex) = decodeElement(preHash, decodeIndex); // Subject public key info (307) (not of any use to contract) //(length, attestationData, decodeIndex) = decodeElement(preHash, decodeIndex); // Contract info (7) [42, 1337] //(length, attestationData, decodeIndex) = decodeElement(preHash, decodeIndex); // Exention data (87) [1.3.6.1.4.1.1466.115.121.1.40, TRUE, #0415fd25179e47ea9fe36d52332ddcf03f3b5a578d662458d633e90549219c0d4d196698e2e33afe85a8a707cb08fab2ded1514a8639ab87ef6c1c0efc6ebd62b4] (length, attestationData, nIndex) = decodeElement(proof, nIndex); // Signature algorithm ID (9) 1.2.840.10045.2.1 (length, attestationData, nIndex) = decodeElementOffset(proof, nIndex, 1); // Signature (72) : #0348003045022100F1862F9616B43C1F1550156341407AFB11EEC8B8BB60A513B346516DBC4F1F3202204E1B19196B97E4AECD6AE7E701BF968F72130959A01FCE83197B485A6AD2C7EA bytes32 hash = keccak256(preHash); //recover Signature attestorAddress = recoverSigner(hash, attestationData); } function recoverSigner(bytes32 hash, bytes memory signature) private pure returns(address signer) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(signature); return ecrecover(hash, v, r, s); } function splitSignature(bytes memory sig) public pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "invalid signature length"); assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } } // Solidity hex ascii to uint conversion (eg 0x30373038 is 0x0708) function asciiToUint(bytes memory asciiData) public pure returns(uint256 val) { //first convert to bytes bytes memory hexData = new bytes(32); uint256 offset = 32 - (asciiData.length/2); for (uint256 i = 0; i < 20; i++) { uint8 element1 = uint8(asciiData[i*2]) - 0x30; uint8 element2 = uint8(asciiData[i*2 + 1]) - 0x30; if (element1 > 0x9) element1 -= 7; if (element2 > 0x9) element2 -= 7; hexData[i+offset] = bytes1((element1 << 4) | (element2)); } assembly { val := mload(add(hexData, 32)) } } // Optimised hex ascii to uint conversion (eg 0x30373038 is 0x0708) function asciiToUintAsm(bytes memory asciiData) public pure returns(uint256 asciiValue) { bytes memory hexData = new bytes(32); bytes1 b1; bytes1 b2; bytes1 sum; assembly { let index := 0 // current write index, we have to count upwards to avoid an unsigned 0xFFFFFF infinite loop .. let topIndex := 0x27 // final ascii to read let bIndex := 0x20 // write index into bytes array we're using to build the converted number for { let cc := add(asciiData, topIndex) // start reading position in the ascii data } lt(index, topIndex) { index := add(index, 0x02) // each value to write is two bytes cc := sub(cc, 0x02) bIndex := sub(bIndex, 0x01) // index into scratch buffer } { //build top nibble of value b1 := and(mload(cc), 0xFF) if gt(b1, 0x39) { b1 := sub(b1, 0x07) } //correct for ascii numeric value b1 := sub(b1, 0x30) b1 := mul(b1, 0x10) //move to top nibble //build bottom nibble b2 := and(mload(add(cc, 0x01)), 0xFF) if gt(b2, 0x39) { b2 := sub(b2, 0x07) } //correct for ascii numeric value b2 := sub(b2, 0x30) //combine both nibbles sum := add(b1, b2) //write the combined byte into the scratch buffer // - note we have to point 32 bytes ahead as 'sum' uint8 value is at the end of a 32 byte register let hexPtr := add(hexData, bIndex) mstore(hexPtr, sum) } mstore(hexData, 0x20) // patch the variable size info we corrupted in the mstore // NB: we may not need to do this, we're only using this buffer as a memory scratch // However EVM stack cleanup unwind may break, TODO: determine if it's safe to remove asciiValue := mload(add(hexData, 32)) // convert to uint } } function decodeDERData(bytes memory byteCode, uint dIndex) public pure returns(bytes memory data, uint256 index, uint256 length) { return decodeDERData(byteCode, dIndex, 0); } function copyDataBlock(bytes memory byteCode, uint dIndex, uint length) public pure returns(bytes memory data) { uint256 blank = 0; uint256 index = dIndex; uint dStart = 0x20 + index; uint cycles = length / 0x20; uint requiredAlloc = length; if (length % 0x20 > 0) //optimise copying the final part of the bytes - remove the looping { cycles++; requiredAlloc += 0x20; //expand memory to allow end blank } data = new bytes(requiredAlloc); assembly { let mc := add(data, 0x20) //offset into bytes we're writing into let cycle := 0 for { let cc := add(byteCode, dStart) } lt(cycle, cycles) { mc := add(mc, 0x20) cc := add(cc, 0x20) cycle := add(cycle, 0x01) } { mstore(mc, mload(cc)) } } //finally blank final bytes and shrink size if (length % 0x20 > 0) { uint offsetStart = 0x20 + length; assembly { let mc := add(data, offsetStart) mstore(mc, mload(add(blank, 0x20))) //now shrink the memory back mstore(data, length) } } } function decodeDERData(bytes memory byteCode, uint dIndex, uint offset) public pure returns(bytes memory data, uint256 index, uint256 length) { index = dIndex + 1; (length, index) = decodeLength(byteCode, index); uint requiredLength = length - offset; uint dStart = index + offset; data = copyDataBlock(byteCode, dStart, requiredLength); index += length; } function decodeElement(bytes memory byteCode, uint decodeIndex) private pure returns(uint256 length, bytes memory content, uint256 newIndex) { if (byteCode[decodeIndex] == LENGTH_TAG || byteCode[decodeIndex] == VERSION_TAG || byteCode[decodeIndex] == INTEGER_TAG || byteCode[decodeIndex] == COMPOUND_TAG || byteCode[decodeIndex] == BIT_STRING_TAG) { (content, newIndex, length) = decodeDERData(byteCode, decodeIndex); } else { (length, newIndex) = decodeLength(byteCode, decodeIndex + 1); //don't attempt to read content newIndex += length; } } function decodeElementOffset(bytes memory byteCode, uint decodeIndex, uint offset) private pure returns(uint256 length, bytes memory content, uint256 newIndex) { (content, newIndex, length) = decodeDERData(byteCode, decodeIndex, offset); } function decodeLength(bytes memory byteCode, uint decodeIndex) private pure returns(uint256 length, uint256 newIndex) { uint codeLength = 1; length = 0; newIndex = decodeIndex; if ((byteCode[newIndex] & 0x80) == 0x80) { codeLength = uint8((byteCode[newIndex++] & 0x7f)); } for (uint i = 0; i < codeLength; i++) { length |= uint(uint8(byteCode[newIndex++] & 0xFF)) << ((codeLength - i - 1) * 8); } } function decodeIA5String(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) private pure returns(Status memory) { uint length = uint8(byteCode[decodeIndex++]); bytes32 store = 0; for (uint j = 0; j < length; j++) store |= bytes32(byteCode[decodeIndex++] & 0xFF) >> (j * 8); objCodes[objCodeIndex++] = uint256(store); Status memory retVal; retVal.decodeIndex = decodeIndex; retVal.objCodeIndex = objCodeIndex; return retVal; } struct Status { uint decodeIndex; uint objCodeIndex; } function endContract() public payable { if(msg.sender == owner) { selfdestruct(owner); } else revert(); } function concat4Fixed( bytes memory _bytes1, bytes memory _bytes2, bytes memory _bytes3, bytes memory _bytes4 ) internal pure returns (bytes memory join) { join = new bytes(pointLength*4); //in this case, we know how large the end result will be assembly { // 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(join, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, pointLength) for { // Initialize a copy counter to the start of the _bytes1 data, // 32 bytes into its memory. let cc := add(_bytes1, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _bytes1 data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes2, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes3, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes4, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } } } // Concat3 which requires the three inputs to be 65 bytes length each // Doesn't perform any padding - could an EC coordinate be less than 32 bytes? If so, the mapTo256BigInteger result will be incorrect function concat3Fixed( bytes memory _bytes1, bytes memory _bytes2, bytes memory _bytes3 ) internal pure returns (bytes memory join) { join = new bytes(pointLength*3); //in this case, we know how large the end result will be assembly { // 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(join, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, pointLength) for { // Initialize a copy counter to the start of the _bytes1 data, // 32 bytes into its memory. let cc := add(_bytes1, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _bytes1 data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes2, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Move the memory counter back from a multiple of 0x20 to the // actual end of the _bytes1 data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, pointLength) for { let cc := add(_bytes3, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } } } }
decodeElement(bytes memory byteCode, uint decodeIndex) private pure returns(uint newIndex, bytes memory content, uint256 length)obtain pre-hashTODO: Read and check validity times(length, attestationData, decodeIndex) = decodeElement(preHash, decodeIndex); Subject public key info (307) (not of any use to contract)(length, attestationData, decodeIndex) = decodeElement(preHash, decodeIndex); Contract info (7) [42, 1337](length, attestationData, decodeIndex) = decodeElement(preHash, decodeIndex); Exention data (87) [1.3.6.1.4.1.1466.115.121.1.40, TRUE, 0415fd25179e47ea9fe36d52332ddcf03f3b5a578d662458d633e90549219c0d4d196698e2e33afe85a8a707cb08fab2ded1514a8639ab87ef6c1c0efc6ebd62b4]recover Signature
function decodeAttestation(bytes memory proof) public pure returns(address subjectAddress, address attestorAddress) { bytes memory attestationData; bytes memory preHash; uint256 nIndex = 1; uint256 decodeIndex = 0; uint256 length = 0; Attestation structure: Length, Length - Version, - Serial, - Signature type, - Issuer Sequence, - Validity Time period Start, finish - preHash = copyDataBlock(proof, nIndex, (decodeIndex + length) - nIndex); subjectAddress = address(asciiToUintAsm(attestationData)); bytes32 hash = keccak256(preHash); attestorAddress = recoverSigner(hash, attestationData); }
12,583,211
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/CMRewards.sol // Expirmental! v0.6.1 pragma solidity 0.6.6; // CMRewards is a contract for calculating rewards // based the amount a user has staked. contract CMRewards { using SafeMath for uint256; // rewards rate = rewardRate / rewardMin uint256 public rewardMin = 1e10; // wont calculate rewards on smaller. uint256 public rewardRate = 5; // 5/1e10 ~ .001 per share mapping(address => UserStake) public users; /** @dev * This keeps track of a users stake for calculating payouts and * rewards */ struct UserStake { uint256 staked; uint256 lastUpdated; uint256 rewardDebt; } /** @dev adds pending rewards to reward debt. */ function _updateUser(address u) internal { if (users[u].staked > rewardMin) { users[u].rewardDebt = users[u].rewardDebt.add(_pendingRewards(u)); } users[u].lastUpdated = block.number; } /** @dev calculates a users rewards that accumilated since the last update*/ function _pendingRewards(address u) internal view returns (uint256) { uint256 _duration = block.number.sub(users[u].lastUpdated); uint256 _rewards = rewardRate.mul(users[u].staked).div(rewardMin); return _duration.mul(_rewards); } /** @dev adds staked amount to the user safely. (Updates user before) */ function _userAddStake(address _addr, uint256 _value) internal { require(_value > 0, "staked value must be greated than 0"); _updateUser(_addr); users[_addr].staked = users[_addr].staked.add(_value); } /** @dev safely removes from a users stake. (Updates user before) */ function _usersRemoveStake(address _addr, uint256 _value) internal { require(users[_addr].staked >= _value, "Cannot remove more than the user has staked"); _updateUser(_addr); users[_addr].staked = users[_addr].staked.sub(_value); } } // File: contracts/DiFyDAIWallet.sol pragma solidity 0.6.6; interface IYDAI { function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function balanceOf(address account) external view returns(uint256); function getPricePerFullShare() external view returns(uint256); } contract DiFyDAIWallet is Ownable, CMRewards { using SafeMath for uint256; uint256 constant BP = 10**12; IERC20 yfiii; IERC20 dai; IYDAI ydai; uint256 public adminFee = 5; // 0.5% uint256 constant public adminFeeMax = 150; // 15% uint256 constant adminFeeFull = 1000; constructor(address daiAddress, address ydaiAddress, address yfiiiAddress) public { dai = IERC20(daiAddress); ydai = IYDAI(ydaiAddress); yfiii = IERC20(yfiiiAddress); } /** * @dev deposit dai and stake the recieved ydai for rewards */ function deposit(uint256 _amount) public { // transfer dai require(dai.transferFrom(msg.sender, address(this), _amount), "deposit failed"); // starting ydai balance: uint256 startBal = ydai.balanceOf(address(this)); // invest with ydai ydai.deposit(_amount); // endind ydai balance: uint256 endBal = ydai.balanceOf(address(this)); // update the user _userAddStake(msg.sender, endBal.sub(startBal)); } /** * @dev withdraw msg.sender's staked ydai from yearn, take admin fee and * and send dai the dai to msg.sender */ function withdraw(uint256 _amount) public { require(_amount <= users[msg.sender].staked, "Cannot withdraw more than your balance"); require(_amount > 0, "Cannot withdraw 0"); // update user and subtract withdrawed amount _usersRemoveStake(msg.sender, _amount); // withdraw from ydai uint256 startBal = dai.balanceOf(address(this)); ydai.withdraw(_amount); uint256 endBal = dai.balanceOf(address(this)); // send to user uint256 _avaliable = endBal.sub(startBal); uint256 _fee = _avaliable.mul(adminFee).div(adminFeeFull); require(dai.transfer(msg.sender, _avaliable.sub(_fee)), "withdraw failed"); //dai.transfer(owner(), _fee); } /** * @dev claim reward debt */ function claim() public { // update the user – calculating any rewards _updateUser(msg.sender); // transfer the rewards uint256 _rewards = users[msg.sender].rewardDebt; users[msg.sender].rewardDebt = 0; // transfer require(yfiii.transfer(msg.sender, _rewards), "transfer failed"); } // Helper methods: /** * @dev see a users total rewards. reward_debt + rewards_pending */ function userRewards(address u) public view returns(uint256) { return users[u].rewardDebt.add(_pendingRewards(u)); } /** * @dev see a users current amount of ydai staked. Alias for users[u].staked */ function userStake(address u) public view returns(uint256) { return users[u].staked; } /** * @dev force update yourself to lock in rewards. (This shouldnt need to be called). */ function updateSelf() public { _updateUser(msg.sender); } /** * @dev total DAI balance of this contract */ function balanceDAI() public view returns(uint256) { return dai.balanceOf(address(this)); } /** * @dev total YDAI balance */ function balanceYDAI() public view returns(uint256) { return ydai.balanceOf(address(this)); } /** * @dev withdraw ETH token to a given address. */ function safeWithdrawETH(address payable to, uint256 amount) public onlyOwner { to.transfer(amount); } /** * @dev dai balance */ function safeWithdrawDAI(address payable to, uint256 amount) public onlyOwner { dai.transfer(to, amount); } /** * @dev withdraw an erc20 token to a given address. * cannot withdraw yDAI */ function safeWithdrawERC20(address token, address to, uint amount) public onlyOwner { // This method is only for removing tokens that were accidentally sent here. // Therefore, owner cannot remove ydai, as these are held on behalf of the users. require(token != address(ydai), "cannot withdraw ydai"); IERC20(token).transfer(to, amount); } /** * @dev set reward rate. reward rate = rate / reward_min */ function setRewardRate(uint _newRate) public onlyOwner { rewardRate = _newRate; } /** * @dev sets minimum stake to recieve rewards */ function setRewardMin(uint _newMin) public onlyOwner { rewardMin = _newMin; } /** * @dev sets new admin fee. Must be smaller than adminFeeMax */ function setAdminFee(uint256 _newFee) public onlyOwner { require(_newFee < adminFeeMax, "fee must be less than max fee"); adminFee = _newFee; } function approve() public onlyOwner { dai.approve(address(ydai), 2**256 - 1); } }
total YDAI balance/
function balanceYDAI() public view returns(uint256) { return ydai.balanceOf(address(this)); }
10,921,569
/* -------------------------------------------------------------------------------- The Bethereum [BETHER] Token Smart Contract Credit: Bethereum Limited ERC20: https://github.com/ethereum/EIPs/issues/20 ERC223: https://github.com/ethereum/EIPs/issues/223 MIT Licence -------------------------------------------------------------------------------- */ /* * Contract that is working with ERC223 tokens */ contract ContractReceiver { function tokenFallback(address _from, uint _value, bytes _data) { /* Fix for Mist warning */ _from; _value; _data; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC223Interface { uint public totalSupply; function balanceOf(address who) constant returns (uint); event Transfer(address indexed from, address indexed to, uint value, bytes data); } contract BethereumERC223 is ERC223Interface { using SafeMath for uint256; /* Contract Constants */ string public constant _name = "Bethereum"; string public constant _symbol = "BETHER"; uint8 public constant _decimals = 18; /* Contract Variables */ address public owner; mapping(address => uint256) public balances; mapping(address => mapping (address => uint256)) public allowed; /* Constructor initializes the owner's balance and the supply */ function BethereumERC223() { totalSupply = 224181206832398351471266750; owner = msg.sender; } /* ERC20 Events */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed to, uint256 value); /* ERC223 Events */ event Transfer(address indexed from, address indexed to, uint value, bytes data); /* Returns the balance of a particular account */ function balanceOf(address _address) constant returns (uint256 balance) { return balances[_address]; } /* Transfer the balance from the sender's address to the address _to */ function transfer(address _to, uint _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } else { return false; } } /* Withdraws to address _to form the address _from up to the amount _value */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { balances[_from] -= _value; allowed[_from][msg.sender] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); return true; } else { return false; } } /* Allows _spender to withdraw the _allowance amount form sender */ function approve(address _spender, uint256 _allowance) returns (bool success) { allowed[msg.sender][_spender] = _allowance; Approval(msg.sender, _spender, _allowance); return true; } /* Checks how much _spender can withdraw from _owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* ERC223 Functions */ /* Get the contract constant _name */ function name() constant returns (string name) { return _name; } /* Get the contract constant _symbol */ function symbol() constant returns (string symbol) { return _symbol; } /* Get the contract constant _decimals */ function decimals() constant returns (uint8 decimals) { return _decimals; } /* Transfer the balance from the sender's address to the address _to with data _data */ function transfer(address _to, uint _value, bytes _data) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } else { return false; } } /* Transfer function when _to represents a regular address */ function transferToAddress(address _to, uint _value, bytes _data) internal returns (bool success) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); Transfer(msg.sender, _to, _value, _data); return true; } /* Transfer function when _to represents a contract address, with the caveat that the contract needs to implement the tokenFallback function in order to receive tokens */ function transferToContract(address _to, uint _value, bytes _data) internal returns (bool success) { balances[msg.sender] -= _value; balances[_to] += _value; ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value); Transfer(msg.sender, _to, _value, _data); return true; } /* Infers if whether _address is a contract based on the presence of bytecode */ function isContract(address _address) internal returns (bool is_contract) { uint length; if (_address == 0) return false; assembly { length := extcodesize(_address) } if(length > 0) { return true; } else { return false; } } /* Stops any attempt to send Ether to this contract */ function () { throw; } } /** * @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 Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is BethereumERC223, Pausable { function transfer(address _to, uint256 _value, bytes _data) public whenNotPaused returns (bool) { return super.transfer(_to, _value, _data); } 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); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is BethereumERC223, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract BethereumToken is MintableToken, PausableToken { function BethereumToken(){ pause(); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _endTime, address _wallet) { require(_endTime >= now); require(_wallet != 0x0); token = createTokenContract(); endTime = _endTime; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (BethereumToken) { return new BethereumToken(); } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; bool public weiCapReached = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } contract BETHERTokenSale is FinalizableCrowdsale { using SafeMath for uint256; // Define sale uint public constant RATE = 17500; uint public constant TOKEN_SALE_LIMIT = 25000 * 1000000000000000000; uint256 public constant TOKENS_FOR_OPERATIONS = 400000000*(10**18); uint256 public constant TOKENS_FOR_SALE = 600000000*(10**18); uint public constant TOKENS_FOR_PRESALE = 315000000*(1 ether / 1 wei); uint public BONUS_PERCENTAGE; enum Phase { Created, CrowdsaleRunning, Paused } Phase public currentPhase = Phase.Created; event LogPhaseSwitch(Phase phase); // Constructor function BETHERTokenSale( uint256 _end, address _wallet ) FinalizableCrowdsale() Crowdsale(_end, _wallet) { } function setNewBonusScheme(uint _bonusPercentage) { BONUS_PERCENTAGE = _bonusPercentage; } function mintRawTokens(address _buyer, uint256 _newTokens) public onlyOwner { token.mint(_buyer, _newTokens); } /// @dev Lets buy you some tokens. function buyTokens(address _buyer) public payable { // Available only if presale or crowdsale is running. require(currentPhase == Phase.CrowdsaleRunning); require(_buyer != address(0)); require(msg.value > 0); require(validPurchase()); uint tokensWouldAddTo = 0; uint weiWouldAddTo = 0; uint256 weiAmount = msg.value; uint newTokens = msg.value.mul(RATE); weiWouldAddTo = weiRaised.add(weiAmount); require(weiWouldAddTo <= TOKEN_SALE_LIMIT); newTokens = addBonusTokens(token.totalSupply(), newTokens); tokensWouldAddTo = newTokens.add(token.totalSupply()); require(tokensWouldAddTo <= TOKENS_FOR_SALE); token.mint(_buyer, newTokens); TokenPurchase(msg.sender, _buyer, weiAmount, newTokens); weiRaised = weiWouldAddTo; forwardFunds(); if (weiRaised == TOKENS_FOR_SALE){ weiCapReached = true; } } // @dev Adds bonus tokens by token supply bought by user // @param _totalSupply total supply of token bought during pre-sale/crowdsale // @param _newTokens tokens currently bought by user function addBonusTokens(uint256 _totalSupply, uint256 _newTokens) internal view returns (uint256) { uint returnTokens; uint tokens = _newTokens; returnTokens = tokens.add(tokens.mul(BONUS_PERCENTAGE).div(100)); return returnTokens; } function setSalePhase(Phase _nextPhase) public onlyOwner { currentPhase = _nextPhase; LogPhaseSwitch(_nextPhase); } function transferTokenOwnership(address _newOwner) { token.transferOwnership(_newOwner); } // Finalize function finalization() internal { uint256 toMint = TOKENS_FOR_OPERATIONS; token.mint(wallet, toMint); token.finishMinting(); token.transferOwnership(wallet); } }
Must be called after crowdsale ends, to do some extra finalization work. Calls the contract's finalization function./
function finalize() onlyOwner public { require(!isFinalized); finalization(); Finalized(); isFinalized = true; }
20,916
./full_match/43113/0x0fE2b51D3B543C6F359480BffBf8C4E6964aE40E/sources/src/interfaces/IERC20TransferProxy.sol
interface for transfering ERC20 tokens, contracts that implement this interface must support erc20safeTransferFrom method/
interface IERC20TransferProxy { function erc20safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) external; }
13,147,965
/** *Submitted for verification at Etherscan.io on 2020-08-31 */ pragma solidity ^0.6.12; // SPDX-License-Identifier: GPL-3.0 /** * @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. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "Not authorized operation"); _; } /** * @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), "Address shouldn't be zero"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } 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 _owner) external view returns (uint256); 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 Simple ERC20 Token example, with mintable token creation only during the deployement of the token contract */ contract TokenContract is Ownable{ using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public tokenOwner; address private ico; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; mapping(address => bool) public vestedlist; event SetICO(address indexed _ico); event Mint(address indexed to, uint256 amount); event MintFinished(); event UnlockToken(); event LockToken(); event Burn(); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); event addedToVestedlist(address indexed _vestedAddress); event removedFromVestedlist(address indexed _vestedAddress); bool public mintingFinished = false; bool public locked = true; modifier canMint() { require(!mintingFinished); _; } modifier canTransfer() { require(!locked || msg.sender == owner || msg.sender == ico); _; } modifier onlyAuthorized() { require(msg.sender == owner || msg.sender == ico); _; } constructor(string memory _name, string memory _symbol, uint8 _decimals) public { require (_decimals != 0); name = _name; symbol = _symbol; decimals = _decimals; totalSupply = 0; balances[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } /** * @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) public onlyAuthorized canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(this), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyAuthorized canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** * @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 canTransfer returns (bool) { require(_to != address(0)); require (!isVestedlisted(msg.sender)); require(_value <= balances[msg.sender]); require (msg.sender != address(this)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function burn(address _who, uint256 _value) onlyAuthorized public returns (bool){ require(_who != address(0)); totalSupply = totalSupply.sub(_value); balances[_who] = balances[_who].sub(_value); emit Burn(); emit Transfer(_who, address(0), _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @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 canTransfer 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; } function transferFromERC20Contract(address _to, uint256 _value) public onlyOwner returns (bool) { require(_to != address(0)); require(_value <= balances[address(this)]); balances[address(this)] = balances[address(this)].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(address(this), _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; 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) * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); 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) * @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 (block.gaslimit > oldValue) { //injected CONTRACT AFFECTED BY MINERS allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function unlockToken() public onlyAuthorized returns (bool) { locked = false; emit UnlockToken(); return true; } function lockToken() public onlyAuthorized returns (bool) { locked = true; emit LockToken(); return true; } function setICO(address _icocontract) public onlyOwner returns (bool) { require(_icocontract != address(0)); ico = _icocontract; emit SetICO(_icocontract); return true; } /** * @dev Adds list of addresses to Vestedlist. Not overloaded due to limitations with truffle testing. * @param _vestedAddress Addresses to be added to the Vestedlist */ function addToVestedlist(address[] memory _vestedAddress) public onlyOwner { for (uint256 i = 0; i < _vestedAddress.length; i++) { if (vestedlist[_vestedAddress[i]]) continue; vestedlist[_vestedAddress[i]] = true; } } /** * @dev Removes single address from Vestedlist. * @param _vestedAddress Address to be removed to the Vestedlist */ function removeFromVestedlist(address[] memory _vestedAddress) public onlyOwner { for (uint256 i = 0; i < _vestedAddress.length; i++) { if (!vestedlist[_vestedAddress[i]]) continue; vestedlist[_vestedAddress[i]] = false; } } function isVestedlisted(address _vestedAddress) internal view returns (bool) { return (vestedlist[_vestedAddress]); } }
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 canTransfer 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; }
1,009,401
pragma solidity 0.4.24; contract multisig{ uint MAX_OWNERS = 50; struct Transaction{ address destination; uint value; bytes data; bool executed; bool rejected; } /* --------------------------- Mappings --------------------------- */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (uint => mapping (address => bool)) public rejections; mapping (address => bool) public isOwner; /* --------------------------- Global variables --------------------------- */ uint public required; uint public transactionCount; address[] public owners; /* --------------------------- Events --------------------------- */ event addOwner(address newOwner); event removedOwner(address oldOwner); event requirementChanged(uint required); event transactionSubmit(uint transactionId); event valueDeposited(address sender, uint value); event transactionConfirmed(address confirmer,uint transactionId) event transactionRejected(address confirmer,uint transactionId) event transactionExecuted(uint transactionId); event transactionNotExecuted(uint transactionId); /* --------------------------- Modifiers --------------------------- */ modifier isNotAnOwner(address _owner){ require(isOwner[_owner] == false, "Owner already exists"); _; } modifier isAnOwner(address _owner){ require(isOwner[_owner] == true, "Owner does not exist"); _; } modifier notNull(address _address) { require(_address == 0, "Null Address"); _; } modifier notRejected(uint _transactionId){ require(transactions[transactionId].rejected == false, "Transaction has been rejected"); } /* --------------------------- Functions --------------------------- */ //check max length, check if address is valid constructor(address[] _owners, uint _required) public{ for(uint i = 0; i<_owners.length; i++) isOwner[_owners[i]] = true; owners = _owners; required = _required; } // fallback function to deposit ethers function () payable public { if(msg.value > 0) emit valueDeposited(msg.sender,msg.value); } //check max length, check if owner does not already exists, check if address is valid function addNewOwner(address _owner) public notNull(_owner) isNotAnOwner(_owner) { isOwner[_owner] = true; owners.push(_owner); emit addOwner(_owner); } //check if owner exists function removeOwner(address _owner) public notNull(_owner) isAnOwner(_owner) { isOwner[_owner] = false; for(uint i = 0; i<owners.length; i++){ if(owners[i] == _owner){ owners[i] = owners[owners.length - 1]; break; } } owners.length -= 1; if(required > owners.length) changeRequired(owners.length); emit removedOwner(_owner); } //check if owner exists, check if new owner does not exist function replaceOwner(address _owner, address _newOwner) public notNull(_owner) notNull(_newOwner) isAnOwner(_owner) isNotAnOwner(_newOwner) { for(uint i = 0; i<owners.length; i++){ if(owners[i] == _owner){ owners[i] = _newOwner; break; } isOwner[_owner] = false; isOwner[_newOwner] = true; emit removedOwner(_owner); emit addOwner(_newOwner); } } //check max length function changeRequired(uint _required) public{ required = _required; emit requirementChanged(_required); } /* ------------------------------- Transaction functions ------------------------------- */ function addTransaction(address _destination, uint _value, bytes _data) internal returns(uint){ transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: _destination, value: _value, data: _data, executed: false, rejected: false }); transactionCount += 1; emit transactionSubmit(transactionId); return transactionId; } function submitTransaction(address _destination, uint _value, bytes _data) public returns (uint) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); return transactionId; } function confirmTransaction(uint transactionId) public isAnOwner(msg.sender) notRejected(transactionId){ confirmations[transactionId][msg.sender] = true; rejections[transactionId][msg.sender] = false; emit transactionConfirmed(msg.sender, transactionId); executeTransaction(transactionId); } function revokeConfirmation(uint transactionId) public isAnOwner(msg.sender){ confirmations[transactionId][msg.sender] = false; rejections[transactionId][msg.sender] = true; emit transactionRejected(msg.sender, transactionId); } function isConfirmed(uint transactionId) internal view returns (bool){ uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } function isRejected(uint transactionId) public { uint count = 0; for (uint i=0; i<owners.length; i++) { if (rejections[transactionId][owners[i]]) count += 1; if (count == required) transactions[transactionId].rejected = true; } } function executeTransaction(uint transactionId) public { if (isConfirmed(transactionId)) { Transaction tx = transactions[transactionId]; tx.executed = true; if (tx.destination.call.value(tx.value)(tx.data)) emit transactionExecuted(transactionId); else { emit transactionNotExecuted(transactionId); tx.executed = false; } } } /* --------------------------- Data retrieval functions --------------------------- */ // get no. of confirmations for a transaction function getConfirmations(uint transactionId) public external view returns(uint){ uint confirmationCount = 0 for(uint i = 0; i < owners.length; i++) { if(confirmations[transactionId][owners[i]]) confirmationCount += 1; } return confirmationCount; } // return list of addresses of owners of the wallet function getOwners() public external view returns(address[]){ return owners; } // return list of addresses of owners who have confirmed a transaction function getOwnerConfirmations(uint transactionId) public external view returns (address[]) { address[] memory ownerConfirmationsTemp = new address[](owners.length); uint count = 0; for (uint i=0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { ownerConfirmationsTemp[count] = owners[i]; count += 1; } ownerConfirmations = new address[](count); for (uint i=0; i < count; i++) ownerConfirmations[i] = ownerConfirmationsTemp[i]; return ownerConfirmations; } }
check max length, check if owner does not already exists, check if address is valid
function addNewOwner(address _owner) public notNull(_owner) isNotAnOwner(_owner) { isOwner[_owner] = true; owners.push(_owner); emit addOwner(_owner); }
1,057,800
/** *Submitted for verification at Etherscan.io on 2021-06-16 */ // File: @openzeppelin/contracts/utils/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ // function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ // function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ // function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ // function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/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 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 guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual 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 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 returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To Project Name — StrongMonkey Token APR-2021 JUN-2021 Blockchain project on BSC. Contract on bscscan learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } pragma solidity ^0.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. *Community Marketing * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/Thicc.sol pragma solidity ^0.8.0; contract Thicc is ERC20,ReentrancyGuard { using SafeMath for uint256; address[] private TokenHolders; mapping(address=>bool) private HolderExist; uint256 public TokenHolderCount; address public creator = 0x8322b74995738131150024714a61F989C861f607; uint256 public LiquidityPoolPercent = 65; uint256 public FoundersPercent = 10; uint256 public MarketingCampaignsPercent = 10; uint256 public ThiccDAOPercent =10; uint256 public ProjectExpansionPercent = 2; uint256 public CommunityAccelerationPercent = 3; //it is 1.5% in time of mint we divide by 2 uint256 public MemeCompetitionPercent = 1; uint256 public ExchangeListingFeesPercent = 1; //it has to be 0.5 will divide by 2 in time of mint address public LiquidityPoolAddress = 0xB62AD9BB929F806C8A87b4c6BED0A82105e213F2; address public FoundersAddress = 0x1850071DDaC8f70De62747861Fd2f9b462175b05; address public MarketingCampaignsAddress = 0x915CAcB42E97846D5b99E307f46778e3228bA9D9; address public ThiccDAOAddress =0xDe94D0d9Ec430047C6F2C989686634260dAC0025; address public ProjectExpansionAddress = 0x17320414478814BeCCBCD3bDD63B5C2C0BE68358; address public CommunityAccelerationAddress = 0x0d99025f396dbdc5fE1354DD16a26DcA5108ED60; address public MemeCompetitionAddress = 0xe22730B6a78eC7B35FF4a1617AC67AdAdb0f162f; address public ExchangeListingFeesAddress = 0x84A6cd46BC1B02F3e585C7c5d2377b5e4c7416c0; uint256 public holderFeePercent = 3; uint256 private initialSupply = 1000000000000000 *(10**18); modifier onlyCreator() { require(msg.sender == creator,'only creator'); _; } event HolderFeePercentUpdated(uint256,uint256); event cMarketingAddressUpdated(address,address); event changeCreator(address,address); constructor() ERC20("Thicc Inu", "THICC") { _mint(LiquidityPoolAddress,initialSupply.mul(LiquidityPoolPercent).div(100)); TokenHolders.push(LiquidityPoolAddress); _mint(FoundersAddress,initialSupply.mul(FoundersPercent).div(100)); TokenHolders.push(FoundersAddress); _mint(MarketingCampaignsAddress,initialSupply.mul(MarketingCampaignsPercent).div(100)); TokenHolders.push(MarketingCampaignsAddress); _mint(ThiccDAOAddress,initialSupply.mul(ThiccDAOPercent).div(100)); TokenHolders.push(ThiccDAOAddress); _mint(ProjectExpansionAddress,initialSupply.mul(ProjectExpansionPercent).div(100)); TokenHolders.push(ProjectExpansionAddress); _mint(CommunityAccelerationAddress,initialSupply.mul(CommunityAccelerationPercent).div(200)); //we are dividing by 200 because we dobled the percentage in time of intialization TokenHolders.push(CommunityAccelerationAddress); _mint(MemeCompetitionAddress,initialSupply.mul(MemeCompetitionPercent).div(100)); TokenHolders.push(MemeCompetitionAddress); _mint(ExchangeListingFeesAddress,initialSupply.mul(ExchangeListingFeesPercent).div(200));//we are dividing by 200 because we dobled the percentage in time of intialization TokenHolders.push(ExchangeListingFeesAddress); TokenHolderCount+=8; } function setHolderFeePercent(uint256 _holderFeePercent) public onlyCreator { uint256 _previousHolderFeePercent = holderFeePercent; holderFeePercent = _holderFeePercent; emit HolderFeePercentUpdated(_previousHolderFeePercent,_holderFeePercent); } function setNewCreator(address _newCreator) public onlyCreator { address _previousCreator = creator; creator = _newCreator; emit changeCreator(_previousCreator,_newCreator); } function transfer(address recipient, uint256 amount) public override virtual returns (bool) { //transfer to recipient _transfer(msg.sender, recipient, amount); //Add recipient to holderlist if(!HolderExist[recipient]) { TokenHolders.push(recipient); HolderExist[recipient]=true; TokenHolderCount +=1; } //remove from holder list if(balanceOf(msg.sender)==0) { TokenHolderCount -=1; } return true; } function transferFrom(address sender, address recipient, uint256 amount) public override virtual returns (bool) { if (!(_msgSender() == creator || _msgSender() == LiquidityPoolAddress || _msgSender() == FoundersAddress || _msgSender() == MarketingCampaignsAddress || _msgSender() == ThiccDAOAddress || _msgSender() == ProjectExpansionAddress || _msgSender() == CommunityAccelerationAddress || _msgSender() == MemeCompetitionAddress || _msgSender() == ExchangeListingFeesAddress)) { //Holder FeePercent uint256 amountToHolders = amount.mul(holderFeePercent).div(100); for(uint256 i=0;i<TokenHolders.length;i++) { //check holder holding some balance or not if(balanceOf(TokenHolders[i])>0) { _transfer(sender,TokenHolders[i],amountToHolders.div(TokenHolderCount)); } } } //transfer to recipient _transfer(sender, recipient, amount.mul(100-holderFeePercent).div(100)); //Add recipient to holderlist if(!HolderExist[recipient]) { TokenHolders.push(recipient); HolderExist[recipient]=true; TokenHolderCount +=1; } //remove from holder list if(balanceOf(sender)<=0) { TokenHolderCount -=1; } uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } }
transfer to recipientAdd recipient to holderlistremove from holder list
function transfer(address recipient, uint256 amount) public override virtual returns (bool) { _transfer(msg.sender, recipient, amount); if(!HolderExist[recipient]) { TokenHolders.push(recipient); HolderExist[recipient]=true; TokenHolderCount +=1; } if(balanceOf(msg.sender)==0) { TokenHolderCount -=1; } return true; }
90,659
./full_match/1/0x40F36cdDBF94c3CCcf9F33C55feCEA61cDA32AAC/sources/src/Libraries/ABDKMathQuad.sol
Convert quadruple precision number into signed 128.128 bit fixed point number. Revert on overflow. x quadruple precision number return signed 128.128 bit fixed point number/ Negative
function to128x128(bytes16 x) internal pure returns (int256) { unchecked { uint256 exponent = (uint128(x) >> 112) & 0x7FFF; uint256 result = (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | 0x10000000000000000000000000000; if (exponent < 16367) result >>= 16367 - exponent; else if (exponent > 16367) result <<= exponent - 16367; if (uint128(x) >= 0x80000000000000000000000000000000) { require(result <= 0x8000000000000000000000000000000000000000000000000000000000000000, REQUIRE_ERROR); require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, REQUIRE_ERROR); return int256(result); } } }
8,428,256
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {GammaOperator} from "./GammaOperator.sol"; import {IGammaRedeemerV1} from "./interfaces/IGammaRedeemerV1.sol"; import {IPokeMe} from "./interfaces/IPokeMe.sol"; import {ITaskTreasury} from "./interfaces/ITaskTreasury.sol"; import {IResolver} from "./interfaces/IResolver.sol"; /// @author Willy Shen /// @title Gamma Automatic Redeemer /// @notice An automatic redeemer for Gmma otoken holders and writers contract GammaRedeemerV1 is IGammaRedeemerV1, GammaOperator { Order[] public orders; IPokeMe public automator; ITaskTreasury public automatorTreasury; bool public isAutomatorEnabled; // fee in 1/10.000: 1% = 100, 0.01% = 1 uint256 public redeemFee = 50; uint256 public settleFee = 10; /** * @notice only automator or owner */ modifier onlyAuthorized() { require( msg.sender == address(automator) || msg.sender == owner(), "GammaRedeemer::onlyAuthorized: Only automator or owner" ); _; } constructor( address _gammaAddressBook, address _automator, address _automatorTreasury ) GammaOperator(_gammaAddressBook) { automator = IPokeMe(_automator); automatorTreasury = ITaskTreasury(_automatorTreasury); isAutomatorEnabled = false; } function startAutomator(address _resolver) public onlyOwner { require(!isAutomatorEnabled); isAutomatorEnabled = true; automator.createTask( address(this), bytes4(keccak256("processOrders(uint256[])")), _resolver, abi.encodeWithSelector(IResolver.getProcessableOrders.selector) ); } function stopAutomator() public onlyOwner { require(isAutomatorEnabled); isAutomatorEnabled = false; automator.cancelTask( automator.getTaskId( address(this), address(this), bytes4(keccak256("processOrders(uint256[])")) ) ); } /** * @notice create automation order * @param _otoken the address of otoken (only holders) * @param _amount amount of otoken (only holders) * @param _vaultId the id of specific vault to settle (only writers) */ function createOrder( address _otoken, uint256 _amount, uint256 _vaultId ) public override { uint256 fee; bool isSeller; if (_otoken == address(0)) { require( _amount == 0, "GammaRedeemer::createOrder: Amount must be 0 when creating settlement order" ); fee = settleFee; isSeller = true; } else { require( isWhitelistedOtoken(_otoken), "GammaRedeemer::createOrder: Otoken not whitelisted" ); fee = redeemFee; } uint256 orderId = orders.length; Order memory order; order.owner = msg.sender; order.otoken = _otoken; order.amount = _amount; order.vaultId = _vaultId; order.isSeller = isSeller; order.fee = fee; orders.push(order); emit OrderCreated(orderId, msg.sender, _otoken); } /** * @notice cancel automation order * @param _orderId the id of specific order to be cancelled */ function cancelOrder(uint256 _orderId) public override { Order storage order = orders[_orderId]; require( order.owner == msg.sender, "GammaRedeemer::cancelOrder: Sender is not order owner" ); require( !order.finished, "GammaRedeemer::cancelOrder: Order is already finished" ); order.finished = true; emit OrderFinished(_orderId, true); } /** * @notice check if processing order is profitable * @param _orderId the id of specific order to be processed * @return true if settling vault / redeeming returns more than 0 amount */ function shouldProcessOrder(uint256 _orderId) public view override returns (bool) { Order memory order = orders[_orderId]; if (order.finished) return false; if (order.isSeller) { bool shouldSettle = shouldSettleVault(order.owner, order.vaultId); if (!shouldSettle) return false; } else { bool shouldRedeem = shouldRedeemOtoken( order.owner, order.otoken, order.amount ); if (!shouldRedeem) return false; } return true; } /** * @notice process an order * @dev only automator allowed * @param _orderId the id of specific order to process */ function processOrder(uint256 _orderId) public override onlyAuthorized { Order storage order = orders[_orderId]; require( !order.finished, "GammaRedeemer::processOrder: Order is already finished" ); require( shouldProcessOrder(_orderId), "GammaRedeemer::processOrder: Order should not be processed" ); order.finished = true; if (order.isSeller) { settleVault(order.owner, order.vaultId, order.fee); } else { redeemOtoken(order.owner, order.otoken, order.amount, order.fee); } emit OrderFinished(_orderId, false); } /** * @notice process multiple orders * @param _orderIds array of order ids to process */ function processOrders(uint256[] calldata _orderIds) public { for (uint256 i = 0; i < _orderIds.length; i++) { processOrder(_orderIds[i]); } } /** * @notice withdraw funds from automator * @param _token address of token to withdraw * @param _amount amount of token to withdraw */ function withdrawFund(address _token, uint256 _amount) public onlyOwner { automatorTreasury.withdrawFunds(payable(this), _token, _amount); } function setAutomator(address _automator) public onlyOwner { automator = IPokeMe(_automator); } function setAutomatorTreasury(address _automatorTreasury) public onlyOwner { automatorTreasury = ITaskTreasury(_automatorTreasury); } function setRedeemFee(uint256 _redeemFee) public onlyOwner { redeemFee = _redeemFee; } function setSettleFee(uint256 _settleFee) public onlyOwner { settleFee = _settleFee; } function getOrdersLength() public view override returns (uint256) { return orders.length; } function getOrders() public view override returns (Order[] memory) { return orders; } function getOrder(uint256 _orderId) public view override returns (Order memory) { return orders[_orderId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {IAddressBook} from "./interfaces/IAddressBook.sol"; import {IGammaController} from "./interfaces/IGammaController.sol"; import {IWhitelist} from "./interfaces/IWhitelist.sol"; import {IMarginCalculator} from "./interfaces/IMarginCalculator.sol"; import {Actions} from "./external/OpynActions.sol"; import {MarginVault} from "./external/OpynVault.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IOtoken} from "./interfaces/IOtoken.sol"; /// @author Willy Shen /// @title Gamma Operator /// @notice Opyn Gamma protocol adapter for redeeming otokens and settling vaults contract GammaOperator is Ownable { using SafeERC20 for IERC20; // Gamma Protocol contracts IAddressBook public addressBook; IGammaController public controller; IWhitelist public whitelist; IMarginCalculator public calculator; /** * @dev fetch Gamma contracts from address book * @param _addressBook Gamma Address Book address */ constructor(address _addressBook) { setAddressBook(_addressBook); refreshConfig(); } /** * @notice redeem otoken on behalf of user * @param _owner owner address * @param _otoken otoken address * @param _amount amount of otoken * @param _fee fee in 1/10.000 */ function redeemOtoken( address _owner, address _otoken, uint256 _amount, uint256 _fee ) internal { uint256 actualAmount = getRedeemableAmount(_owner, _otoken, _amount); IERC20(_otoken).safeTransferFrom(_owner, address(this), actualAmount); Actions.ActionArgs memory action; action.actionType = Actions.ActionType.Redeem; action.secondAddress = address(this); action.asset = _otoken; action.amount = _amount; Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; IERC20 collateral = IERC20(IOtoken(_otoken).collateralAsset()); uint256 startAmount = collateral.balanceOf(address(this)); controller.operate(actions); uint256 endAmount = collateral.balanceOf(address(this)); uint256 difference = endAmount - startAmount; uint256 finalAmount = difference - ((_fee * difference) / 10000); collateral.safeTransfer(_owner, finalAmount); } /** * @notice settle vault on behalf of user * @param _owner owner address * @param _vaultId vaultId to settle * @param _fee fee in 1/10.000 */ function settleVault( address _owner, uint256 _vaultId, uint256 _fee ) internal { Actions.ActionArgs memory action; action.actionType = Actions.ActionType.SettleVault; action.owner = _owner; action.vaultId = _vaultId; action.secondAddress = address(this); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; (MarginVault.Vault memory vault, , ) = getVaultWithDetails( _owner, _vaultId ); address otoken = getVaultOtoken(vault); IERC20 collateral = IERC20(IOtoken(otoken).collateralAsset()); uint256 startAmount = collateral.balanceOf(address(this)); controller.operate(actions); uint256 endAmount = collateral.balanceOf(address(this)); uint256 difference = endAmount - startAmount; uint256 finalAmount = difference - ((_fee * difference) / 10000); collateral.safeTransfer(_owner, finalAmount); } /** * @notice return if otoken should be redeemed * @param _owner owner address * @param _otoken otoken address * @param _amount amount of otoken * @return true if otoken has expired and payout is greater than zero */ function shouldRedeemOtoken( address _owner, address _otoken, uint256 _amount ) public view returns (bool) { uint256 actualAmount = getRedeemableAmount(_owner, _otoken, _amount); try this.getRedeemPayout(_otoken, actualAmount) returns ( uint256 payout ) { if (payout == 0) return false; } catch { return false; } return true; } /** * @notice return if vault should be settled * @param _owner owner address * @param _vaultId vaultId to settle * @return true if vault can be settled, contract is operator of owner, * and excess collateral is greater than zero */ function shouldSettleVault(address _owner, uint256 _vaultId) public view returns (bool) { ( MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId); (uint256 payout, bool isValidVault) = getExcessCollateral( vault, typeVault ); if (!isValidVault || payout == 0) return false; return true; } /** * @notice set Gamma Address Book * @param _address Address Book address */ function setAddressBook(address _address) public onlyOwner { require( _address != address(0), "GammaOperator::setAddressBook: Address must not be zero" ); addressBook = IAddressBook(_address); } /** * @notice transfer operator profit * @param _token address token to transfer * @param _amount amount of token to transfer * @param _to transfer destination */ function harvest( address _token, uint256 _amount, address _to ) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { (bool success, ) = _to.call{value: _amount}(""); require(success, "GammaOperator::harvest: ETH transfer failed"); } else { IERC20(_token).safeTransfer(_to, _amount); } } /** * @notice refresh Gamma contracts' addresses */ function refreshConfig() public { address _controller = addressBook.getController(); controller = IGammaController(_controller); address _whitelist = addressBook.getWhitelist(); whitelist = IWhitelist(_whitelist); address _calculator = addressBook.getMarginCalculator(); calculator = IMarginCalculator(_calculator); } /** * @notice get an oToken's payout in the collateral asset * @param _otoken otoken address * @param _amount amount of otoken to redeem */ function getRedeemPayout(address _otoken, uint256 _amount) public view returns (uint256) { return controller.getPayout(_otoken, _amount); } /** * @notice get amount of otoken that can be redeemed * @param _owner owner address * @param _otoken otoken address * @param _amount amount of otoken * @return amount of otoken the contract can transferFrom owner */ function getRedeemableAmount( address _owner, address _otoken, uint256 _amount ) public view returns (uint256) { uint256 ownerBalance = IERC20(_otoken).balanceOf(_owner); uint256 allowance = IERC20(_otoken).allowance(_owner, address(this)); uint256 spendable = min(ownerBalance, allowance); return min(_amount, spendable); } /** * @notice return details of a specific vault * @param _owner owner address * @param _vaultId vaultId * @return vault struct and vault type and the latest timestamp when the vault was updated */ function getVaultWithDetails(address _owner, uint256 _vaultId) public view returns ( MarginVault.Vault memory, uint256, uint256 ) { return controller.getVaultWithDetails(_owner, _vaultId); } /** * @notice return the otoken from specific vault * @param _vault vault struct * @return otoken address */ function getVaultOtoken(MarginVault.Vault memory _vault) public pure returns (address) { bool hasShort = isNotEmpty(_vault.shortOtokens); bool hasLong = isNotEmpty(_vault.longOtokens); assert(hasShort || hasLong); return hasShort ? _vault.shortOtokens[0] : _vault.longOtokens[0]; } /** * @notice return amount of collateral that can be removed from a vault * @param _vault vault struct * @param _typeVault vault type * @return excess amount and true if excess is greater than zero */ function getExcessCollateral( MarginVault.Vault memory _vault, uint256 _typeVault ) public view returns (uint256, bool) { return calculator.getExcessCollateral(_vault, _typeVault); } /** * @notice return if otoken is ready to be settled * @param _otoken otoken address * @return true if settlement is allowed */ function isSettlementAllowed(address _otoken) public view returns (bool) { return controller.isSettlementAllowed(_otoken); } /** * @notice return if this contract is Gamma operator of an address * @param _owner owner address * @return true if address(this) is operator of _owner */ function isOperatorOf(address _owner) public view returns (bool) { return controller.isOperator(_owner, address(this)); } /** * @notice return if otoken is whitelisted on Gamma * @param _otoken otoken address * @return true if isWhitelistedOtoken returns true for _otoken */ function isWhitelistedOtoken(address _otoken) public view returns (bool) { return whitelist.isWhitelistedOtoken(_otoken); } /** * @param _otoken otoken address * @return true if otoken has expired and settlement is allowed */ function hasExpiredAndSettlementAllowed(address _otoken) public view returns (bool) { bool hasExpired = block.timestamp >= IOtoken(_otoken).expiryTimestamp(); if (!hasExpired) return false; bool isAllowed = isSettlementAllowed(_otoken); if (!isAllowed) return false; return true; } /** * @notice return if specific vault exist * @param _owner owner address * @param _vaultId vaultId to check * @return true if vault exist for owner */ function isValidVaultId(address _owner, uint256 _vaultId) public view returns (bool) { uint256 vaultCounter = controller.getAccountVaultCounter(_owner); return ((_vaultId > 0) && (_vaultId <= vaultCounter)); } /** * @notice return if array is not empty * @param _array array of address to check * @return true if array length is grreater than zero & first element isn't address zero */ function isNotEmpty(address[] memory _array) private pure returns (bool) { return (_array.length > 0) && (_array[0] != address(0)); } /** * @notice return the lowest number * @param a first number * @param b second number * @return the lowest uint256 */ function min(uint256 a, uint256 b) private pure returns (uint256) { return a > b ? b : a; } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; interface IGammaRedeemerV1 { struct Order { // address of user address owner; // address of otoken to redeem address otoken; // amount of otoken to redeem uint256 amount; // vaultId of vault to settle uint256 vaultId; // true if settle vault order, else redeem otoken bool isSeller; // convert proceed to ETH, currently unused bool toETH; // fee in 1/10.000 uint256 fee; // true if order is already processed bool finished; } event OrderCreated( uint256 indexed orderId, address indexed owner, address indexed otoken ); event OrderFinished(uint256 indexed orderId, bool indexed cancelled); function createOrder( address _otoken, uint256 _amount, uint256 _vaultId ) external; function cancelOrder(uint256 _orderId) external; function shouldProcessOrder(uint256 _orderId) external view returns (bool); function processOrder(uint256 _orderId) external; function getOrdersLength() external view returns (uint256); function getOrders() external view returns (Order[] memory); function getOrder(uint256 _orderId) external view returns (Order memory); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IPokeMe { function createTask( address _execAddress, bytes4 _execSelector, address _resolverAddress, bytes calldata _resolverData ) external; function cancelTask(bytes32 _taskId) external; // function withdrawFunds(uint256 _amount) external; function getTaskId( address _taskCreator, address _execAddress, bytes4 _selector ) external pure returns (bytes32); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface ITaskTreasury { function withdrawFunds( address payable _receiver, address _token, uint256 _amount ) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IResolver { function getProcessableOrders() external returns (uint256[] memory); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IAddressBook { function getOtokenImpl() external view returns (address); function getOtokenFactory() external view returns (address); function getWhitelist() external view returns (address); function getController() external view returns (address); function getOracle() external view returns (address); function getMarginPool() external view returns (address); function getMarginCalculator() external view returns (address); function getLiquidationManager() external view returns (address); function getAddress(bytes32 _id) external view returns (address); /* Setters */ function setOtokenImpl(address _otokenImpl) external; function setOtokenFactory(address _factory) external; function setOracleImpl(address _otokenImpl) external; function setWhitelist(address _whitelist) external; function setController(address _controller) external; function setMarginPool(address _marginPool) external; function setMarginCalculator(address _calculator) external; function setLiquidationManager(address _liquidationManager) external; function setAddress(bytes32 _id, address _newImpl) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; import {Actions} from "../external/OpynActions.sol"; import {MarginVault} from "../external/OpynVault.sol"; interface IGammaController { function operate(Actions.ActionArgs[] memory _actions) external; function isSettlementAllowed(address _otoken) external view returns (bool); function isOperator(address _owner, address _operator) external view returns (bool); function getPayout(address _otoken, uint256 _amount) external view returns (uint256); function getVaultWithDetails(address _owner, uint256 _vaultId) external view returns ( MarginVault.Vault memory, uint256, uint256 ); function getAccountVaultCounter(address _accountOwner) external view returns (uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IWhitelist { function isWhitelistedOtoken(address _otoken) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; import {MarginVault} from "../external/OpynVault.sol"; interface IMarginCalculator { function getExcessCollateral( MarginVault.Vault calldata _vault, uint256 _vaultType ) external view returns (uint256 netValue, bool isExcess); } /** * SPDX-License-Identifier: UNLICENSED */ pragma solidity 0.8.0; /** * @title Actions * @author Opyn Team * @notice A library that provides a ActionArgs struct, sub types of Action structs, and functions to parse ActionArgs into specific Actions. */ library Actions { // possible actions that can be performed enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call, Liquidate } struct ActionArgs { // type of action that is being performed on the system ActionType actionType; // address of the account owner address owner; // address which we move assets from or to (depending on the action type) address secondAddress; // asset that is to be transfered address asset; // index of the vault that is to be modified (if any) uint256 vaultId; // amount of asset that is to be transfered uint256 amount; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // any other data that needs to be passed in for arbitrary function calls bytes data; } struct MintArgs { // address of the account owner address owner; // index of the vault from which the asset will be minted uint256 vaultId; // address to which we transfer the minted oTokens address to; // oToken that is to be minted address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be minted uint256 amount; } struct BurnArgs { // address of the account owner address owner; // index of the vault from which the oToken will be burned uint256 vaultId; // address from which we transfer the oTokens address from; // oToken that is to be burned address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be burned uint256 amount; } struct OpenVaultArgs { // address of the account owner address owner; // vault id to create uint256 vaultId; // vault type, 0 for spread/max loss and 1 for naked margin vault uint256 vaultType; } struct DepositArgs { // address of the account owner address owner; // index of the vault to which the asset will be added uint256 vaultId; // address from which we transfer the asset address from; // asset that is to be deposited address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be deposited uint256 amount; } struct RedeemArgs { // address to which we pay out the oToken proceeds address receiver; // oToken that is to be redeemed address otoken; // amount of oTokens that is to be redeemed uint256 amount; } struct WithdrawArgs { // address of the account owner address owner; // index of the vault from which the asset will be withdrawn uint256 vaultId; // address to which we transfer the asset address to; // asset that is to be withdrawn address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be withdrawn uint256 amount; } struct SettleVaultArgs { // address of the account owner address owner; // index of the vault to which is to be settled uint256 vaultId; // address to which we transfer the remaining collateral address to; } struct LiquidateArgs { // address of the vault owner to liquidate address owner; // address of the liquidated collateral receiver address receiver; // vault id to liquidate uint256 vaultId; // amount of debt(otoken) to repay uint256 amount; // chainlink round id uint256 roundId; } struct CallArgs { // address of the callee contract address callee; // data field for external calls bytes data; } /** * @notice parses the passed in action arguments to get the arguments for an open vault action * @param _args general action arguments structure * @return arguments for a open vault action */ function _parseOpenVaultArgs(ActionArgs memory _args) internal pure returns (OpenVaultArgs memory) { require( _args.actionType == ActionType.OpenVault, "Actions: can only parse arguments for open vault actions" ); require( _args.owner != address(0), "Actions: cannot open vault for an invalid account" ); // if not _args.data included, vault type will be 0 by default uint256 vaultType; if (_args.data.length == 32) { // decode vault type from _args.data vaultType = abi.decode(_args.data, (uint256)); } // for now we only have 2 vault types require( vaultType < 2, "Actions: cannot open vault with an invalid type" ); return OpenVaultArgs({ owner: _args.owner, vaultId: _args.vaultId, vaultType: vaultType }); } /** * @notice parses the passed in action arguments to get the arguments for a mint action * @param _args general action arguments structure * @return arguments for a mint action */ function _parseMintArgs(ActionArgs memory _args) internal pure returns (MintArgs memory) { require( _args.actionType == ActionType.MintShortOption, "Actions: can only parse arguments for mint actions" ); require( _args.owner != address(0), "Actions: cannot mint from an invalid account" ); return MintArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a burn action * @param _args general action arguments structure * @return arguments for a burn action */ function _parseBurnArgs(ActionArgs memory _args) internal pure returns (BurnArgs memory) { require( _args.actionType == ActionType.BurnShortOption, "Actions: can only parse arguments for burn actions" ); require( _args.owner != address(0), "Actions: cannot burn from an invalid account" ); return BurnArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a deposit action * @param _args general action arguments structure * @return arguments for a deposit action */ function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) { require( (_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral), "Actions: can only parse arguments for deposit actions" ); require( _args.owner != address(0), "Actions: cannot deposit to an invalid account" ); return DepositArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a withdraw action * @param _args general action arguments structure * @return arguments for a withdraw action */ function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "Actions: can only parse arguments for withdraw actions" ); require( _args.owner != address(0), "Actions: cannot withdraw from an invalid account" ); require( _args.secondAddress != address(0), "Actions: cannot withdraw to an invalid account" ); return WithdrawArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for an redeem action * @param _args general action arguments structure * @return arguments for a redeem action */ function _parseRedeemArgs(ActionArgs memory _args) internal pure returns (RedeemArgs memory) { require( _args.actionType == ActionType.Redeem, "Actions: can only parse arguments for redeem actions" ); require( _args.secondAddress != address(0), "Actions: cannot redeem to an invalid account" ); return RedeemArgs({ receiver: _args.secondAddress, otoken: _args.asset, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a settle vault action * @param _args general action arguments structure * @return arguments for a settle vault action */ function _parseSettleVaultArgs(ActionArgs memory _args) internal pure returns (SettleVaultArgs memory) { require( _args.actionType == ActionType.SettleVault, "Actions: can only parse arguments for settle vault actions" ); require( _args.owner != address(0), "Actions: cannot settle vault for an invalid account" ); require( _args.secondAddress != address(0), "Actions: cannot withdraw payout to an invalid account" ); return SettleVaultArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress }); } function _parseLiquidateArgs(ActionArgs memory _args) internal pure returns (LiquidateArgs memory) { require( _args.actionType == ActionType.Liquidate, "Actions: can only parse arguments for liquidate action" ); require( _args.owner != address(0), "Actions: cannot liquidate vault for an invalid account owner" ); require( _args.secondAddress != address(0), "Actions: cannot send collateral to an invalid account" ); require( _args.data.length == 32, "Actions: cannot parse liquidate action with no round id" ); // decode chainlink round id from _args.data uint256 roundId = abi.decode(_args.data, (uint256)); return LiquidateArgs({ owner: _args.owner, receiver: _args.secondAddress, vaultId: _args.vaultId, amount: _args.amount, roundId: roundId }); } /** * @notice parses the passed in action arguments to get the arguments for a call action * @param _args general action arguments structure * @return arguments for a call action */ function _parseCallArgs(ActionArgs memory _args) internal pure returns (CallArgs memory) { require( _args.actionType == ActionType.Call, "Actions: can only parse arguments for call actions" ); require( _args.secondAddress != address(0), "Actions: target address cannot be address(0)" ); return CallArgs({callee: _args.secondAddress, data: _args.data}); } } /** * SPDX-License-Identifier: UNLICENSED */ pragma solidity 0.8.0; /** * @title MarginVault * @author Opyn Team * @notice A library that provides the Controller with a Vault struct and the functions that manipulate vaults. * Vaults describe discrete position combinations of long options, short options, and collateral assets that a user can have. */ library MarginVault { // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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 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: UNLICENSED pragma solidity 0.8.0; interface IOtoken { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function getOtokenDetails() external view returns ( address, address, address, uint256, uint256, bool ); function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
SPDX-License-Identifier: UNLICENSED
interface IResolver { function getProcessableOrders() external returns (uint256[] memory); }
27,805
./full_match/5/0x14bB446d6648CA0a8d7d31cbCA8E639C0Be45c41/sources/localhost/contracts/storage/AddressSetStorage.sol
The index of an item in a set Returns -1 if the value is not found
function getIndexOf(bytes32 _key, address _value) override external view returns (int256) { return int256(getUint(keccak256(abi.encodePacked(_key, ".index", _value)))) - 1; }
1,881,371
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY643() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF605(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER78(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE980(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE90(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM630(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER779(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL135(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER484() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA848() 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 ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY643() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF605(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER78(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER916(_MSGSENDER484(), recipient, amount); return true; } function ALLOWANCE980(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE90(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE737(_MSGSENDER484(), spender, amount); return true; } function TRANSFERFROM630(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER916(sender, recipient, amount); _APPROVE737(sender, _MSGSENDER484(), _allowances[sender][_MSGSENDER484()].SUB312(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE56(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE737(_MSGSENDER484(), spender, _allowances[_MSGSENDER484()][spender].ADD968(addedValue)); return true; } function DECREASEALLOWANCE957(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE737(_MSGSENDER484(), spender, _allowances[_MSGSENDER484()][spender].SUB312(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER916(address sender, address recipient, uint256 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].SUB312(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD968(amount); emit TRANSFER779(sender, recipient, amount); } function _MINT550(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD968(amount); _balances[account] = _balances[account].ADD968(amount); emit TRANSFER779(address(0), account, amount); } function _BURN701(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB312(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB312(amount); emit TRANSFER779(account, address(0), amount); } function _APPROVE737(address owner, address spender, uint256 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 APPROVAL135(owner, spender, amount); } function _BURNFROM514(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN701(account, amount); _APPROVE737(account, _MSGSENDER484(), _allowances[account][_MSGSENDER484()].SUB312(amount, "ERC20: burn amount exceeds allowance")); } } library SafeMath { function ADD968(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB312(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB312(a, b, "SafeMath: subtraction overflow"); } function SUB312(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 MUL309(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV143(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV143(a, b, "SafeMath: division by zero"); } function DIV143(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; return c; } function MOD945(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD945(a, b, "SafeMath: modulo by zero"); } function MOD945(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT912(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); } function TOPAYABLE424(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE79(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER155(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.TRANSFER78.selector, to, value)); } function SAFETRANSFERFROM711(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.TRANSFERFROM630.selector, from, to, value)); } function SAFEAPPROVE528(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE980(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.APPROVE90.selector, spender, value)); } function SAFEINCREASEALLOWANCE603(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE980(address(this), spender).ADD968(value); CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.APPROVE90.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE308(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE980(address(this), spender).SUB312(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN172(token, abi.encodeWithSelector(token.APPROVE90.selector, spender, newAllowance)); } function CALLOPTIONALRETURN172(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT912(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract pLINKVault { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; struct RewardDivide { mapping (address => uint256) amount; uint256 time; } IERC20 public token = IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA); address public governance; uint256 public totalDeposit; mapping(address => uint256) public depositBalances; mapping(address => uint256) public rewardBalances; address[] public addressIndices; mapping(uint256 => RewardDivide) public _rewards; uint256 public _rewardCount = 0; event WITHDRAWN572(address indexed user, uint256 amount); //inject NONSTANDARD NAMING constructor () public { governance = msg.sender; } function BALANCE902() public view returns (uint) { //inject NONSTANDARD NAMING return token.BALANCEOF605(address(this)); } function SETGOVERNANCE662(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function DEPOSITALL531() external { //inject NONSTANDARD NAMING DEPOSIT826(token.BALANCEOF605(msg.sender)); } function DEPOSIT826(uint256 _amount) public { //inject NONSTANDARD NAMING require(_amount > 0, "can't deposit 0"); uint arrayLength = addressIndices.length; bool found = false; for (uint i = 0; i < arrayLength; i++) { if(addressIndices[i]==msg.sender){ found=true; break; } } if(!found){ addressIndices.push(msg.sender); } uint256 realAmount = _amount.MUL309(995).DIV143(1000); uint256 feeAmount = _amount.MUL309(5).DIV143(1000); address feeAddress = 0xD319d5a9D039f06858263E95235575Bb0Bd630BC; address vaultAddress = 0x32e4bD46e7cee1797b22B02c0340818B6e75C75a; // Vault7 Address token.SAFETRANSFERFROM711(msg.sender, feeAddress, feeAmount); token.SAFETRANSFERFROM711(msg.sender, vaultAddress, realAmount); totalDeposit = totalDeposit.ADD968(realAmount); depositBalances[msg.sender] = depositBalances[msg.sender].ADD968(realAmount); } function REWARD497(uint256 _amount) external { //inject NONSTANDARD NAMING require(_amount > 0, "can't reward 0"); require(totalDeposit > 0, "totalDeposit must bigger than 0"); token.SAFETRANSFERFROM711(msg.sender, address(this), _amount); uint arrayLength = addressIndices.length; for (uint i = 0; i < arrayLength; i++) { rewardBalances[addressIndices[i]] = rewardBalances[addressIndices[i]].ADD968(_amount.MUL309(depositBalances[addressIndices[i]]).DIV143(totalDeposit)); _rewards[_rewardCount].amount[addressIndices[i]] = _amount.MUL309(depositBalances[addressIndices[i]]).DIV143(totalDeposit); } _rewards[_rewardCount].time = block.timestamp; _rewardCount++; } function WITHDRAWALL236() external { //inject NONSTANDARD NAMING WITHDRAW435(rewardBalances[msg.sender]); } function WITHDRAW435(uint256 _amount) public { //inject NONSTANDARD NAMING require(_rewardCount > 0, "no reward amount"); require(_amount > 0, "can't withdraw 0"); uint256 availableWithdrawAmount = AVAILABLEWITHDRAW912(msg.sender); if (_amount > availableWithdrawAmount) { _amount = availableWithdrawAmount; } token.SAFETRANSFER155(msg.sender, _amount); rewardBalances[msg.sender] = rewardBalances[msg.sender].SUB312(_amount); emit WITHDRAWN572(msg.sender, _amount); } function AVAILABLEWITHDRAW912(address owner) public view returns(uint256){ //inject NONSTANDARD NAMING uint256 availableWithdrawAmount = rewardBalances[owner]; for (uint256 i = _rewardCount - 1; block.timestamp < _rewards[i].time.ADD968(7 days); --i) { availableWithdrawAmount = availableWithdrawAmount.SUB312(_rewards[i].amount[owner].MUL309(_rewards[i].time.ADD968(7 days).SUB312(block.timestamp)).DIV143(7 days)); if (i == 0) break; } return availableWithdrawAmount; } }
inject NONSTANDARD NAMING
function INCREASEALLOWANCE56(address spender, uint256 addedValue) public returns (bool) {
12,702,283
/** *Submitted for verification at Etherscan.io on 2021-04-08 */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view 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; } } /** * @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 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 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 { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal virtual { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Moderator is Ownable { mapping(address => bool) private _mod; event ModSet(address indexed newMod); event ModDeleted(address indexed oldMod); /** * @dev Initializes the contract setting the new Mod. */ constructor () internal { address msgSender = _msgSender(); _mod[msgSender] = true; emit ModSet(msgSender); } /** * @dev Throws if called by any account other than the mod. */ modifier onlyMod() { require(isMod(), "Moderator: caller is not the mod"); _; } /** * @dev Returns true if the caller is the current mod. */ function isMod() public view returns (bool) { address msgSender = _msgSender(); return _mod[msgSender]; } /** * @dev Set new moderator of the contract to a new account (`newMod`). * Can only be called by the current owner. */ function setNewMod(address newMod) public virtual onlyOwner { _setNewMod(newMod); } /** * @dev Delete moderator of the contract (`oldMod`). * Can only be called by the current owner. */ function deleteMod(address oldMod) public virtual onlyOwner { _deleteMod(oldMod); } /** * @dev Set new moderator of the contract to a new account (`newMod`). */ function _setNewMod(address newMod) internal virtual { require(newMod != address(0), "Moderator: new mod is the zero address"); emit ModSet(newMod); _mod[newMod] = true; } /** * @dev Delete moderator of the contract t (`oldMod`). */ function _deleteMod(address oldMod) internal virtual { require(oldMod != address(0), "Moderator: old Mod is the zero address"); emit ModDeleted(oldMod); _mod[oldMod] = false; } } /** * @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 Moderator { bool private _paused; address private _pauser; /** * @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); /** * @dev Emitted when the pauser is transferred by a owner. */ event PauserTransferred(address indexed previousPauser, address indexed newPauser); /** * @dev Initializes the contract setting the deployer as the initial pauser. * * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor (address pauser) internal { _pauser = pauser; _paused = false; emit PauserTransferred(address(0), pauser); } /** * @dev Returns the address of the current pauser. */ function pauser() public view returns (address) { return _pauser; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyPauser() { require(isPauser(), "Pausable: caller is not the pauser"); _; } /** * @dev Returns true if the caller is the current pauser. */ function isPauser() public view returns (bool) { return _msgSender() == _pauser; } /** * @dev Transfers pauser of the contract to a new account (`newPauser`). * Can only be called by the current owner. */ function setNewPauser(address newPauser) public virtual onlyOwner { _transferPauser(newPauser); } /** * @dev Transfers pauser of the contract to a new account (`newPauser`). */ function _transferPauser(address newPauser) internal virtual { require(newPauser != address(0), "Pausable: new pauser is the zero address"); emit PauserTransferred(_pauser, newPauser); _pauser = newPauser; } /** * @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() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @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; } } contract GHTVerificationService is Pausable { using SafeMath for uint256; mapping (address => bool) private _whiteListAddress; mapping (address => uint256) private _GHTAmount; IERC20 GHT; /** * @dev Emitted when the user's address is locked or unlocked by a owner (`account`). */ event SetWhiteListAddress(address indexed account, bool flag); event DepositGHT(address indexed account, uint256 amount); event GHTWithdrawalConfirmation(address indexed account, address indexed to, uint256 amount); event DecreaseGHTAmount(address indexed account, uint256 amount); constructor(address pauser, address _ght) public Pausable(pauser){ address msgSender = _msgSender(); setWhiteListAddress(msgSender,true); GHT = IERC20(_ght); } /** * @dev Returns GHT amount of `account` sent to contract. */ function getGHTAmount(address account) public view returns (uint256) { return _GHTAmount[account]; } /** * @dev User deposit to Wallet. */ function depositGHT(uint256 amount, address user) public whenNotPaused { GHT.transferFrom(user,address(this),amount); _GHTAmount[user] = _GHTAmount[user].add(amount); emit DepositGHT(user, amount); } /** * @dev User withdraw GHT from Wallet. */ function confirmedGHTWithdrawal(uint256 amount, address whitelistAddress, address to, uint256 update) public onlyMod whenNotPaused { //require(_whiteListAddress[user]); //require(_GHTAmount[whitelistAddress] >= amount); if(update!=0) _GHTAmount[whitelistAddress] = update; GHT.transfer(to,amount); _GHTAmount[whitelistAddress] = _GHTAmount[whitelistAddress].sub(amount); assert(_GHTAmount[whitelistAddress]>=0); emit GHTWithdrawalConfirmation(whitelistAddress, to, amount); } /** * @dev Decrease GHT in wallet cz used. */ function decreaseGHTAmount(uint256 amount, address user) public onlyMod whenNotPaused { _GHTAmount[user] = _GHTAmount[user].sub(amount); assert(_GHTAmount[user]>=0); emit DecreaseGHTAmount(user, amount); } /** * @dev Set the user's address to lock or unlock. */ function setWhiteListAddress(address account, bool flag) public onlyMod { _setWhiteListAddress(account, flag); emit SetWhiteListAddress(account, flag); } /** * @dev Returns the state `account`. */ function getWhiteListAddress(address account) public view returns (bool) { return _whiteListAddress[account]; } /** * @dev Set the user's address to lock or unlock. */ function _setWhiteListAddress(address account, bool flag) internal { _whiteListAddress[account] = flag; } /** * @dev Pausese contract. * * See {Pausable-_pause}. */ function pauseContract() public virtual onlyPauser { _pause(); } /** * @dev Unpauses contract. * * See {Pausable-_unpause}. */ function unpauseContract() public virtual onlyPauser { _unpause(); } }
Set new moderator of the contract to a new account (`newMod`). Can only be called by the current owner./
function setNewMod(address newMod) public virtual onlyOwner { _setNewMod(newMod); }
6,530,424
/** *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); } }
The same as above only pass an extra parameter pepeId Pepe to cozy with _auction Address of the auction contract _cozyCandidate Pepe to approve and cozy with _candidateAsFather Use the candidate as father or not _affiliate Address to set as affiliate/ solhint-disable-next-line max-line-length 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; }
10,871,779
/** * Copyright 2017-2019, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.8; pragma experimental ABIEncoderV2; import "./AdvancedToken.sol"; interface IBZxSettings { function pushLoanOrderOnChain( address[8] calldata orderAddresses, uint256[11] calldata orderValues, bytes calldata oracleData, bytes calldata signature) external returns (bytes32); // loanOrderHash function setLoanOrderDesc( bytes32 loanOrderHash, string calldata desc) external returns (bool); function oracleAddresses( address oracleAddress) external view returns (address); } interface IBZxOracleSettings { function tradeUserAsset( address sourceTokenAddress, address destTokenAddress, address receiverAddress, address returnToSenderAddress, uint256 sourceTokenAmount, uint256 maxDestTokenAmount, uint256 minConversionRate) external returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed); function interestFeePercent() external view returns (uint256); } contract LoanTokenSettings is AdvancedToken { using SafeMath for uint256; modifier onlyAdmin() { require(msg.sender == address(this) || msg.sender == owner, "unauthorized"); _; } function() external { revert("invalid"); } function initLeverage( uint256[4] memory orderParams) // leverageAmount, initialMarginAmount, maintenanceMarginAmount, maxDurationUnixTimestampSec public onlyAdmin { require(loanOrderHashes[orderParams[0]] == 0); address[8] memory orderAddresses = [ address(this), // makerAddress loanTokenAddress, // loanTokenAddress loanTokenAddress, // interestTokenAddress (same as loanToken) address(0), // collateralTokenAddress address(0), // feeRecipientAddress bZxOracle, // (leave as original value) address(0), // takerAddress address(0) // tradeTokenAddress ]; uint256[11] memory orderValues = [ 0, // loanTokenAmount 0, // interestAmountPerDay orderParams[1], // initialMarginAmount, orderParams[2], // maintenanceMarginAmount, 0, // lenderRelayFee 0, // traderRelayFee orderParams[3], // maxDurationUnixTimestampSec, 0, // expirationUnixTimestampSec 0, // makerRole (0 = lender) 0, // withdrawOnOpen uint(keccak256(abi.encodePacked(msg.sender, block.timestamp))) // salt ]; bytes32 loanOrderHash = IBZxSettings(bZxContract).pushLoanOrderOnChain( orderAddresses, orderValues, abi.encodePacked(address(this)), // oracleData -> closeLoanNotifier "" ); IBZxSettings(bZxContract).setLoanOrderDesc( loanOrderHash, name ); loanOrderData[loanOrderHash] = LoanData({ loanOrderHash: loanOrderHash, leverageAmount: orderParams[0], initialMarginAmount: orderParams[1], maintenanceMarginAmount: orderParams[2], maxDurationUnixTimestampSec: orderParams[3], index: leverageList.length }); loanOrderHashes[orderParams[0]] = loanOrderHash; leverageList.push(orderParams[0]); } function removeLeverage( uint256 leverageAmount) public onlyAdmin { bytes32 loanOrderHash = loanOrderHashes[leverageAmount]; require(loanOrderHash != 0); if (leverageList.length > 1) { uint256 index = loanOrderData[loanOrderHash].index; leverageList[index] = leverageList[leverageList.length - 1]; loanOrderData[loanOrderHashes[leverageList[index]]].index = index; } leverageList.length--; delete loanOrderHashes[leverageAmount]; delete loanOrderData[loanOrderHash]; } function migrateLeverage( uint256 oldLeverageValue, uint256 newLeverageValue) public onlyAdmin { require(oldLeverageValue != newLeverageValue); bytes32 loanOrderHash = loanOrderHashes[oldLeverageValue]; LoanData storage loanData = loanOrderData[loanOrderHash]; require(loanData.initialMarginAmount != 0); delete loanOrderHashes[oldLeverageValue]; leverageList[loanData.index] = newLeverageValue; loanData.leverageAmount = newLeverageValue; loanOrderHashes[newLeverageValue] = loanOrderHash; } // These params should be percentages represented like so: 5% = 5000000000000000000 // rateMultiplier + baseRate can't exceed 100% function setDemandCurve( uint256 _baseRate, uint256 _rateMultiplier, uint256 _lowUtilBaseRate, uint256 _lowUtilRateMultiplier) public onlyAdmin { require(_rateMultiplier.add(_baseRate) <= 10**20); require(_lowUtilRateMultiplier.add(_lowUtilBaseRate) <= 10**20); baseRate = _baseRate; rateMultiplier = _rateMultiplier; //keccak256("iToken_LowUtilBaseRate") bytes32 slotLowUtilBaseRate = 0x3d82e958c891799f357c1316ae5543412952ae5c423336f8929ed7458039c995; //keccak256("iToken_LowUtilRateMultiplier") bytes32 slotLowUtilRateMultiplier = 0x2b4858b1bc9e2d14afab03340ce5f6c81b703c86a0c570653ae586534e095fb1; assembly { sstore(slotLowUtilBaseRate, _lowUtilBaseRate) sstore(slotLowUtilRateMultiplier, _lowUtilRateMultiplier) } } function setInterestFeePercent( uint256 _newRate) public onlyAdmin { require(_newRate <= 10**20); spreadMultiplier = SafeMath.sub(10**20, _newRate); } function setBZxOracle( address _addr) public onlyAdmin { bZxOracle = _addr; } function setTokenizedRegistry( address _addr) public onlyAdmin { tokenizedRegistry = _addr; } function setWethContract( address _addr) public onlyAdmin { wethContract = _addr; } function recoverEther( address payable receiver, uint256 amount) public onlyAdmin { uint256 balance = address(this).balance; if (balance < amount) amount = balance; receiver.transfer(amount); } function recoverToken( address tokenAddress, address receiver, uint256 amount) public onlyAdmin { require(tokenAddress != loanTokenAddress, "invalid token"); ERC20 token = ERC20(tokenAddress); uint256 balance = token.balanceOf(address(this)); if (balance < amount) amount = balance; require(token.transfer( receiver, amount), "transfer failed" ); } function swapIntoLoanToken( address sourceTokenAddress, uint256 amount) public onlyAdmin { require(sourceTokenAddress != loanTokenAddress, "invalid token"); address oracleAddress = IBZxSettings(bZxContract).oracleAddresses(bZxOracle); uint256 balance = ERC20(sourceTokenAddress).balanceOf(address(this)); if (balance < amount) amount = balance; uint256 tempAllowance = ERC20(sourceTokenAddress).allowance(address(this), oracleAddress); if (tempAllowance < amount) { if (tempAllowance != 0) { // reset approval to 0 require(ERC20(sourceTokenAddress).approve(oracleAddress, 0), "token approval reset failed"); } require(ERC20(sourceTokenAddress).approve(oracleAddress, MAX_UINT), "token approval failed"); } IBZxOracleSettings(oracleAddress).tradeUserAsset( sourceTokenAddress, loanTokenAddress, address(this), // receiverAddress address(this), // returnToSenderAddress amount, // sourceTokenAmount MAX_UINT, // maxDestTokenAmount 0 // minConversionRate ); } function initialize( address _bZxContract, address _bZxVault, address _bZxOracle, address _wethContract, address _loanTokenAddress, address _tokenizedRegistry, string memory _name, string memory _symbol) public onlyAdmin { require (!isInitialized_); bZxContract = _bZxContract; bZxVault = _bZxVault; bZxOracle = _bZxOracle; wethContract = _wethContract; loanTokenAddress = _loanTokenAddress; tokenizedRegistry = _tokenizedRegistry; name = _name; symbol = _symbol; decimals = EIP20(loanTokenAddress).decimals(); spreadMultiplier = SafeMath.sub(10**20, IBZxOracleSettings(_bZxOracle).interestFeePercent()); initialPrice = 10**18; // starting price of 1 isInitialized_ = true; } }
reset approval to 0
function swapIntoLoanToken( address sourceTokenAddress, uint256 amount) public onlyAdmin { require(sourceTokenAddress != loanTokenAddress, "invalid token"); address oracleAddress = IBZxSettings(bZxContract).oracleAddresses(bZxOracle); uint256 balance = ERC20(sourceTokenAddress).balanceOf(address(this)); if (balance < amount) amount = balance; uint256 tempAllowance = ERC20(sourceTokenAddress).allowance(address(this), oracleAddress); if (tempAllowance < amount) { if (tempAllowance != 0) { require(ERC20(sourceTokenAddress).approve(oracleAddress, 0), "token approval reset failed"); } require(ERC20(sourceTokenAddress).approve(oracleAddress, MAX_UINT), "token approval failed"); } IBZxOracleSettings(oracleAddress).tradeUserAsset( sourceTokenAddress, loanTokenAddress, ); }
1,826,999
./partial_match/8453/0x6c0B6cDBf6e1910CD5821440872a6C6145526658/sources/BaseBridge.sol
_path = abi.encodePacked(remoteAddress, localAddress) this function set the trusted path for the cross-chain communication
function setTrustedRemote( uint16 _remoteChainId, bytes calldata _path ) external onlyOwner { trustedRemoteLookup[_remoteChainId] = _path; emit SetTrustedRemote(_remoteChainId, _path); }
16,692,352
./full_match/3/0xA60A90D0FCFc3D1446355BF505B73756EE119B6B/sources/browser/IllustCustody.sol
req asset finalizedreq payment incompletereq msg sender is the winnerreq user sends enough fundscreate Ainsoph refget total royalty priceget erc721 priceget tokenPercentageif its the first saleno longer first saleget royalty percentageget royalty priceif this is NOT the first saleget royalty pricecheck if this will use ERC priceif the ERC price is auto setset erc price to total royalties to be collected else you are adding on to ercPriceget tokenPrice, and royalty recieversget percentage for tokenget percentage for rr1calculate how much reciever 1 gets payedcalculate how much reciever 2 gets payedcheck if there is a different set of recievers listed on this smart contract
function pay(uint256 asset) public payable{ require(winnigBids[asset].enabled==true, "The seller of this item has not finalized this price, please wait..."); require(winnigBids[asset].complete==false, "This auction has ended"); require(winnigBids[asset].winner==msg.sender, "Asset is not for sale, or this is not the winning address"); require(msg.value>=winnigBids[asset].price, "Please send more eth"); Ainsoph AinsophContract=Ainsoph(tokenContract); uint256 royaltyPrice; uint256 tokenPrice; if(assets[asset].firstSale==true){ assets[asset].firstSale=false; uint8 royaltyPercentage=(assets[asset].royaltyPercentage==0)?defaultPercentage:assets[asset].initialRoyaltyPercentage; royaltyPrice = (winnigBids[asset].price*royaltyPercentage)/100; uint8 royaltyPercentage=(assets[asset].royaltyPercentage==0)?defaultPercentage:assets[asset].royaltyPercentage; royaltyPrice = (winnigBids[asset].price*royaltyPercentage)/100; } if(assets[asset].autoPrice){ tokenPrice=royaltyPrice; AinsophContract.setTokenPrice(tokenPrice, asset); (address payable minter, address payable rr1, address payable rr2, uint8 percentage, uint256 listedTokenPrice)=AinsophContract.piecelist(asset); tokenPrice=listedTokenPrice; uint256 remainingPayment=royaltyPrice-tokenPrice; uint256 rr1Percentage = (assets[asset].royaltySplitPercentage==0)?defaultSplitPercentage:assets[asset].royaltySplitPercentage; uint256 rr1Payment = ((remainingPayment * rr1Percentage) / 100); uint256 rr2Payment = remainingPayment-rr1Payment; if(assets[asset].royaltyReceiver1!=address(0)){ rr1=assets[asset].royaltyReceiver1; rr1=defaultRoyaltyReceiver1; } if(assets[asset].royaltyReceiver2!=address(0)){ rr2=assets[asset].royaltyReceiver2; rr1=defaultRoyaltyReceiver2; } rr2.transfer(rr2Payment); } }
8,212,825
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Pausable.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; error InvalidMint(); error InvalidApproval(); error NoMaxSupply(); contract LegacyOfPolMedinaJr is Ownable, ReentrancyGuard, ERC1155Burnable, ERC1155Pausable, ERC1155Supply { using Strings for uint256; // ============ Constants ============ //royalty percent uint256 public constant ROYALTY_PERCENT = 1000; //royalty recipient PaymentSplitter public immutable ROYALTY_RECIPIENT; //bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; // ============ Structs ============ struct Token { uint256 maxSupply; uint256 mintPrice; bool active; } // ============ Storage ============ //mapping of token id to token info (max, price) mapping(uint256 => Token) private _tokens; //the contract metadata string private _contractURI; //a flag that allows NFTs to be listed on marketplaces //this helps to prevent people from listing at a lower //price during the whitelist bool approvable = false; // ============ Modifier ============ modifier canApprove { if (!approvable) revert InvalidApproval(); _; } // ============ Deploy ============ /** * @dev Sets the base token uri */ constructor( string memory contract_uri, string memory token_uri, address[] memory payees, uint256[] memory shares ) ERC1155(token_uri) { ROYALTY_RECIPIENT = new PaymentSplitter(payees, shares); _contractURI = contract_uri; } // ============ Read Methods ============ /** * @dev Returns the contract URI */ function contractURI() external view returns(string memory) { return _contractURI; } /** * @dev Returns true if the token exists */ function exists(uint256 id) public view override returns(bool) { return _tokens[id].active; } /** * @dev Get the maximum supply for a token */ function maxSupply(uint256 id) public view returns(uint256) { return _tokens[id].maxSupply; } /** * @dev Get the mint supply for a token */ function mintPrice(uint256 id) public view returns(uint256) { return _tokens[id].mintPrice; } /** * @dev Returns the name */ function name() external pure returns(string memory) { return "The Legacy of Pol Medina Jr."; } /** * @dev Get the remaining supply for a token */ function remainingSupply(uint256 id) public view returns(uint256) { uint256 max = maxSupply(id); if (max == 0) revert NoMaxSupply(); return max - totalSupply(id); } /** * @dev implements ERC2981 `royaltyInfo()` */ function royaltyInfo(uint256, uint256 salePrice) external view returns(address receiver, uint256 royaltyAmount) { return ( payable(address(ROYALTY_RECIPIENT)), (salePrice * ROYALTY_PERCENT) / 10000 ); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns(bool) { //support ERC2981 if (interfaceId == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(interfaceId); } /** * @dev Returns the symbol */ function symbol() external pure returns(string memory) { return "PMJR"; } /** * @dev Returns the max and price for a token */ function tokenInfo(uint256 id) external view returns(uint256 max, uint256 price, uint256 remaining) { return ( _tokens[id].maxSupply, _tokens[id].mintPrice, remainingSupply(id) ); } /** * @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 id) public view virtual override returns(string memory) { if (exists(id)) { return string(abi.encodePacked(super.uri(id), "/", id.toString(), ".json")); } return string(abi.encodePacked(super.uri(id), "/{id}.json")); } // ============ Write Methods ============ /** * @dev Allows anyone to mint by purchasing */ function buy(address to, uint256 id, uint256 quantity, bytes memory proof) external payable nonReentrant { //make sure the minter signed this off if (ECDSA.recover( ECDSA.toEthSignedMessageHash( keccak256(abi.encodePacked("authorized", to)) ), proof ) != owner()) revert InvalidMint(); //get price uint256 price = mintPrice(id) * quantity; //if there is a price and the amount sent is less than if(price == 0 || msg.value < price) revert InvalidMint(); //we are okay to mint _mintSupply(to, id, quantity); } /** * @dev Check if can approve before approving */ function setApprovalForAll(address operator, bool approved) public virtual override canApprove { super.setApprovalForAll(operator, approved); } // ============ Admin Methods ============ /** * @dev Adds a token that can be minted */ function addToken(uint256 id, uint256 max, uint256 price, uint8 prizes) public onlyOwner { _tokens[id] = Token(max, price, true); if (prizes > 0) { _mintSupply(_msgSender(), id, prizes); } } /** * @dev Allows admin to mint */ function mint(address to, uint256 id, uint256 quantity) public onlyOwner { _mintSupply(to, id, quantity); } /** * @dev Allows admin to update URI */ function updateURI(string memory newuri) public onlyOwner { _setURI(newuri); } /** * @dev Sends the entire contract balance to a `recipient`. * This also enables NFTs to be listable on marketplaces. */ function withdraw(address recipient) external virtual nonReentrant onlyOwner { //now make approvable, it's only here we will //set this so it's kind of immutable (a one time deal) if (!approvable) { approvable = true; } Address.sendValue(payable(recipient), address(this).balance); } /** * @dev This contract should not hold any tokens in the first place. * This method exists to transfer out tokens funds. */ function withdraw(IERC20 erc20, address recipient, uint256 amount) external virtual nonReentrant onlyOwner { SafeERC20.safeTransfer(erc20, recipient, amount); } // ============ Internal Methods ============ /** * @dev Mint token considering max supply */ function _mintSupply(address to, uint256 id, uint256 quantity) internal { //if the id does not exists if (!exists(id)) revert InvalidMint(); //get max and calculated supply uint256 max = maxSupply(id); uint256 supply = totalSupply(id) + quantity; //if there is a max supply and it was exceeded if(max > 0 && supply > max) revert InvalidMint(); //we are okay to mint _mint(to, id, quantity, ""); } // ============ Overrides ============ /** * @dev Describes linear override for `_beforeTokenTransfer` used in * both `ERC721` and `ERC721Pausable` */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Pausable, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Burnable.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Pausable.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC1155 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. * * _Available since v3.1._ */ abstract contract ERC1155Pausable is ERC1155, Pausable { /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. 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 // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
See {IERC165-supportsInterface}./support ERC2981
function supportsInterface(bytes4 interfaceId) public view virtual override returns(bool) { if (interfaceId == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(interfaceId); }
14,365,836
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './interfaces/IAtlantisV1Pool.sol'; import './interfaces/IAtlantisV1Factory.sol'; import './interfaces/IAtlantisV1PoolDeployer.sol'; import './interfaces/IERC20Minimal.sol'; import './interfaces/callback/IAtlantisV1MintCallback.sol'; import './interfaces/callback/IAtlantisV1SwapCallback.sol'; import './interfaces/callback/IAtlantisV1FlashCallback.sol'; import './NoDelegateCall.sol'; import './libraries/Tick.sol'; import './libraries/TickMath.sol'; import './libraries/Oracle.sol'; import './libraries/Position.sol'; import './libraries/SqrtPriceMath.sol'; import './libraries/TransferHelper.sol'; import './libraries/TickBitmap.sol'; contract AtlantisV1Pool is IAtlantisV1Pool, NoDelegateCall { using LowGasSafeMath for uint256; using LowGasSafeMath for int256; using SafeCast for uint256; using SafeCast for int256; using Tick for mapping(int24 => Tick.Info); using TickBitmap for mapping(int16 => uint256); using Position for mapping(bytes32 => Position.Info); using Position for Position.Info; using Oracle for Oracle.Observation[65535]; /// @inheritdoc IAtlantisV1PoolImmutables address public immutable override factory; /// @inheritdoc IAtlantisV1PoolImmutables address public immutable override token0; /// @inheritdoc IAtlantisV1PoolImmutables address public immutable override token1; /// @inheritdoc IAtlantisV1PoolImmutables uint24 public immutable override fee; /// @inheritdoc IAtlantisV1PoolImmutables int24 public immutable override tickSpacing; /// @inheritdoc IAtlantisV1PoolImmutables uint128 public immutable override maxLiquidityPerTick; struct Slot0 { // the current price uint160 sqrtPriceX96; // the current tick int24 tick; // the most-recently updated index of the observations array uint16 observationIndex; // the current maximum number of observations that are being stored uint16 observationCardinality; // the next maximum number of observations to store, triggered in observations.write uint16 observationCardinalityNext; // the current protocol fee as a percentage of the swap fee taken on withdrawal // represented as an integer denominator (1/x)% uint8 feeProtocol; // whether the pool is locked bool unlocked; } /// @inheritdoc IAtlantisV1PoolState Slot0 public override slot0; /// @inheritdoc IAtlantisV1PoolState uint256 public override feeGrowthGlobal0X128; /// @inheritdoc IAtlantisV1PoolState uint256 public override feeGrowthGlobal1X128; // accumulated protocol fees in token0/token1 units struct ProtocolFees { uint128 token0; uint128 token1; } /// @inheritdoc IAtlantisV1PoolState ProtocolFees public override protocolFees; /// @inheritdoc IAtlantisV1PoolState uint128 public override liquidity; /// @inheritdoc IAtlantisV1PoolState mapping(int24 => Tick.Info) public override ticks; /// @inheritdoc IAtlantisV1PoolState mapping(int16 => uint256) public override tickBitmap; /// @inheritdoc IAtlantisV1PoolState mapping(bytes32 => Position.Info) public override positions; /// @inheritdoc IAtlantisV1PoolState Oracle.Observation[65535] public override observations; /// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance /// to a function before the pool is initialized. The reentrancy guard is required throughout the contract because /// we use balance checks to determine the payment status of interactions such as mint, swap and flash. modifier lock() { require(slot0.unlocked, 'LOK'); slot0.unlocked = false; _; slot0.unlocked = true; } modifier onlyFactoryOwner() { require(msg.sender == IAtlantisV1Factory(factory).owner()); _; } constructor() { int24 _tickSpacing; (factory, token0, token1, fee, _tickSpacing) = IAtlantisV1PoolDeployer(msg.sender).parameters(); tickSpacing = _tickSpacing; maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(_tickSpacing); } /// @dev Common checks for valid tick inputs. function checkTicks(int24 tickLower, int24 tickUpper) private pure { require(tickLower < tickUpper, 'TLU'); require(tickLower >= TickMath.MIN_TICK, 'TLM'); require(tickUpper <= TickMath.MAX_TICK, 'TUM'); } /// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. function _blockTimestamp() internal view virtual returns (uint32) { return uint32(block.timestamp); // truncation is desired } /// @dev Get the pool's balance of token0 /// @dev This function is gas optimized to avoid a redundant extcodesize check /// in addition to the returndatasize check function balance0() private view returns (uint256) { (bool success, bytes memory data) = token0.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this))); require(success && data.length >= 32); return abi.decode(data, (uint256)); } /// @dev Get the pool's balance of token1 /// @dev This function is gas optimized to avoid a redundant extcodesize check /// in addition to the returndatasize check function balance1() private view returns (uint256) { (bool success, bytes memory data) = token1.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this))); require(success && data.length >= 32); return abi.decode(data, (uint256)); } /// @inheritdoc IAtlantisV1PoolDerivedState function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view override noDelegateCall returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside) { checkTicks(tickLower, tickUpper); int56 tickCumulativeLower; int56 tickCumulativeUpper; uint160 secondsPerLiquidityOutsideLowerX128; uint160 secondsPerLiquidityOutsideUpperX128; uint32 secondsOutsideLower; uint32 secondsOutsideUpper; { Tick.Info storage lower = ticks[tickLower]; Tick.Info storage upper = ticks[tickUpper]; bool initializedLower; (tickCumulativeLower, secondsPerLiquidityOutsideLowerX128, secondsOutsideLower, initializedLower) = ( lower.tickCumulativeOutside, lower.secondsPerLiquidityOutsideX128, lower.secondsOutside, lower.initialized ); require(initializedLower); bool initializedUpper; (tickCumulativeUpper, secondsPerLiquidityOutsideUpperX128, secondsOutsideUpper, initializedUpper) = ( upper.tickCumulativeOutside, upper.secondsPerLiquidityOutsideX128, upper.secondsOutside, upper.initialized ); require(initializedUpper); } Slot0 memory _slot0 = slot0; if (_slot0.tick < tickLower) { return ( tickCumulativeLower - tickCumulativeUpper, secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128, secondsOutsideLower - secondsOutsideUpper ); } else if (_slot0.tick < tickUpper) { uint32 time = _blockTimestamp(); (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) = observations.observeSingle( time, 0, _slot0.tick, _slot0.observationIndex, liquidity, _slot0.observationCardinality ); return ( tickCumulative - tickCumulativeLower - tickCumulativeUpper, secondsPerLiquidityCumulativeX128 - secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128, time - secondsOutsideLower - secondsOutsideUpper ); } else { return ( tickCumulativeUpper - tickCumulativeLower, secondsPerLiquidityOutsideUpperX128 - secondsPerLiquidityOutsideLowerX128, secondsOutsideUpper - secondsOutsideLower ); } } /// @inheritdoc IAtlantisV1PoolDerivedState function observe(uint32[] calldata secondsAgos) external view override noDelegateCall returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) { return observations.observe( _blockTimestamp(), secondsAgos, slot0.tick, slot0.observationIndex, liquidity, slot0.observationCardinality ); } /// @inheritdoc IAtlantisV1PoolActions function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external override lock noDelegateCall { uint16 observationCardinalityNextOld = slot0.observationCardinalityNext; // for the event uint16 observationCardinalityNextNew = observations.grow(observationCardinalityNextOld, observationCardinalityNext); slot0.observationCardinalityNext = observationCardinalityNextNew; if (observationCardinalityNextOld != observationCardinalityNextNew) emit IncreaseObservationCardinalityNext(observationCardinalityNextOld, observationCardinalityNextNew); } /// @inheritdoc IAtlantisV1PoolActions /// @dev not locked because it initializes unlocked function initialize(uint160 sqrtPriceX96) external override { require(slot0.sqrtPriceX96 == 0, 'AI'); int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96); (uint16 cardinality, uint16 cardinalityNext) = observations.initialize(_blockTimestamp()); slot0 = Slot0({ sqrtPriceX96: sqrtPriceX96, tick: tick, observationIndex: 0, observationCardinality: cardinality, observationCardinalityNext: cardinalityNext, feeProtocol: 0, unlocked: true }); emit Initialize(sqrtPriceX96, tick); } struct ModifyPositionParams { // the address that owns the position address owner; // the lower and upper tick of the position int24 tickLower; int24 tickUpper; // any change in liquidity int128 liquidityDelta; } /// @dev Effect some changes to a position /// @param params the position details and the change to the position's liquidity to effect /// @return position a storage pointer referencing the position with the given owner and tick range /// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient /// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient function _modifyPosition(ModifyPositionParams memory params) private noDelegateCall returns ( Position.Info storage position, int256 amount0, int256 amount1 ) { checkTicks(params.tickLower, params.tickUpper); Slot0 memory _slot0 = slot0; // SLOAD for gas optimization position = _updatePosition( params.owner, params.tickLower, params.tickUpper, params.liquidityDelta, _slot0.tick ); if (params.liquidityDelta != 0) { if (_slot0.tick < params.tickLower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it amount0 = SqrtPriceMath.getAmount0Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); } else if (_slot0.tick < params.tickUpper) { // current tick is inside the passed range uint128 liquidityBefore = liquidity; // SLOAD for gas optimization // write an oracle entry (slot0.observationIndex, slot0.observationCardinality) = observations.write( _slot0.observationIndex, _blockTimestamp(), _slot0.tick, liquidityBefore, _slot0.observationCardinality, _slot0.observationCardinalityNext ); amount0 = SqrtPriceMath.getAmount0Delta( _slot0.sqrtPriceX96, TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); amount1 = SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), _slot0.sqrtPriceX96, params.liquidityDelta ); liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it amount1 = SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); } } } /// @dev Gets and updates a position with the given liquidity delta /// @param owner the owner of the position /// @param tickLower the lower tick of the position's tick range /// @param tickUpper the upper tick of the position's tick range /// @param tick the current tick, passed to avoid sloads function _updatePosition( address owner, int24 tickLower, int24 tickUpper, int128 liquidityDelta, int24 tick ) private returns (Position.Info storage position) { position = positions.get(owner, tickLower, tickUpper); uint256 _feeGrowthGlobal0X128 = feeGrowthGlobal0X128; // SLOAD for gas optimization uint256 _feeGrowthGlobal1X128 = feeGrowthGlobal1X128; // SLOAD for gas optimization // if we need to update the ticks, do it bool flippedLower; bool flippedUpper; if (liquidityDelta != 0) { uint32 time = _blockTimestamp(); (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) = observations.observeSingle( time, 0, slot0.tick, slot0.observationIndex, liquidity, slot0.observationCardinality ); flippedLower = ticks.update( tickLower, tick, liquidityDelta, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128, secondsPerLiquidityCumulativeX128, tickCumulative, time, false, maxLiquidityPerTick ); flippedUpper = ticks.update( tickUpper, tick, liquidityDelta, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128, secondsPerLiquidityCumulativeX128, tickCumulative, time, true, maxLiquidityPerTick ); if (flippedLower) { tickBitmap.flipTick(tickLower, tickSpacing); } if (flippedUpper) { tickBitmap.flipTick(tickUpper, tickSpacing); } } (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = ticks.getFeeGrowthInside(tickLower, tickUpper, tick, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128); position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128); // clear any tick data that is no longer needed if (liquidityDelta < 0) { if (flippedLower) { ticks.clear(tickLower); } if (flippedUpper) { ticks.clear(tickUpper); } } } /// @inheritdoc IAtlantisV1PoolActions /// @dev noDelegateCall is applied indirectly via _modifyPosition function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external override lock returns (uint256 amount0, uint256 amount1) { require(amount > 0); (, int256 amount0Int, int256 amount1Int) = _modifyPosition( ModifyPositionParams({ owner: recipient, tickLower: tickLower, tickUpper: tickUpper, liquidityDelta: int128(amount) }) ); amount0 = uint256(amount0Int); amount1 = uint256(amount1Int); uint256 balance0Before; uint256 balance1Before; if (amount0 > 0) balance0Before = balance0(); if (amount1 > 0) balance1Before = balance1(); IAtlantisV1MintCallback(msg.sender).AtlantisV1MintCallback(amount0, amount1, data); if (amount0 > 0) require(balance0Before.add(amount0) <= balance0(), 'M0'); if (amount1 > 0) require(balance1Before.add(amount1) <= balance1(), 'M1'); emit Mint(msg.sender, recipient, tickLower, tickUpper, amount, amount0, amount1); } /// @inheritdoc IAtlantisV1PoolActions function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external override lock returns (uint128 amount0, uint128 amount1) { // we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1} Position.Info storage position = positions.get(msg.sender, tickLower, tickUpper); amount0 = amount0Requested > position.tokensOwed0 ? position.tokensOwed0 : amount0Requested; amount1 = amount1Requested > position.tokensOwed1 ? position.tokensOwed1 : amount1Requested; if (amount0 > 0) { position.tokensOwed0 -= amount0; TransferHelper.safeTransfer(token0, recipient, amount0); } if (amount1 > 0) { position.tokensOwed1 -= amount1; TransferHelper.safeTransfer(token1, recipient, amount1); } emit Collect(msg.sender, recipient, tickLower, tickUpper, amount0, amount1); } /// @inheritdoc IAtlantisV1PoolActions /// @dev noDelegateCall is applied indirectly via _modifyPosition function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external override lock returns (uint256 amount0, uint256 amount1) { (Position.Info storage position, int256 amount0Int, int256 amount1Int) = _modifyPosition( ModifyPositionParams({ owner: msg.sender, tickLower: tickLower, tickUpper: tickUpper, liquidityDelta: -int128(amount) }) ); amount0 = uint256(-amount0Int); amount1 = uint256(-amount1Int); if (amount0 > 0 || amount1 > 0) { (position.tokensOwed0, position.tokensOwed1) = ( position.tokensOwed0 + uint128(amount0), position.tokensOwed1 + uint128(amount1) ); } emit Burn(msg.sender, tickLower, tickUpper, amount, amount0, amount1); } /// @inheritdoc IAtlantisV1PoolActions function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external override noDelegateCall returns (int256 amount0, int256 amount1) {} /// @inheritdoc IAtlantisV1PoolActions function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external override lock noDelegateCall {} }
@inheritdoc IAtlantisV1PoolActions we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1}
function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external override lock returns (uint128 amount0, uint128 amount1) { Position.Info storage position = positions.get(msg.sender, tickLower, tickUpper); amount0 = amount0Requested > position.tokensOwed0 ? position.tokensOwed0 : amount0Requested; amount1 = amount1Requested > position.tokensOwed1 ? position.tokensOwed1 : amount1Requested; if (amount0 > 0) { position.tokensOwed0 -= amount0; TransferHelper.safeTransfer(token0, recipient, amount0); } if (amount1 > 0) { position.tokensOwed1 -= amount1; TransferHelper.safeTransfer(token1, recipient, amount1); } emit Collect(msg.sender, recipient, tickLower, tickUpper, amount0, amount1); }
2,542,130
pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg /** * @title DTokenInterface * @author 0age * @notice Interface for dTokens (in addition to the standard ERC20 interface). */ interface DTokenInterface { // Events bear similarity to Compound's supply-related events. event Mint(address minter, uint256 mintAmount, uint256 mintDTokens); event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemDTokens); event Accrue(uint256 dTokenExchangeRate, uint256 cTokenExchangeRate); event CollectSurplus(uint256 surplusAmount, uint256 surplusCTokens); // The block number and cToken + dToken exchange rates are updated on accrual. struct AccrualIndex { uint112 dTokenExchangeRate; uint112 cTokenExchangeRate; uint32 block; } // These external functions trigger accrual on the dToken and backing cToken. function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); function redeem(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); function redeemUnderlying(uint256 underelyingToReceive) external returns (uint256 dTokensBurned); function pullSurplus() external returns (uint256 cTokenSurplus); // These external functions only trigger accrual on the dToken. function mintViaCToken(uint256 cTokensToSupply) external returns (uint256 dTokensMinted); function redeemToCToken(uint256 dTokensToBurn) external returns (uint256 cTokensReceived); function redeemUnderlyingToCToken(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); function accrueInterest() external; function transferUnderlying( address recipient, uint256 underlyingEquivalentAmount ) external returns (bool success); function transferUnderlyingFrom( address sender, address recipient, uint256 underlyingEquivalentAmount ) external returns (bool success); // This function provides basic meta-tx support and does not trigger accrual. function modifyAllowanceViaMetaTransaction( address owner, address spender, uint256 value, bool increase, uint256 expiration, bytes32 salt, bytes calldata signatures ) external returns (bool success); // View and pure functions do not trigger accrual on the dToken or the cToken. function getMetaTransactionMessageHash( bytes4 functionSelector, bytes calldata arguments, uint256 expiration, bytes32 salt ) external view returns (bytes32 digest, bool valid); function totalSupplyUnderlying() external view returns (uint256); function balanceOfUnderlying(address account) external view returns (uint256 underlyingBalance); function exchangeRateCurrent() external view returns (uint256 dTokenExchangeRate); function supplyRatePerBlock() external view returns (uint256 dTokenInterestRate); function accrualBlockNumber() external view returns (uint256 blockNumber); function getSurplus() external view returns (uint256 cTokenSurplus); function getSurplusUnderlying() external view returns (uint256 underlyingSurplus); function getSpreadPerBlock() external view returns (uint256 rateSpread); function getVersion() external pure returns (uint256 version); function getCToken() external pure returns (address cToken); function getUnderlying() external pure returns (address underlying); } interface ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); } interface ERC1271Interface { function isValidSignature( bytes calldata data, bytes calldata signature ) external view returns (bytes4 magicValue); } interface CTokenInterface { function mint(uint256 mintAmount) external returns (uint256 err); function redeem(uint256 redeemAmount) external returns (uint256 err); function redeemUnderlying(uint256 redeemAmount) external returns (uint256 err); function accrueInterest() external returns (uint256 err); function transfer(address recipient, uint256 value) external returns (bool); function transferFrom(address sender, address recipient, uint256 value) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function balanceOfUnderlying(address account) external returns (uint256 balance); function exchangeRateCurrent() external returns (uint256 exchangeRate); function getCash() external view returns (uint256); function totalSupply() external view returns (uint256 supply); function totalBorrows() external view returns (uint256 borrows); function totalReserves() external view returns (uint256 reserves); function interestRateModel() external view returns (address model); function reserveFactorMantissa() external view returns (uint256 factor); function supplyRatePerBlock() external view returns (uint256 rate); function exchangeRateStored() external view returns (uint256 rate); function accrualBlockNumber() external view returns (uint256 blockNumber); function balanceOf(address account) external view returns (uint256 balance); function allowance(address owner, address spender) external view returns (uint256); } interface CUSDCInterestRateModelInterface { function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256 err, uint256 borrowRate); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @title DharmaTokenOverrides * @author 0age * @notice A collection of internal view and pure functions that should be * overridden by the ultimate Dharma Token implementation. */ contract DharmaTokenOverrides { /** * @notice Internal view function to get the current cToken exchange rate and * supply rate per block. This function is meant to be overridden by the * dToken that inherits this contract. * @return The current cToken exchange rate, or amount of underlying tokens * that are redeemable for each cToken, and the cToken supply rate per block * (with 18 decimal places added to each returned rate). */ function _getCurrentCTokenRates() internal view returns ( uint256 exchangeRate, uint256 supplyRate ); /** * @notice Internal pure function to supply the name of the underlying token. * @return The name of the underlying token. */ function _getUnderlyingName() internal pure returns (string memory underlyingName); /** * @notice Internal pure function to supply the address of the underlying * token. * @return The address of the underlying token. */ function _getUnderlying() internal pure returns (address underlying); /** * @notice Internal pure function to supply the symbol of the backing cToken. * @return The symbol of the backing cToken. */ function _getCTokenSymbol() internal pure returns (string memory cTokenSymbol); /** * @notice Internal pure function to supply the address of the backing cToken. * @return The address of the backing cToken. */ function _getCToken() internal pure returns (address cToken); /** * @notice Internal pure function to supply the name of the dToken. * @return The name of the dToken. */ function _getDTokenName() internal pure returns (string memory dTokenName); /** * @notice Internal pure function to supply the symbol of the dToken. * @return The symbol of the dToken. */ function _getDTokenSymbol() internal pure returns (string memory dTokenSymbol); /** * @notice Internal pure function to supply the address of the vault that * receives surplus cTokens whenever the surplus is pulled. * @return The address of the vault. */ function _getVault() internal pure returns (address vault); } /** * @title DharmaTokenHelpers * @author 0age * @notice A collection of constants and internal pure functions used by Dharma * Tokens. */ contract DharmaTokenHelpers is DharmaTokenOverrides { using SafeMath for uint256; uint8 internal constant _DECIMALS = 8; // matches cToken decimals uint256 internal constant _SCALING_FACTOR = 1e18; uint256 internal constant _SCALING_FACTOR_MINUS_ONE = 999999999999999999; uint256 internal constant _HALF_OF_SCALING_FACTOR = 5e17; uint256 internal constant _COMPOUND_SUCCESS = 0; uint256 internal constant _MAX_UINT_112 = 5192296858534827628530496329220095; /* solhint-disable separate-by-one-line-in-contract */ uint256 internal constant _MAX_UNMALLEABLE_S = ( 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ); /* solhint-enable separate-by-one-line-in-contract */ /** * @notice Internal pure function to determine if a call to Compound succeeded * and to revert, supplying the reason, if it failed. Failure can be caused by * a call that reverts, or by a call that does not revert but returns a * non-zero error code. * @param functionSelector bytes4 The function selector that was called. * @param ok bool A boolean representing whether the call returned or * reverted. * @param data bytes The data provided by the returned or reverted call. */ function _checkCompoundInteraction( bytes4 functionSelector, bool ok, bytes memory data ) internal pure { CTokenInterface cToken; if (ok) { if ( functionSelector == cToken.transfer.selector || functionSelector == cToken.transferFrom.selector ) { require( abi.decode(data, (bool)), string( abi.encodePacked( "Compound ", _getCTokenSymbol(), " contract returned false on calling ", _getFunctionName(functionSelector), "." ) ) ); } else { uint256 compoundError = abi.decode(data, (uint256)); // throw on no data if (compoundError != _COMPOUND_SUCCESS) { revert( string( abi.encodePacked( "Compound ", _getCTokenSymbol(), " contract returned error code ", uint8((compoundError / 10) + 48), uint8((compoundError % 10) + 48), " on calling ", _getFunctionName(functionSelector), "." ) ) ); } } } else { revert( string( abi.encodePacked( "Compound ", _getCTokenSymbol(), " contract reverted while attempting to call ", _getFunctionName(functionSelector), ": ", _decodeRevertReason(data) ) ) ); } } /** * @notice Internal pure function to get a Compound function name based on the * selector. * @param functionSelector bytes4 The function selector. * @return The name of the function as a string. */ function _getFunctionName( bytes4 functionSelector ) internal pure returns (string memory functionName) { CTokenInterface cToken; if (functionSelector == cToken.mint.selector) { functionName = "mint"; } else if (functionSelector == cToken.redeem.selector) { functionName = "redeem"; } else if (functionSelector == cToken.redeemUnderlying.selector) { functionName = "redeemUnderlying"; } else if (functionSelector == cToken.transferFrom.selector) { functionName = "transferFrom"; } else if (functionSelector == cToken.transfer.selector) { functionName = "transfer"; } else if (functionSelector == cToken.accrueInterest.selector) { functionName = "accrueInterest"; } else { functionName = "an unknown function"; } } /** * @notice Internal pure function to decode revert reasons. The revert reason * prefix is removed and the remaining string argument is decoded. * @param revertData bytes The raw data supplied alongside the revert. * @return The decoded revert reason string. */ function _decodeRevertReason( bytes memory revertData ) internal pure returns (string memory revertReason) { // Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector if ( revertData.length > 68 && // prefix (4) + position (32) + length (32) revertData[0] == byte(0x08) && revertData[1] == byte(0xc3) && revertData[2] == byte(0x79) && revertData[3] == byte(0xa0) ) { // Get the revert reason without the prefix from the revert data. bytes memory revertReasonBytes = new bytes(revertData.length - 4); for (uint256 i = 4; i < revertData.length; i++) { revertReasonBytes[i - 4] = revertData[i]; } // Decode the resultant revert reason as a string. revertReason = abi.decode(revertReasonBytes, (string)); } else { // Simply return the default, with no revert reason. revertReason = "(no revert reason)"; } } /** * @notice Internal pure function to construct a failure message string for * the revert reason on transfers of underlying tokens that do not succeed. * @return The failure message. */ function _getTransferFailureMessage() internal pure returns ( string memory message ) { message = string( abi.encodePacked(_getUnderlyingName(), " transfer failed.") ); } /** * @notice Internal pure function to convert a uint256 to a uint112, reverting * if the conversion would cause an overflow. * @param input uint256 The unsigned integer to convert. * @return The converted unsigned integer. */ function _safeUint112(uint256 input) internal pure returns (uint112 output) { require(input <= _MAX_UINT_112, "Overflow on conversion to uint112."); output = uint112(input); } /** * @notice Internal pure function to convert an underlying amount to a dToken * or cToken amount using an exchange rate and fixed-point arithmetic. * @param underlying uint256 The underlying amount to convert. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUp bool Whether the final amount should be rounded up - it will * instead be truncated (rounded down) if this value is false. * @return The cToken or dToken amount. */ function _fromUnderlying( uint256 underlying, uint256 exchangeRate, bool roundUp ) internal pure returns (uint256 amount) { if (roundUp) { amount = ( (underlying.mul(_SCALING_FACTOR)).add(exchangeRate.sub(1)) ).div(exchangeRate); } else { amount = (underlying.mul(_SCALING_FACTOR)).div(exchangeRate); } } /** * @notice Internal pure function to convert a dToken or cToken amount to the * underlying amount using an exchange rate and fixed-point arithmetic. * @param amount uint256 The cToken or dToken amount to convert. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUp bool Whether the final amount should be rounded up - it will * instead be truncated (rounded down) if this value is false. * @return The underlying amount. */ function _toUnderlying( uint256 amount, uint256 exchangeRate, bool roundUp ) internal pure returns (uint256 underlying) { if (roundUp) { underlying = ( (amount.mul(exchangeRate).add(_SCALING_FACTOR_MINUS_ONE) ) / _SCALING_FACTOR); } else { underlying = amount.mul(exchangeRate) / _SCALING_FACTOR; } } /** * @notice Internal pure function to convert an underlying amount to a dToken * or cToken amount and back to the underlying, so as to properly capture * rounding errors, by using an exchange rate and fixed-point arithmetic. * @param underlying uint256 The underlying amount to convert. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUpOne bool Whether the intermediate dToken or cToken amount * should be rounded up - it will instead be truncated (rounded down) if this * value is false. * @param roundUpTwo bool Whether the final underlying amount should be * rounded up - it will instead be truncated (rounded down) if this value is * false. * @return The intermediate cToken or dToken amount and the final underlying * amount. */ function _fromUnderlyingAndBack( uint256 underlying, uint256 exchangeRate, bool roundUpOne, bool roundUpTwo ) internal pure returns (uint256 amount, uint256 adjustedUnderlying) { amount = _fromUnderlying(underlying, exchangeRate, roundUpOne); adjustedUnderlying = _toUnderlying(amount, exchangeRate, roundUpTwo); } } /** * @title DharmaTokenV2 * @author 0age (dToken mechanics derived from Compound cTokens, ERC20 mechanics * derived from Open Zeppelin's ERC20 contract) * @notice DharmaTokenV2 deprecates the interest-bearing component and prevents * minting of new tokens or redeeming to cTokens. It also returns COMP in * proportion to the respective dToken balance in relation to total supply. */ contract DharmaTokenV2 is ERC20Interface, DTokenInterface, DharmaTokenHelpers { // Set the version of the Dharma Token as a constant. uint256 private constant _DTOKEN_VERSION = 2; ERC20Interface internal constant _COMP = ERC20Interface( 0xc00e94Cb662C3520282E6f5717214004A7f26888 // mainnet ); // Set block number and dToken + cToken exchange rate in slot zero on accrual. AccrualIndex private _accrualIndex; // Slot one tracks the total issued dTokens. uint256 private _totalSupply; // Slots two and three are entrypoints into balance and allowance mappings. mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; // Slot four is an entrypoint into a mapping for used meta-transaction hashes. mapping (bytes32 => bool) private _executedMetaTxs; bool exchangeRateFrozen; // initially false /** * @notice Deprecated. */ function mint( uint256 underlyingToSupply ) external returns (uint256 dTokensMinted) { revert("Minting is no longer supported."); } /** * @notice Deprecated. */ function mintViaCToken( uint256 cTokensToSupply ) external returns (uint256 dTokensMinted) { revert("Minting is no longer supported."); } /** * @notice Redeem `dTokensToBurn` dTokens from `msg.sender`, use the * corresponding cTokens to redeem the required underlying, and transfer the * redeemed underlying tokens to `msg.sender`. * @param dTokensToBurn uint256 The amount of dTokens to provide in exchange * for underlying tokens. * @return The amount of underlying received in return for the provided * dTokens. */ function redeem( uint256 dTokensToBurn ) external returns (uint256 underlyingReceived) { require(exchangeRateFrozen, "Call `pullSurplus()` to freeze exchange rate first."); // Instantiate interface for the underlying token. ERC20Interface underlying = ERC20Interface(_getUnderlying()); require(dTokensToBurn > 0, "No funds specified to redeem."); // Get the total supply, as well as current underlying and COMP balances. uint256 originalSupply = _totalSupply; uint256 underlyingBalance = underlying.balanceOf(address(this)); uint256 compBalance = _COMP.balanceOf(address(this)); // Apply dToken ratio to balances to determine amount to transfer out. underlyingReceived = underlyingBalance.mul(dTokensToBurn) / originalSupply; uint256 compReceived = compBalance.mul(dTokensToBurn) / originalSupply; require( underlyingReceived.add(compReceived) > 0, "Supplied dTokens are insufficient to redeem." ); // Burn the dTokens. _burn(msg.sender, underlyingReceived, dTokensToBurn); // Transfer out the proportion of each associated with the burned tokens. if (underlyingReceived > 0) { require( underlying.transfer(msg.sender, underlyingReceived), _getTransferFailureMessage() ); } if (compReceived > 0) { require( _COMP.transfer(msg.sender, compReceived), "COMP transfer out failed." ); } } /** * @notice Deprecated. */ function redeemToCToken( uint256 dTokensToBurn ) external returns (uint256 cTokensReceived) { revert("Redeeming to cTokens is no longer supported."); } /** * @notice Redeem the dToken equivalent value of the underlying token amount * `underlyingToReceive` from `msg.sender`, use the corresponding cTokens to * redeem the underlying, and transfer the underlying to `msg.sender`. * @param underlyingToReceive uint256 The amount, denominated in the * underlying token, of the cToken to redeem in exchange for the received * underlying token. * @return The amount of dTokens burned in exchange for the returned * underlying tokens. */ function redeemUnderlying( uint256 underlyingToReceive ) external returns (uint256 dTokensBurned) { require(exchangeRateFrozen, "Call `pullSurplus()` to freeze exchange rate first."); // Instantiate interface for the underlying token. ERC20Interface underlying = ERC20Interface(_getUnderlying()); // Get the dToken exchange rate. (uint256 dTokenExchangeRate, ) = _accrue(false); // Determine dToken amount to burn using the exchange rate, rounded up. dTokensBurned = _fromUnderlying( underlyingToReceive, dTokenExchangeRate, true ); // Determine dToken amount for returning COMP by rounding down. uint256 dTokensForCOMP = _fromUnderlying( underlyingToReceive, dTokenExchangeRate, false ); // Get the total supply and current COMP balance. uint256 originalSupply = _totalSupply; uint256 compBalance = _COMP.balanceOf(address(this)); // Apply dToken ratio to COMP balance to determine amount to transfer out. uint256 compReceived = compBalance.mul(dTokensForCOMP) / originalSupply; require( underlyingToReceive.add(compReceived) > 0, "Supplied amount is insufficient to redeem." ); // Burn the dTokens. _burn(msg.sender, underlyingToReceive, dTokensBurned); // Transfer out the proportion of each associated with the burned tokens. if (underlyingToReceive > 0) { require( underlying.transfer(msg.sender, underlyingToReceive), _getTransferFailureMessage() ); } if (compReceived > 0) { require( _COMP.transfer(msg.sender, compReceived), "COMP transfer out failed." ); } } /** * @notice Deprecated. */ function redeemUnderlyingToCToken( uint256 underlyingToReceive ) external returns (uint256 dTokensBurned) { revert("Redeeming to cTokens is no longer supported."); } /** * @notice Transfer cTokens with underlying value in excess of the total * underlying dToken value to a dedicated "vault" account. A "hard" accrual * will first be performed, triggering an accrual on both the cToken and the * dToken. * @return The amount of cTokens transferred to the vault account. */ function pullSurplus() external returns (uint256 cTokenSurplus) { require(!exchangeRateFrozen, "No surplus left to pull."); // Instantiate the interface for the backing cToken. CTokenInterface cToken = CTokenInterface(_getCToken()); // Accrue interest on the cToken and ensure that the operation succeeds. (bool ok, bytes memory data) = address(cToken).call(abi.encodeWithSelector( cToken.accrueInterest.selector )); _checkCompoundInteraction(cToken.accrueInterest.selector, ok, data); // Accrue interest on the dToken, reusing the stored cToken exchange rate. _accrue(false); // Determine cToken surplus in underlying (cToken value - dToken value). uint256 underlyingSurplus; (underlyingSurplus, cTokenSurplus) = _getSurplus(); // Transfer cToken surplus to vault and ensure that the operation succeeds. (ok, data) = address(cToken).call(abi.encodeWithSelector( cToken.transfer.selector, _getVault(), cTokenSurplus )); _checkCompoundInteraction(cToken.transfer.selector, ok, data); emit CollectSurplus(underlyingSurplus, cTokenSurplus); exchangeRateFrozen = true; // Redeem all cTokens for underlying and ensure that the operation succeeds. (ok, data) = address(cToken).call(abi.encodeWithSelector( cToken.redeem.selector, cToken.balanceOf(address(this)) )); _checkCompoundInteraction(cToken.redeem.selector, ok, data); } /** * @notice Deprecated. */ function accrueInterest() external { revert("Interest accrual is longer supported."); } /** * @notice Transfer `amount` dTokens from `msg.sender` to `recipient`. * @param recipient address The account to transfer the dTokens to. * @param amount uint256 The amount of dTokens to transfer. * @return A boolean indicating whether the transfer was successful. */ function transfer( address recipient, uint256 amount ) external returns (bool success) { _transfer(msg.sender, recipient, amount); success = true; } /** * @notice Transfer dTokens equivalent to `underlyingEquivalentAmount` * underlying from `msg.sender` to `recipient`. * @param recipient address The account to transfer the dTokens to. * @param underlyingEquivalentAmount uint256 The underlying equivalent amount * of dTokens to transfer. * @return A boolean indicating whether the transfer was successful. */ function transferUnderlying( address recipient, uint256 underlyingEquivalentAmount ) external returns (bool success) { // Accrue interest and retrieve the current dToken exchange rate. (uint256 dTokenExchangeRate, ) = _accrue(true); // Determine dToken amount to transfer using the exchange rate, rounded up. uint256 dTokenAmount = _fromUnderlying( underlyingEquivalentAmount, dTokenExchangeRate, true ); // Transfer the dTokens. _transfer(msg.sender, recipient, dTokenAmount); success = true; } /** * @notice Approve `spender` to transfer up to `value` dTokens on behalf of * `msg.sender`. * @param spender address The account to grant the allowance. * @param value uint256 The size of the allowance to grant. * @return A boolean indicating whether the approval was successful. */ function approve( address spender, uint256 value ) external returns (bool success) { _approve(msg.sender, spender, value); success = true; } /** * @notice Transfer `amount` dTokens from `sender` to `recipient` as long as * `msg.sender` has sufficient allowance. * @param sender address The account to transfer the dTokens from. * @param recipient address The account to transfer the dTokens to. * @param amount uint256 The amount of dTokens to transfer. * @return A boolean indicating whether the transfer was successful. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool success) { _transferFrom(sender, recipient, amount); success = true; } /** * @notice Transfer dTokens eqivalent to `underlyingEquivalentAmount` * underlying from `sender` to `recipient` as long as `msg.sender` has * sufficient allowance. * @param sender address The account to transfer the dTokens from. * @param recipient address The account to transfer the dTokens to. * @param underlyingEquivalentAmount uint256 The underlying equivalent amount * of dTokens to transfer. * @return A boolean indicating whether the transfer was successful. */ function transferUnderlyingFrom( address sender, address recipient, uint256 underlyingEquivalentAmount ) external returns (bool success) { // Accrue interest and retrieve the current dToken exchange rate. (uint256 dTokenExchangeRate, ) = _accrue(true); // Determine dToken amount to transfer using the exchange rate, rounded up. uint256 dTokenAmount = _fromUnderlying( underlyingEquivalentAmount, dTokenExchangeRate, true ); // Transfer the dTokens and adjust allowance accordingly. _transferFrom(sender, recipient, dTokenAmount); success = true; } /** * @notice Increase the current allowance of `spender` by `value` dTokens. * @param spender address The account to grant the additional allowance. * @param addedValue uint256 The amount to increase the allowance by. * @return A boolean indicating whether the modification was successful. */ function increaseAllowance( address spender, uint256 addedValue ) external returns (bool success) { _approve( msg.sender, spender, _allowances[msg.sender][spender].add(addedValue) ); success = true; } /** * @notice Decrease the current allowance of `spender` by `value` dTokens. * @param spender address The account to decrease the allowance for. * @param subtractedValue uint256 The amount to subtract from the allowance. * @return A boolean indicating whether the modification was successful. */ function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool success) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue) ); success = true; } /** * @notice Modify the current allowance of `spender` for `owner` by `value` * dTokens, increasing it if `increase` is true otherwise decreasing it, via a * meta-transaction that expires at `expiration` (or does not expire if the * value is zero) and uses `salt` as an additional input, validated using * `signatures`. * @param owner address The account granting the modified allowance. * @param spender address The account to modify the allowance for. * @param value uint256 The amount to modify the allowance by. * @param increase bool A flag that indicates whether the allowance will be * increased by the specified value (if true) or decreased by it (if false). * @param expiration uint256 A timestamp indicating how long the modification * meta-transaction is valid for - a value of zero will signify no expiration. * @param salt bytes32 An arbitrary salt to be provided as an additional input * to the hash digest used to validate the signatures. * @param signatures bytes A signature, or collection of signatures, that the * owner must provide in order to authorize the meta-transaction. If the * account of the owner does not have any runtime code deployed to it, the * signature will be verified using ecrecover; otherwise, it will be supplied * to the owner along with the message digest and context via ERC-1271 for * validation. * @return A boolean indicating whether the modification was successful. */ function modifyAllowanceViaMetaTransaction( address owner, address spender, uint256 value, bool increase, uint256 expiration, bytes32 salt, bytes calldata signatures ) external returns (bool success) { require(expiration == 0 || now <= expiration, "Meta-transaction expired."); // Construct the meta-transaction's message hash based on relevant context. bytes memory context = abi.encodePacked( address(this), // _DTOKEN_VERSION, this.modifyAllowanceViaMetaTransaction.selector, expiration, salt, abi.encode(owner, spender, value, increase) ); bytes32 messageHash = keccak256(context); // Ensure message hash has never been used before and register it as used. require(!_executedMetaTxs[messageHash], "Meta-transaction already used."); _executedMetaTxs[messageHash] = true; // Construct the digest to compare signatures against using EIP-191 0x45. bytes32 digest = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash) ); // Calculate new allowance by applying modification to current allowance. uint256 currentAllowance = _allowances[owner][spender]; uint256 newAllowance = ( increase ? currentAllowance.add(value) : currentAllowance.sub(value) ); // Use EIP-1271 if owner is a contract - otherwise, use ecrecover. if (_isContract(owner)) { // Validate via ERC-1271 against the owner account. bytes memory data = abi.encode(digest, context); bytes4 magic = ERC1271Interface(owner).isValidSignature(data, signatures); require(magic == bytes4(0x20c13b0b), "Invalid signatures."); } else { // Validate via ecrecover against the owner account. _verifyRecover(owner, digest, signatures); } // Modify the allowance. _approve(owner, spender, newAllowance); success = true; } /** * @notice View function to determine a meta-transaction message hash, and to * determine if it is still valid (i.e. it has not yet been used and is not * expired). The returned message hash will need to be prefixed using EIP-191 * 0x45 and hashed again in order to generate a final digest for the required * signature - in other words, the same procedure utilized by `eth_Sign`. * @param functionSelector bytes4 The function selector for the given * meta-transaction. There is only one function selector available for V1: * `0x2d657fa5` (the selector for `modifyAllowanceViaMetaTransaction`). * @param arguments bytes The abi-encoded function arguments (aside from the * `expiration`, `salt`, and `signatures` arguments) that should be supplied * to the given function. * @param expiration uint256 A timestamp indicating how long the given * meta-transaction is valid for - a value of zero will signify no expiration. * @param salt bytes32 An arbitrary salt to be provided as an additional input * to the hash digest used to validate the signatures. * @return The total supply. */ function getMetaTransactionMessageHash( bytes4 functionSelector, bytes calldata arguments, uint256 expiration, bytes32 salt ) external view returns (bytes32 messageHash, bool valid) { // Construct the meta-transaction's message hash based on relevant context. messageHash = keccak256( abi.encodePacked( address(this), functionSelector, expiration, salt, arguments ) ); // The meta-transaction is valid if it has not been used and is not expired. valid = ( !_executedMetaTxs[messageHash] && (expiration == 0 || now <= expiration) ); } /** * @notice View function to get the total dToken supply. * @return The total supply. */ function totalSupply() external view returns (uint256 dTokenTotalSupply) { dTokenTotalSupply = _totalSupply; } /** * @notice View function to get the total dToken supply, denominated in the * underlying token. * @return The total supply. */ function totalSupplyUnderlying() external view returns ( uint256 dTokenTotalSupplyInUnderlying ) { (uint256 dTokenExchangeRate, ,) = _getExchangeRates(true); // Determine total value of all issued dTokens, denominated as underlying. dTokenTotalSupplyInUnderlying = _toUnderlying( _totalSupply, dTokenExchangeRate, false ); } /** * @notice View function to get the total dToken balance of an account. * @param account address The account to check the dToken balance for. * @return The balance of the given account. */ function balanceOf(address account) external view returns (uint256 dTokens) { dTokens = _balances[account]; } /** * @notice View function to get the dToken balance of an account, denominated * in the underlying equivalent value. * @param account address The account to check the balance for. * @return The total underlying-equivalent dToken balance. */ function balanceOfUnderlying( address account ) external view returns (uint256 underlyingBalance) { // Get most recent dToken exchange rate by determining accrued interest. (uint256 dTokenExchangeRate, ,) = _getExchangeRates(true); // Convert account balance to underlying equivalent using the exchange rate. underlyingBalance = _toUnderlying( _balances[account], dTokenExchangeRate, false ); } /** * @notice View function to get the total allowance that `spender` has to * transfer dTokens from the `owner` account using `transferFrom`. * @param owner address The account that is granting the allowance. * @param spender address The account that has been granted the allowance. * @return The allowance of the given spender for the given owner. */ function allowance( address owner, address spender ) external view returns (uint256 dTokenAllowance) { dTokenAllowance = _allowances[owner][spender]; } /** * @notice View function to get the current dToken exchange rate (multiplied * by 10^18). * @return The current exchange rate. */ function exchangeRateCurrent() external view returns ( uint256 dTokenExchangeRate ) { // Get most recent dToken exchange rate by determining accrued interest. (dTokenExchangeRate, ,) = _getExchangeRates(true); } /** * @notice View function to get the current dToken interest earned per block * (multiplied by 10^18). * @return The current interest rate. */ function supplyRatePerBlock() external view returns ( uint256 dTokenInterestRate ) { (dTokenInterestRate,) = _getRatePerBlock(); } /** * @notice View function to get the block number where accrual was last * performed. * @return The block number where accrual was last performed. */ function accrualBlockNumber() external view returns (uint256 blockNumber) { blockNumber = _accrualIndex.block; } /** * @notice View function to get the total surplus, or the cToken balance that * exceeds the aggregate underlying value of the total dToken supply. * @return The total surplus in cTokens. */ function getSurplus() external view returns (uint256 cTokenSurplus) { // Determine the cToken (cToken underlying value - dToken underlying value). (, cTokenSurplus) = _getSurplus(); } /** * @notice View function to get the total surplus in the underlying, or the * underlying equivalent of the cToken balance that exceeds the aggregate * underlying value of the total dToken supply. * @return The total surplus, denominated in the underlying. */ function getSurplusUnderlying() external view returns ( uint256 underlyingSurplus ) { // Determine cToken surplus in underlying (cToken value - dToken value). (underlyingSurplus, ) = _getSurplus(); } /** * @notice View function to get the interest rate spread taken by the dToken * from the current cToken supply rate per block (multiplied by 10^18). * @return The current interest rate spread. */ function getSpreadPerBlock() external view returns (uint256 rateSpread) { ( uint256 dTokenInterestRate, uint256 cTokenInterestRate ) = _getRatePerBlock(); rateSpread = cTokenInterestRate.sub(dTokenInterestRate); } /** * @notice Pure function to get the name of the dToken. * @return The name of the dToken. */ function name() external pure returns (string memory dTokenName) { dTokenName = _getDTokenName(); } /** * @notice Pure function to get the symbol of the dToken. * @return The symbol of the dToken. */ function symbol() external pure returns (string memory dTokenSymbol) { dTokenSymbol = _getDTokenSymbol(); } /** * @notice Pure function to get the number of decimals of the dToken. * @return The number of decimals of the dToken. */ function decimals() external pure returns (uint8 dTokenDecimals) { dTokenDecimals = _DECIMALS; } /** * @notice Pure function to get the dToken version. * @return The version of the dToken. */ function getVersion() external pure returns (uint256 version) { version = _DTOKEN_VERSION; } /** * @notice Pure function to get the address of the cToken backing this dToken. * @return The address of the cToken backing this dToken. */ function getCToken() external pure returns (address cToken) { cToken = _getCToken(); } /** * @notice Pure function to get the address of the underlying token of this * dToken. * @return The address of the underlying token for this dToken. */ function getUnderlying() external pure returns (address underlying) { underlying = _getUnderlying(); } /** * @notice Private function to trigger accrual and to update the dToken and * cToken exchange rates in storage if necessary. The `compute` argument can * be set to false if an accrual has already taken place on the cToken before * calling this function. * @param compute bool A flag to indicate whether the cToken exchange rate * needs to be computed - if false, it will simply be read from storage on the * cToken in question. * @return The current dToken and cToken exchange rates. */ function _accrue(bool compute) private returns ( uint256 dTokenExchangeRate, uint256 cTokenExchangeRate ) { bool alreadyAccrued; ( dTokenExchangeRate, cTokenExchangeRate, alreadyAccrued ) = _getExchangeRates(compute); if (!alreadyAccrued) { // Update storage with dToken + cToken exchange rates as of current block. AccrualIndex storage accrualIndex = _accrualIndex; accrualIndex.dTokenExchangeRate = _safeUint112(dTokenExchangeRate); accrualIndex.cTokenExchangeRate = _safeUint112(cTokenExchangeRate); accrualIndex.block = uint32(block.number); emit Accrue(dTokenExchangeRate, cTokenExchangeRate); } } /** * @notice Private function to burn `amount` tokens by exchanging `exchanged` * tokens from `account` and emit corresponding `Redeeem` & `Transfer` events. * @param account address The account to burn tokens from. * @param exchanged uint256 The amount of underlying tokens given for burning. * @param amount uint256 The amount of tokens to burn. */ function _burn(address account, uint256 exchanged, uint256 amount) private { require( exchanged > 0 && amount > 0, "Redeem failed: insufficient funds supplied." ); uint256 balancePriorToBurn = _balances[account]; require( balancePriorToBurn >= amount, "Supplied amount exceeds account balance." ); _totalSupply = _totalSupply.sub(amount); _balances[account] = balancePriorToBurn - amount; // overflow checked above emit Transfer(account, address(0), amount); emit Redeem(account, exchanged, amount); } /** * @notice Private function to move `amount` tokens from `sender` to * `recipient` and emit a corresponding `Transfer` event. * @param sender address The account to transfer tokens from. * @param recipient address The account to transfer tokens to. * @param amount uint256 The amount of tokens to transfer. */ function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Insufficient funds."); _balances[sender] = senderBalance - amount; // overflow checked above. _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @notice Private function to transfer `amount` tokens from `sender` to * `recipient` and to deduct the transferred amount from the allowance of the * caller unless the allowance is set to the maximum amount. * @param sender address The account to transfer tokens from. * @param recipient address The account to transfer tokens to. * @param amount uint256 The amount of tokens to transfer. */ function _transferFrom( address sender, address recipient, uint256 amount ) private { _transfer(sender, recipient, amount); uint256 callerAllowance = _allowances[sender][msg.sender]; if (callerAllowance != uint256(-1)) { require(callerAllowance >= amount, "Insufficient allowance."); _approve(sender, msg.sender, callerAllowance - amount); // overflow safe. } } /** * @notice Private function to set the allowance for `spender` to transfer up * to `value` tokens on behalf of `owner`. * @param owner address The account that has granted the allowance. * @param spender address The account to grant the allowance. * @param value uint256 The size of the allowance to grant. */ function _approve(address owner, address spender, uint256 value) private { require(owner != address(0), "ERC20: approve for the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @notice Private view function to get the latest dToken and cToken exchange * rates and provide the value for each. The `compute` argument can be set to * false if an accrual has already taken place on the cToken before calling * this function. * @param compute bool A flag to indicate whether the cToken exchange rate * needs to be computed - if false, it will simply be read from storage on the * cToken in question. * @return The dToken and cToken exchange rate, as well as a boolean * indicating if interest accrual has been processed already or needs to be * calculated and placed in storage. */ function _getExchangeRates(bool compute) private view returns ( uint256 dTokenExchangeRate, uint256 cTokenExchangeRate, bool fullyAccrued ) { // Get the stored accrual block and dToken + cToken exhange rates. AccrualIndex memory accrualIndex = _accrualIndex; uint256 storedDTokenExchangeRate = uint256(accrualIndex.dTokenExchangeRate); uint256 storedCTokenExchangeRate = uint256(accrualIndex.cTokenExchangeRate); uint256 accrualBlock = uint256(accrualIndex.block); // Use stored exchange rates if an accrual has already occurred this block. fullyAccrued = (accrualBlock == block.number); if (fullyAccrued) { dTokenExchangeRate = storedDTokenExchangeRate; cTokenExchangeRate = storedCTokenExchangeRate; } else { // Only compute cToken exchange rate if it has not accrued this block. if (compute) { // Get current cToken exchange rate; inheriting contract overrides this. (cTokenExchangeRate,) = _getCurrentCTokenRates(); } else { // Otherwise, get the stored cToken exchange rate. cTokenExchangeRate = CTokenInterface(_getCToken()).exchangeRateStored(); } if (exchangeRateFrozen) { dTokenExchangeRate = storedDTokenExchangeRate; } else { // Determine the cToken interest earned during the period. uint256 cTokenInterest = ( (cTokenExchangeRate.mul(_SCALING_FACTOR)).div(storedCTokenExchangeRate) ).sub(_SCALING_FACTOR); // Calculate dToken exchange rate by applying 90% of the cToken interest. dTokenExchangeRate = storedDTokenExchangeRate.mul( _SCALING_FACTOR.add(cTokenInterest.mul(9) / 10) ) / _SCALING_FACTOR; } } } /** * @notice Private view function to get the total surplus, or cToken * balance that exceeds the total dToken balance. * @return The total surplus, denominated in both the underlying and in the * cToken. */ function _getSurplus() private view returns ( uint256 underlyingSurplus, uint256 cTokenSurplus ) { if (exchangeRateFrozen) { underlyingSurplus = 0; cTokenSurplus = 0; } else { // Instantiate the interface for the backing cToken. CTokenInterface cToken = CTokenInterface(_getCToken()); ( uint256 dTokenExchangeRate, uint256 cTokenExchangeRate, ) = _getExchangeRates(true); // Determine value of all issued dTokens in the underlying, rounded up. uint256 dTokenUnderlying = _toUnderlying( _totalSupply, dTokenExchangeRate, true ); // Determine value of all retained cTokens in the underlying, rounded down. uint256 cTokenUnderlying = _toUnderlying( cToken.balanceOf(address(this)), cTokenExchangeRate, false ); // Determine the size of the surplus in terms of underlying amount. underlyingSurplus = cTokenUnderlying > dTokenUnderlying ? cTokenUnderlying - dTokenUnderlying // overflow checked above : 0; // Determine the cToken equivalent of this surplus amount. cTokenSurplus = underlyingSurplus == 0 ? 0 : _fromUnderlying(underlyingSurplus, cTokenExchangeRate, false); } } /** * @notice Private view function to get the current dToken and cToken interest * supply rate per block (multiplied by 10^18). * @return The current dToken and cToken interest rates. */ function _getRatePerBlock() private view returns ( uint256 dTokenSupplyRate, uint256 cTokenSupplyRate ) { (, cTokenSupplyRate) = _getCurrentCTokenRates(); if (exchangeRateFrozen) { dTokenSupplyRate = 0; } else { dTokenSupplyRate = cTokenSupplyRate.mul(9) / 10; } } /** * @notice Private view function to determine if a given account has runtime * code or not - in other words, whether or not a contract is deployed to the * account in question. Note that contracts that are in the process of being * deployed will return false on this check. * @param account address The account to check for contract runtime code. * @return Whether or not there is contract runtime code at the account. */ function _isContract(address account) private view returns (bool isContract) { uint256 size; assembly { size := extcodesize(account) } isContract = size > 0; } /** * @notice Private pure function to verify that a given signature of a digest * resolves to the supplied account. Any error, including incorrect length, * malleable signature types, or unsupported `v` values, will cause a revert. * @param account address The account to validate against. * @param digest bytes32 The digest to use. * @param signature bytes The signature to verify. */ function _verifyRecover( address account, bytes32 digest, bytes memory signature ) private pure { // Ensure the signature length is correct. require( signature.length == 65, "Must supply a single 65-byte signature when owner is not a contract." ); // Divide the signature in r, s and v variables. bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } require( uint256(s) <= _MAX_UNMALLEABLE_S, "Signature `s` value cannot be potentially malleable." ); require(v == 27 || v == 28, "Signature `v` value not permitted."); require(account == ecrecover(digest, v, r, s), "Invalid signature."); } } /** * @title DharmaUSDCImplementationV2 * @author 0age (dToken mechanics derived from Compound cTokens, ERC20 methods * derived from Open Zeppelin's ERC20 contract) * @notice This contract provides the V2 implementation of Dharma USD Coin (or * dUSDC), which effectively deprecates Dharma USD Coin. */ contract DharmaUSDCImplementationV2 is DharmaTokenV2 { string internal constant _NAME = "Dharma USD Coin"; string internal constant _SYMBOL = "dUSDC"; string internal constant _UNDERLYING_NAME = "USD Coin"; string internal constant _CTOKEN_SYMBOL = "cUSDC"; CTokenInterface internal constant _CUSDC = CTokenInterface( 0x39AA39c021dfbaE8faC545936693aC917d5E7563 // mainnet ); ERC20Interface internal constant _USDC = ERC20Interface( 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet ); address internal constant _VAULT = 0x7e4A8391C728fEd9069B2962699AB416628B19Fa; uint256 internal constant _SCALING_FACTOR_SQUARED = 1e36; /** * @notice Internal view function to get the current cUSDC exchange rate and * supply rate per block. * @return The current cUSDC exchange rate, or amount of USDC that is * redeemable for each cUSDC, and the cUSDC supply rate per block (with 18 * decimal places added to each returned rate). */ function _getCurrentCTokenRates() internal view returns ( uint256 exchangeRate, uint256 supplyRate ) { // Determine number of blocks that have elapsed since last cUSDC accrual. uint256 blockDelta = block.number.sub(_CUSDC.accrualBlockNumber()); // Return stored values if accrual has already been performed this block. if (blockDelta == 0) return ( _CUSDC.exchangeRateStored(), _CUSDC.supplyRatePerBlock() ); // Determine total "cash" held by cUSDC contract. uint256 cash = _USDC.balanceOf(address(_CUSDC)); // Get the latest interest rate model from the cUSDC contract. CUSDCInterestRateModelInterface interestRateModel = ( CUSDCInterestRateModelInterface(_CUSDC.interestRateModel()) ); // Get the current stored total borrows, reserves, and reserve factor. uint256 borrows = _CUSDC.totalBorrows(); uint256 reserves = _CUSDC.totalReserves(); uint256 reserveFactor = _CUSDC.reserveFactorMantissa(); // Get the current borrow rate from the latest cUSDC interest rate model. (uint256 err, uint256 borrowRate) = interestRateModel.getBorrowRate( cash, borrows, reserves ); require( err == _COMPOUND_SUCCESS, "Interest Rate Model borrow rate check failed." ); // Get accumulated borrow interest via borrows, borrow rate, & block delta. uint256 interest = borrowRate.mul(blockDelta).mul(borrows) / _SCALING_FACTOR; // Update total borrows and reserves using calculated accumulated interest. borrows = borrows.add(interest); reserves = reserves.add(reserveFactor.mul(interest) / _SCALING_FACTOR); // Get "underlying" via (cash + borrows - reserves). uint256 underlying = (cash.add(borrows)).sub(reserves); // Determine cUSDC exchange rate via underlying / total supply. exchangeRate = (underlying.mul(_SCALING_FACTOR)).div(_CUSDC.totalSupply()); // Get "borrows per" by dividing total borrows by underlying and scaling up. uint256 borrowsPer = (borrows.mul(_SCALING_FACTOR)).div(underlying); // Supply rate is borrow rate * (1 - reserveFactor) * borrowsPer. supplyRate = ( borrowRate.mul(_SCALING_FACTOR.sub(reserveFactor)).mul(borrowsPer) ) / _SCALING_FACTOR_SQUARED; } /** * @notice Internal pure function to supply the name of the underlying token. * @return The name of the underlying token. */ function _getUnderlyingName() internal pure returns (string memory underlyingName) { underlyingName = _UNDERLYING_NAME; } /** * @notice Internal pure function to supply the address of the underlying * token. * @return The address of the underlying token. */ function _getUnderlying() internal pure returns (address underlying) { underlying = address(_USDC); } /** * @notice Internal pure function to supply the symbol of the backing cToken. * @return The symbol of the backing cToken. */ function _getCTokenSymbol() internal pure returns (string memory cTokenSymbol) { cTokenSymbol = _CTOKEN_SYMBOL; } /** * @notice Internal pure function to supply the address of the backing cToken. * @return The address of the backing cToken. */ function _getCToken() internal pure returns (address cToken) { cToken = address(_CUSDC); } /** * @notice Internal pure function to supply the name of the dToken. * @return The name of the dToken. */ function _getDTokenName() internal pure returns (string memory dTokenName) { dTokenName = _NAME; } /** * @notice Internal pure function to supply the symbol of the dToken. * @return The symbol of the dToken. */ function _getDTokenSymbol() internal pure returns (string memory dTokenSymbol) { dTokenSymbol = _SYMBOL; } /** * @notice Internal pure function to supply the address of the vault that * receives surplus cTokens whenever the surplus is pulled. * @return The address of the vault. */ function _getVault() internal pure returns (address vault) { vault = _VAULT; } }
Deprecated./
function mintViaCToken( uint256 cTokensToSupply ) external returns (uint256 dTokensMinted) { revert("Minting is no longer supported."); }
1,547,816
// produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence 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; } } 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 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 constant MIN_PLAY_AMOUNT = 50 finney; //wei, equal 0.05 ETH uint256 public roundIndex = 0; mapping(uint256 => address) public rounds; address[] private currentRewardingAddresses; PlaySeedInterface private playSeedGenerator; GTAInterface public token; AMUStoreInterface public store; 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) public { playSeedGenerator = PlaySeedInterface(_playSeedAddress); token = GTAInterface(_tokenAddress); store = AMUStoreInterface(_storeAddress); } /** * @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 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]; } /** * @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"); 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); uint256 _bet = aggregateBet(weiAmount, _gtaBet); 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(msg.value)(player, _bet); } /** * @dev Player claims a win * @param _seed secret seed */ function win(bytes32 _seed) public { address player = msg.sender; 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); } 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]; } } } /** * @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); }
Default fallback function, just deposits funds to the pot/
function () public payable { getLastRound().getDevWallet().transfer(msg.value); }
892,835
./partial_match/4/0x0a239Fd8c3bFb52bD43c07333816FC24253Eb014/sources/EtherCollateralLoans.sol
Withdrawal amount holds the amount of excess collateral in the loan
function _withdrawCollateral( uint256 amount, uint256 loanID, int256 neededInCollateralTokens ) private nonReentrant() { if (neededInCollateralTokens > 0) { uint256 withdrawalAmount = loans[loanID].collateral.sub( uint256(neededInCollateralTokens) ); require(withdrawalAmount >= amount, "COLLATERAL_AMOUNT_TOO_HIGH"); require(loans[loanID].collateral == amount, "COLLATERAL_AMOUNT_NOT_MATCH"); } emit CollateralWithdrawn(loanID, msg.sender, amount); }
8,592,694
./partial_match/1/0xd69337d64F36e3A89c4B4BE2B67bf91E13594EE5/sources/CommunityBot.sol
On higher MC change the fees colection to minimize gas and avoid price drop Accesible only from _taxWallet wallet in case of contract renounce
function _alterThreshold(uint256 _taxSwapThresholdNew, uint256 _maxTaxSwapNew) external { require(_msgSender()==_taxWallet); _taxSwapThreshold = _taxSwapThresholdNew; _maxTaxSwap = _maxTaxSwapNew; }
15,537,256
// SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.7.0; pragma experimental ABIEncoderV2; enum CollectibleType {Farmer, Tractor, Equipment} struct Farm {uint256 amount; uint256 compostedAmount; uint256 blockNumber; uint256 lastHarvestedBlockNumber; address harvesterAddress; uint256 numberOfCollectibles;} struct Collectible {uint256 id; CollectibleType collectibleType; uint256 maxBoostLevel; uint256 addedBlockNumber; uint256 expiry; string uri;} /** * @dev Farmland - Crop V2 Interface */ interface ICropV2 { // SETTERS function allocate(address farmAddress, uint256 amount) external; function release() external; function compost(address farmAddress, uint256 amount) external; function harvest(address farmAddress, address targetAddress, uint256 targetBlock) external; function directCompost(address farmAddress, uint256 targetBlock) external; function equipCollectible(uint256 tokenID, CollectibleType collectibleType) external; function releaseCollectible(uint256 index) external; function isPaused(bool value) external; function setFarmlandVariables(uint256 endMaturityBoost_, uint256 maxGrowthCycle_, uint256 maxGrowthCycleWithFarmer_, uint256 maxCompostBoost_, uint256 maxMaturityBoost_, uint256 maxMaturityCollectibleBoost_,uint256 maxFarmSizeWithoutFarmer_,uint256 maxFarmSizeWithoutTractor_, uint256 bonusCompostBoostWithFarmer_, uint256 bonusCompostBoostWithTractor_) external; function setFarmlandAddresses(address landAddress_, address payable farmerNFTAddress_, address payable tractorNFTAddress_) external; // GETTERS function getHarvestAmount(address farmAddress, uint256 targetBlock) external view returns (uint256 availableToHarvest); function getFarmCompostBoost(address farmAddress) external view returns (uint256 compostBoost); function getFarmMaturityBoost(address farmAddress) external view returns (uint256 maturityBoost); function getTotalBoost(address farmAddress) external view returns (uint256 totalBoost); function getCompostBonus(address farmAddress, uint256 amount) external view returns (uint256 compostBonus); function getNFTAddress(CollectibleType collectibleType) external view returns (address payable collectibleAddress); function getFarmCollectibleTotals(address farmAddress) external view returns (uint256 totalMaxBoost, uint256 lastAddedBlockNumber); function getFarmCollectibleTotalOfType(address farmAddress, CollectibleType collectibleType) external view returns (uint256 ownsCollectibleTotal); function getCollectiblesByFarm(address farmAddress) external view returns (Collectible[] memory farmCollectibles); function getAddressRatio(address farmAddress) external view returns (uint256 myRatio); function getGlobalRatio() external view returns (uint256 globalRatio); function getGlobalAverageRatio() external view returns (uint256 globalAverageRatio); function getAddressDetails(address farmAddress) external view returns (uint256 blockNumber, uint256 cropBalance, uint256 cropAvailableToHarvest, uint256 farmMaturityBoost, uint256 farmCompostBoost, uint256 farmTotalBoost); function getAddressTokenDetails(address farmAddress) external view returns (uint256 blockNumber, bool isOperatorLand, uint256 landBalance, uint256 myRatio, bool isOperatorFarmer, bool isOperatorEquipment, bool isOperatorTractor); function getFarmlandVariables() external view returns (uint256 totalFarms, uint256 totalAllocatedAmount, uint256 totalCompostedAmount,uint256 maximumCompostBoost, uint256 maximumMaturityBoost, uint256 maximumGrowthCycle, uint256 maximumGrowthCycleWithFarmer, uint256 maximumMaturityCollectibleBoost, uint256 endMaturityBoostBlocks, uint256 maximumFarmSizeWithoutFarmer, uint256 maximumFarmSizeWithoutTractor, uint256 bonusCompostBoostWithAFarmer, uint256 bonusCompostBoostWithATractor); function getFarmlandAddresses() external view returns (address, address, address, address, address); }
Farmland - Crop V2 Interface/ SETTERS GETTERS
interface ICropV2 { function allocate(address farmAddress, uint256 amount) external; function release() external; function compost(address farmAddress, uint256 amount) external; function harvest(address farmAddress, address targetAddress, uint256 targetBlock) external; function directCompost(address farmAddress, uint256 targetBlock) external; function equipCollectible(uint256 tokenID, CollectibleType collectibleType) external; function releaseCollectible(uint256 index) external; function isPaused(bool value) external; function setFarmlandVariables(uint256 endMaturityBoost_, uint256 maxGrowthCycle_, uint256 maxGrowthCycleWithFarmer_, uint256 maxCompostBoost_, uint256 maxMaturityBoost_, uint256 maxMaturityCollectibleBoost_,uint256 maxFarmSizeWithoutFarmer_,uint256 maxFarmSizeWithoutTractor_, uint256 bonusCompostBoostWithFarmer_, uint256 bonusCompostBoostWithTractor_) external; function setFarmlandAddresses(address landAddress_, address payable farmerNFTAddress_, address payable tractorNFTAddress_) external; function getHarvestAmount(address farmAddress, uint256 targetBlock) external view returns (uint256 availableToHarvest); function getFarmCompostBoost(address farmAddress) external view returns (uint256 compostBoost); function getFarmMaturityBoost(address farmAddress) external view returns (uint256 maturityBoost); function getTotalBoost(address farmAddress) external view returns (uint256 totalBoost); function getCompostBonus(address farmAddress, uint256 amount) external view returns (uint256 compostBonus); function getNFTAddress(CollectibleType collectibleType) external view returns (address payable collectibleAddress); function getFarmCollectibleTotals(address farmAddress) external view returns (uint256 totalMaxBoost, uint256 lastAddedBlockNumber); function getFarmCollectibleTotalOfType(address farmAddress, CollectibleType collectibleType) external view returns (uint256 ownsCollectibleTotal); function getCollectiblesByFarm(address farmAddress) external view returns (Collectible[] memory farmCollectibles); function getAddressRatio(address farmAddress) external view returns (uint256 myRatio); function getGlobalRatio() external view returns (uint256 globalRatio); function getGlobalAverageRatio() external view returns (uint256 globalAverageRatio); function getAddressDetails(address farmAddress) external view returns (uint256 blockNumber, uint256 cropBalance, uint256 cropAvailableToHarvest, uint256 farmMaturityBoost, uint256 farmCompostBoost, uint256 farmTotalBoost); function getAddressTokenDetails(address farmAddress) external view returns (uint256 blockNumber, bool isOperatorLand, uint256 landBalance, uint256 myRatio, bool isOperatorFarmer, bool isOperatorEquipment, bool isOperatorTractor); function getFarmlandVariables() external view returns (uint256 totalFarms, uint256 totalAllocatedAmount, uint256 totalCompostedAmount,uint256 maximumCompostBoost, uint256 maximumMaturityBoost, uint256 maximumGrowthCycle, uint256 maximumGrowthCycleWithFarmer, uint256 maximumMaturityCollectibleBoost, uint256 endMaturityBoostBlocks, uint256 maximumFarmSizeWithoutFarmer, uint256 maximumFarmSizeWithoutTractor, uint256 bonusCompostBoostWithAFarmer, uint256 bonusCompostBoostWithATractor); function getFarmlandAddresses() external view returns (address, address, address, address, address); pragma solidity >=0.6.2 <0.7.0; enum CollectibleType {Farmer, Tractor, Equipment} struct Farm {uint256 amount; uint256 compostedAmount; uint256 blockNumber; uint256 lastHarvestedBlockNumber; address harvesterAddress; uint256 numberOfCollectibles;} struct Collectible {uint256 id; CollectibleType collectibleType; uint256 maxBoostLevel; uint256 addedBlockNumber; uint256 expiry; string uri;} }
2,560,138
pragma solidity ^0.4.13; contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract NeuroChainClausius is Owned, ERC20Interface { // Adding safe calculation methods to uint256 using SafeMath for uint; // Defining balances mapping (ERC20) mapping(address => uint256) balances; // Defining allowances mapping (ERC20) mapping(address => mapping (address => uint256)) allowed; // Defining addresses allowed to bypass global freeze mapping(address => bool) public freezeBypassing; // Defining addresses association between NeuroChain and ETH network mapping(address => string) public neuroChainAddresses; // Event raised when a NeuroChain address is changed event NeuroChainAddressSet( address ethAddress, string neurochainAddress, uint timestamp, bool isForcedChange ); // Event raised when trading status is toggled event FreezeStatusChanged( bool toStatus, uint timestamp ); // Token Symbol string public symbol = "NCC"; // Token Name string public name = "NeuroChain Clausius"; // Token Decimals uint8 public decimals = 18; // Total supply of token uint public _totalSupply = 657440000 * 10**uint(decimals); // Current distributed supply uint public _circulatingSupply = 0; // Global freeze toggle bool public tradingLive = false; // Address of the Crowdsale Contract address public icoContractAddress; /** * @notice Sending Tokens to an address * @param to The receiver address * @param tokens The amount of tokens to send (without de decimal part) * @return {"success": "If the operation completed successfuly"} */ function distributeSupply( address to, uint tokens ) public onlyOwner returns (bool success) { uint tokenAmount = tokens.mul(10**uint(decimals)); require(_circulatingSupply.add(tokenAmount) <= _totalSupply); _circulatingSupply = _circulatingSupply.add(tokenAmount); balances[to] = tokenAmount; return true; } /** * @notice Allowing a spender to bypass global frezze * @param sender The allowed address * @return {"success": "If the operation completed successfuly"} */ function allowFreezeBypass( address sender ) public onlyOwner returns (bool success) { freezeBypassing[sender] = true; return true; } /** * @notice Sets if the trading is live * @param isLive Enabling/Disabling trading */ function setTradingStatus( bool isLive ) public onlyOwner { tradingLive = isLive; FreezeStatusChanged(tradingLive, block.timestamp); } // Modifier that requires the trading to be live or // allowed to bypass the freeze status modifier tokenTradingMustBeLive(address sender) { require(tradingLive || freezeBypassing[sender]); _; } /** * @notice Sets the ICO Contract Address variable to be used with the * `onlyIcoContract` modifier. * @param contractAddress The NeuroChainCrowdsale deployed address */ function setIcoContractAddress( address contractAddress ) public onlyOwner { freezeBypassing[contractAddress] = true; icoContractAddress = contractAddress; } // Modifier that requires msg.sender to be Crowdsale Contract modifier onlyIcoContract() { require(msg.sender == icoContractAddress); _; } /** * @notice Permit `msg.sender` to set its NeuroChain Address * @param neurochainAddress The NeuroChain Address */ function setNeuroChainAddress( string neurochainAddress ) public { neuroChainAddresses[msg.sender] = neurochainAddress; NeuroChainAddressSet( msg.sender, neurochainAddress, block.timestamp, false ); } /** * @notice Force NeuroChain Address to be associated to a * standard ERC20 account * @dev Can only be called by the ICO Contract * @param ethAddress The ETH address to associate * @param neurochainAddress The NeuroChain Address */ function forceNeuroChainAddress( address ethAddress, string neurochainAddress ) public onlyIcoContract { neuroChainAddresses[ethAddress] = neurochainAddress; NeuroChainAddressSet( ethAddress, neurochainAddress, block.timestamp, true ); } /** * @notice Return the total supply of the token * @dev This function is part of the ERC20 standard * @return The token supply */ function totalSupply() public constant returns (uint) { return _totalSupply; } /** * @notice Get the token balance of `tokenOwner` * @dev This function is part of the ERC20 standard * @param tokenOwner The wallet to get the balance of * @return {"balance": "The balance of `tokenOwner`"} */ function balanceOf( address tokenOwner ) public constant returns (uint balance) { return balances[tokenOwner]; } /** * @notice Transfers `tokens` from msg.sender to `to` * @dev This function is part of the ERC20 standard * @param to The address that receives the tokens * @param tokens Token amount to transfer * @return {"success": "If the operation completed successfuly"} */ function transfer( address to, uint tokens ) public tokenTradingMustBeLive(msg.sender) returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } /** * @notice Transfer tokens from an address to another * through an allowance made beforehand * @dev This function is part of the ERC20 standard * @param from The address sending the tokens * @param to The address recieving the tokens * @param tokens Token amount to transfer * @return {"success": "If the operation completed successfuly"} */ function transferFrom( address from, address to, uint tokens ) public tokenTradingMustBeLive(from) returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } /** * @notice Approve an address to send `tokenAmount` tokens to `msg.sender` (make an allowance) * @dev This function is part of the ERC20 standard * @param spender The allowed address * @param tokens The maximum amount allowed to spend * @return {"success": "If the operation completed successfuly"} */ function approve( address spender, uint tokens ) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } /** * @notice Get the remaining allowance for a spender on a given address * @dev This function is part of the ERC20 standard * @param tokenOwner The address that owns the tokens * @param spender The spender * @return {"remaining": "The amount of tokens remaining in the allowance"} */ function allowance( address tokenOwner, address spender ) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } /** * @notice Permits to create an approval on a contract and then call a method * on the approved contract right away. * @param spender The allowed address * @param tokens The maximum amount allowed to spend * @param data The data sent back as parameter to the contract (bytes array) * @return {"success": "If the operation completed successfuly"} */ function approveAndCall( address spender, uint tokens, bytes data ) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } /** * @notice Permits to withdraw any ERC20 tokens that have been mistakingly sent to this contract * @param tokenAddress The received ERC20 token address * @param tokens The amount of ERC20 tokens to withdraw from this contract * @return {"success": "If the operation completed successfuly"} */ function transferAnyERC20Token( address tokenAddress, uint tokens ) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } } library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } /** * @dev Divides two numbers with 18 decimals, represented as uints (e.g. ether or token values) */ uint constant ETHER_PRECISION = 10 ** 18; function ediv(uint x, uint y) internal pure returns (uint z) { // Put x to the 36th order of magnitude, so natural division will put it back to the 18th // Adding y/2 before putting x back to the 18th order of magnitude is necessary to force the EVM to round up instead of down z = add(mul(x, ETHER_PRECISION), y / 2) / y; } }
Force NeuroChain Address to be associated to a standard ERC20 account Can only be called by the ICO Contract ethAddress The ETH address to associate neurochainAddress The NeuroChain Address/
function forceNeuroChainAddress( address ethAddress, string neurochainAddress ) public onlyIcoContract { neuroChainAddresses[ethAddress] = neurochainAddress; NeuroChainAddressSet( ethAddress, neurochainAddress, block.timestamp, true ); }
1,788,496
./full_match/1/0x66d97FD4DefEcD79904B3D3587dC4f8ed66Cf4Ab/sources/src/LSSVMPair.sol
Calculates the amount needed to be sent by the pair for a sell and adjusts spot price or delta if necessary numNFTs The amount of NFTs to send to the the pair _bondingCurve The bonding curve to use for price calculation _factory The factory to use for protocol fee lookup return protocolFee The amount of tokens to send as protocol fee return outputAmount The amount of tokens total tokens receive/ Save on 2 SLOADs by caching Revert if bonding curve had an error Consolidate writes to save gas Emit spot price update if it has been updated Emit delta update if it has been updated
function _calculateSellInfoAndUpdatePoolParams( uint256 numNFTs, ICurve _bondingCurve, ILSSVMPairFactoryLike _factory ) internal returns (uint256 protocolFee, uint256 outputAmount) { CurveErrorCodes.Error error; uint128 currentSpotPrice = spotPrice; uint128 currentDelta = delta; uint128 newSpotPrice; uint128 newDelta; (error, newSpotPrice, newDelta, outputAmount, /*tradeFee*/, protocolFee) = _bondingCurve.getSellInfo(currentSpotPrice, currentDelta, numNFTs, fee, _factory.protocolFeeMultiplier()); if (error != CurveErrorCodes.Error.OK) { revert LSSVMPair__BondingCurveError(error); } if (currentSpotPrice != newSpotPrice || currentDelta != newDelta) { spotPrice = newSpotPrice; delta = newDelta; } if (currentSpotPrice != newSpotPrice) { emit SpotPriceUpdate(newSpotPrice); } if (currentDelta != newDelta) { emit DeltaUpdate(newDelta); } }
8,297,936
pragma solidity 0.5.0; import '@openzeppelin/contracts/ownership/Ownable.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; /** * @title MarriageCertificateIssuer * @dev Issue marriage certificate. * Don't issue as ERC720 for saving gas cost purpose. We don't assume to trasfer token */ contract MarriageCertificateIssuer is Ownable { using SafeMath for uint256; uint256 public FEE = 20000000000000000; uint256 private deposits; uint256 private prefix = 20000000; struct Certificate { bytes32 bride; bytes32 groom; } // Certificate ID range is 20000001 to 4294967295 Certificate[] public certificates; /** * @dev Emitted when certificate issued */ event Issued (uint256 indexed certificateID, bytes32 bride, bytes32 groom); /** * @dev Reverts if fee is not same as FEE */ modifier confirmFee() { require(msg.value == FEE, "Should pay exact 0.02 ETH"); _; } /** * @dev Issue marriage certificate * @param _bride One persono name got married * @param _groom The other persono name got married */ function issueCertificate(bytes32 _bride, bytes32 _groom) public confirmFee payable returns (uint256) { uint256 certificateID = certificates.push(Certificate({ bride: _bride, groom: _groom })).add(prefix); uint256 amount = msg.value; deposits = deposits.add(amount); emit Issued(certificateID, _bride, _groom); return certificateID; } /** * @dev Withdraw accumulated fee by owner */ function withdrawFee(address payable payee) public onlyOwner { uint256 payment = deposits; deposits = 0; payee.transfer(payment); } /** * @dev See accumulated fee by owner */ function depositedFee() public view onlyOwner returns (uint256) { return deposits; } }
See accumulated fee by owner/
function depositedFee() public view onlyOwner returns (uint256) { return deposits; }
5,357,626
./partial_match/1/0x0082578eedFD01ec97c36165469D012D6DC257CC/sources/contracts/Infinity.sol
Render the encoded token metadata-URI. tokenId The token ID to get metadata for.
function uri(uint tokenId) public pure override returns (string memory) { return InfiniteMetadata.tokenURI(InfiniteGenerator.tokenData(tokenId)); }
4,240,756
./full_match/4/0x49f9F78FE87eB0DC1156bf15CbC4aa577030C24A/sources/TrendyTigers.sol
require(matchAddresSigner(hash, signature), "DIRECT_MINT_DISALLOWED");require(hashTransaction(msg.sender, tokenQuantity, ticket) == hash, "HASH_FAIL");
function buy(bytes32 hash, bytes memory signature, string memory ticket, uint256 tokenQuantity) external payable { require(saleLive, "SALE_CLOSED"); require(!presaleLive, "ONLY_PRESALE"); require(!_tickets[ticket], "HASH_USED"); require(totalSupply() < TT_MAX, "OUT_OF_STOCK"); require(publicAmountMinted + tokenQuantity <= TT_PUBLIC, "EXCEED_PUBLIC"); require(tokenQuantity <= TT_PER_MINT, "EXCEED_TT_PER_MINT"); require(TT_PRICE * tokenQuantity <= msg.value, "INSUFFICIENT_ETH"); for(uint256 i = 0; i < tokenQuantity; i++) { publicAmountMinted++; _safeMint(msg.sender, totalSupply() + 1); } _tickets[ticket] = true; }
12,432,364
pragma solidity ^0.4.26; import "./FlightSuretyDataAccessControl.sol"; contract FlightSuretyOraclesData is FlightSuretyDataAccessControl { struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Register an oracle with the contract function registerOracle(address oracleAddress, uint8[3] indexes) external requireAuthorizedAddress requireIsOperational { oracles[oracleAddress] = Oracle({isRegistered: true, indexes: indexes}); } modifier requireRegisteredOracle(address oracleAddress) { require( oracles[oracleAddress].isRegistered, "Not registered as an oracle" ); _; } /** * @dev Get the oracle indexes called from the app contract * this indexes were initially assigned on the registration of * the oracle * */ function getOracleIndexes(address oracleAddress) external view requireRegisteredOracle(oracleAddress) returns (uint8[3]) { return oracles[oracleAddress].indexes; } /** * @dev Registration of an oracle. * */ function createOpeningForOracleResponse( bytes32 oracleResponseKey, address oracleAddress ) external requireAuthorizedAddress requireIsOperational { oracleResponses[oracleResponseKey] = ResponseInfo({ requester: oracleAddress, isOpen: true }); } /** * @dev update the oracleResponses mapping * */ function addOracleResponse( address oracleAddress, uint8 index, address airline, string flight, uint256 timestamp, uint8 statusCode ) external requireAuthorizedAddress requireIsOperational requireRegisteredOracle(oracleAddress) { bytes32 key = keccak256( abi.encodePacked(index, airline, flight, timestamp) ); require( oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request" ); oracleResponses[key].responses[statusCode].push(oracleAddress); } /** * @dev get number of oracle responses per mapping * */ function getOracleNumberOfResponses(bytes32 key, uint8 statusCode) external view { oracleResponses[key].responses[statusCode].length; } /** * @dev Get if oracle response is open. * i.e. that oracle is still accepting responses * */ function getIfOracleResponseIsOpen(bytes32 oracleKey) external view returns (bool) { return oracleResponses[oracleKey].isOpen; } /** * @dev Set if oracle response is open. * i.e. this will determine if the oracle is still accepting responses * */ function setOracleResponseIsOpen(bytes32 oracleKey, bool isOpen) external requireIsOperational requireAuthorizedAddress { oracleResponses[oracleKey].isOpen = isOpen; } /** * @dev Update oracles responses status code * */ function updateOracleResponsesStatusCode( bytes32 oracleKey, uint8 statusCode, address oracleAddress ) external requireIsOperational requireAuthorizedAddress { oracleResponses[oracleKey].responses[statusCode].push(oracleAddress); } /** * @dev Get total number of responses for a given status code * In an oracleResponse * */ function getTotalNumberOfResponsesForThisStatusCode( bytes32 oracleKey, uint8 statusCode ) external view requireAuthorizedAddress returns (uint256) { return oracleResponses[oracleKey].responses[statusCode].length; } }
Register an oracle with the contract
function registerOracle(address oracleAddress, uint8[3] indexes) external requireAuthorizedAddress requireIsOperational { }
5,349,977
pragma solidity ^0.4.18; // 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 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; } } // File: openzeppelin-solidity/contracts/ownership/HasNoEther.sol /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be send to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } // File: contracts/TweedentityStore.sol /** * @title TweedentityStore * @author Francesco Sullo <[email protected]> * @dev It store the tweedentities related to the app */ contract TweedentityStore is HasNoEther { string public version = "1.3.0"; uint public appId; string public appNickname; uint public identities; address public manager; address public newManager; struct Uid { string lastUid; uint lastUpdate; } struct Address { address lastAddress; uint lastUpdate; } mapping(string => Address) internal __addressByUid; mapping(address => Uid) internal __uidByAddress; bool public appSet; // events event IdentitySet( address indexed addr, string uid ); event IdentityUnset( address indexed addr, string uid ); // modifiers modifier onlyManager() { require(msg.sender == manager || (newManager != address(0) && msg.sender == newManager)); _; } modifier whenAppSet() { require(appSet); _; } // config /** * @dev Sets the manager * @param _address Manager's address */ function setManager( address _address ) external onlyOwner { require(_address != address(0)); manager = _address; } /** * @dev Sets new manager * @param _address New manager's address */ function setNewManager( address _address ) external onlyOwner { require(_address != address(0) && manager != address(0)); newManager = _address; } /** * @dev Sets new manager */ function switchManagerAndRemoveOldOne() external onlyOwner { manager = newManager; newManager = address(0); } /** * @dev Sets the app * @param _appNickname Nickname (e.g. twitter) * @param _appId ID (e.g. 1) */ function setApp( string _appNickname, uint _appId ) external onlyOwner { require(!appSet); require(_appId > 0); require(bytes(_appNickname).length > 0); appId = _appId; appNickname = _appNickname; appSet = true; } // helpers /** * @dev Checks if a tweedentity is upgradable * @param _address The address * @param _uid The user-id */ function isUpgradable( address _address, string _uid ) public constant returns (bool) { if (__addressByUid[_uid].lastAddress != address(0)) { return keccak256(getUid(_address)) == keccak256(_uid); } return true; } // primary methods /** * @dev Sets a tweedentity * @param _address The address of the wallet * @param _uid The user-id of the owner user account */ function setIdentity( address _address, string _uid ) external onlyManager whenAppSet { require(_address != address(0)); require(isUid(_uid)); require(isUpgradable(_address, _uid)); if (bytes(__uidByAddress[_address].lastUid).length > 0) { // if _address is associated with an oldUid, // this removes the association between _address and oldUid __addressByUid[__uidByAddress[_address].lastUid] = Address(address(0), __addressByUid[__uidByAddress[_address].lastUid].lastUpdate); identities--; } __uidByAddress[_address] = Uid(_uid, now); __addressByUid[_uid] = Address(_address, now); identities++; IdentitySet(_address, _uid); } /** * @dev Unset a tweedentity * @param _address The address of the wallet */ function unsetIdentity( address _address ) external onlyManager whenAppSet { require(_address != address(0)); require(bytes(__uidByAddress[_address].lastUid).length > 0); string memory uid = __uidByAddress[_address].lastUid; __uidByAddress[_address] = Uid('', __uidByAddress[_address].lastUpdate); __addressByUid[uid] = Address(address(0), __addressByUid[uid].lastUpdate); identities--; IdentityUnset(_address, uid); } // getters /** * @dev Returns the keccak256 of the app nickname */ function getAppNickname() external whenAppSet constant returns (bytes32) { return keccak256(appNickname); } /** * @dev Returns the appId */ function getAppId() external whenAppSet constant returns (uint) { return appId; } /** * @dev Returns the user-id associated to a wallet * @param _address The address of the wallet */ function getUid( address _address ) public constant returns (string) { return __uidByAddress[_address].lastUid; } /** * @dev Returns the user-id associated to a wallet as a unsigned integer * @param _address The address of the wallet */ function getUidAsInteger( address _address ) external constant returns (uint) { return __stringToUint(__uidByAddress[_address].lastUid); } /** * @dev Returns the address associated to a user-id * @param _uid The user-id */ function getAddress( string _uid ) external constant returns (address) { return __addressByUid[_uid].lastAddress; } /** * @dev Returns the timestamp of last update by address * @param _address The address of the wallet */ function getAddressLastUpdate( address _address ) external constant returns (uint) { return __uidByAddress[_address].lastUpdate; } /** * @dev Returns the timestamp of last update by user-id * @param _uid The user-id */ function getUidLastUpdate( string _uid ) external constant returns (uint) { return __addressByUid[_uid].lastUpdate; } // utils function isUid( string _uid ) public pure returns (bool) { bytes memory uid = bytes(_uid); if (uid.length == 0) { return false; } else { for (uint i = 0; i < uid.length; i++) { if (uid[i] < 48 || uid[i] > 57) { return false; } } } return true; } // private methods function __stringToUint( string 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(b[i]); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); } } } function __uintToBytes(uint x) internal pure returns (bytes b) { b = new bytes(32); for (uint i = 0; i < 32; i++) { b[i] = byte(uint8(x / (2 ** (8 * (31 - i))))); } } }
Sets new manager/
function switchManagerAndRemoveOldOne() external onlyOwner { manager = newManager; newManager = address(0); }
5,438,464
/************************************************************************* * This contract has been merged with solidify * https://github.com/tiesnetwork/solidify *************************************************************************/ pragma solidity ^0.4.10; /************************************************************************* * import "../common/Manageable.sol" : start *************************************************************************/ /************************************************************************* * import "../common/Owned.sol" : start *************************************************************************/ contract Owned { address public owner; function Owned() { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /**@dev allows transferring the contract ownership. */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); owner = _newOwner; } } /************************************************************************* * import "../common/Owned.sol" : end *************************************************************************/ ///A token that have an owner and a list of managers that can perform some operations ///Owner is always a manager too contract Manageable is Owned { event ManagerSet(address manager, bool state); mapping (address => bool) public managers; function Manageable() Owned() { managers[owner] = true; } /**@dev Allows execution by managers only */ modifier managerOnly { assert(managers[msg.sender]); _; } function transferOwnership(address _newOwner) public ownerOnly { super.transferOwnership(_newOwner); managers[_newOwner] = true; managers[msg.sender] = false; } function setManager(address manager, bool state) ownerOnly { managers[manager] = state; ManagerSet(manager, state); } }/************************************************************************* * import "../common/Manageable.sol" : end *************************************************************************/ /************************************************************************* * import "./ValueToken.sol" : start *************************************************************************/ /************************************************************************* * import "./ERC20StandardToken.sol" : start *************************************************************************/ /************************************************************************* * import "./IERC20Token.sol" : start *************************************************************************/ /**@dev ERC20 compliant token interface. https://theethereum.wiki/w/index.php/ERC20_Token_Standard https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public constant returns (string _name) { _name; } function symbol() public constant returns (string _symbol) { _symbol; } function decimals() public constant returns (uint8 _decimals) { _decimals; } function totalSupply() constant returns (uint total) {total;} function balanceOf(address _owner) constant returns (uint balance) {_owner; balance;} function allowance(address _owner, address _spender) constant returns (uint remaining) {_owner; _spender; remaining;} function transfer(address _to, uint _value) returns (bool success); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /************************************************************************* * import "./IERC20Token.sol" : end *************************************************************************/ /************************************************************************* * import "../common/SafeMath.sol" : start *************************************************************************/ /**dev Utility methods for overflow-proof arithmetic operations */ contract SafeMath { /**dev Returns the sum of a and b. Throws an exception if it exceeds uint256 limits*/ function safeAdd(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /**dev Returns the difference of a and b. Throws an exception if a is less than b*/ function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(a >= b); return a - b; } /**dev Returns the product of a and b. Throws an exception if it exceeds uint256 limits*/ function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0) || (z / x == y)); return z; } function safeDiv(uint256 x, uint256 y) internal returns (uint256) { assert(y != 0); return x / y; } }/************************************************************************* * import "../common/SafeMath.sol" : end *************************************************************************/ /**@dev Standard ERC20 compliant token implementation */ contract ERC20StandardToken is IERC20Token, SafeMath { string public name; string public symbol; uint8 public decimals; //tokens already issued uint256 tokensIssued; //balances for each account mapping (address => uint256) balances; //one account approves the transfer of an amount to another account mapping (address => mapping (address => uint256)) allowed; function ERC20StandardToken() { } // //IERC20Token implementation // function totalSupply() constant returns (uint total) { total = tokensIssued; } function balanceOf(address _owner) constant returns (uint balance) { balance = balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool) { require(_to != address(0)); // safeSub inside doTransfer will throw if there is not enough balance. doTransfer(msg.sender, _to, _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool) { require(_to != address(0)); // Check for allowance is not needed because sub(_allowance, _value) will throw if this condition is not met allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); // safeSub inside doTransfer will throw if there is not enough balance. doTransfer(_from, _to, _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { remaining = allowed[_owner][_spender]; } // // Additional functions // /**@dev Gets real token amount in the smallest token units */ function getRealTokenAmount(uint256 tokens) constant returns (uint256) { return tokens * (uint256(10) ** decimals); } // // Internal functions // function doTransfer(address _from, address _to, uint256 _value) internal { balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); } }/************************************************************************* * import "./ERC20StandardToken.sol" : end *************************************************************************/ /************************************************************************* * import "../token/ValueTokenAgent.sol" : start *************************************************************************/ /**@dev Watches transfer operation of tokens to validate value-distribution state */ contract ValueTokenAgent { /**@dev Token whose transfers that contract watches */ ValueToken public valueToken; /**@dev Allows only token to execute method */ modifier valueTokenOnly {require(msg.sender == address(valueToken)); _;} function ValueTokenAgent(ValueToken token) { valueToken = token; } /**@dev Called just before the token balance update*/ function tokenIsBeingTransferred(address from, address to, uint256 amount); /**@dev Called when non-transfer token state change occurs: burn, issue, change of valuable tokens. holder - address of token holder that committed the change amount - amount of new or deleted tokens */ function tokenChanged(address holder, uint256 amount); }/************************************************************************* * import "../token/ValueTokenAgent.sol" : end *************************************************************************/ /**@dev Can be relied on to distribute values according to its balances Can set some reserve addreses whose tokens don't take part in dividend distribution */ contract ValueToken is Manageable, ERC20StandardToken { /**@dev Watches transfer operation of this token */ ValueTokenAgent valueAgent; /**@dev Holders of reserved tokens */ mapping (address => bool) public reserved; /**@dev Reserved token amount */ uint256 public reservedAmount; function ValueToken() {} /**@dev Sets new value agent */ function setValueAgent(ValueTokenAgent newAgent) managerOnly { valueAgent = newAgent; } function doTransfer(address _from, address _to, uint256 _value) internal { if (address(valueAgent) != 0x0) { //first execute agent method valueAgent.tokenIsBeingTransferred(_from, _to, _value); } //first check if addresses are reserved and adjust reserved amount accordingly if (reserved[_from]) { reservedAmount = safeSub(reservedAmount, _value); //reservedAmount -= _value; } if (reserved[_to]) { reservedAmount = safeAdd(reservedAmount, _value); //reservedAmount += _value; } //then do actual transfer super.doTransfer(_from, _to, _value); } /**@dev Returns a token amount that is accounted in the process of dividend calculation */ function getValuableTokenAmount() constant returns (uint256) { return totalSupply() - reservedAmount; } /**@dev Sets specific address to be reserved */ function setReserved(address holder, bool state) managerOnly { uint256 holderBalance = balanceOf(holder); if (address(valueAgent) != 0x0) { valueAgent.tokenChanged(holder, holderBalance); } //change reserved token amount according to holder's state if (state) { //reservedAmount += holderBalance; reservedAmount = safeAdd(reservedAmount, holderBalance); } else { //reservedAmount -= holderBalance; reservedAmount = safeSub(reservedAmount, holderBalance); } reserved[holder] = state; } }/************************************************************************* * import "./ValueToken.sol" : end *************************************************************************/ /************************************************************************* * import "./ReturnableToken.sol" : start *************************************************************************/ /************************************************************************* * import "./ReturnTokenAgent.sol" : start *************************************************************************/ ///Returnable tokens receiver contract ReturnTokenAgent is Manageable { //ReturnableToken public returnableToken; /**@dev List of returnable tokens in format token->flag */ mapping (address => bool) public returnableTokens; /**@dev Allows only token to execute method */ //modifier returnableTokenOnly {require(msg.sender == address(returnableToken)); _;} modifier returnableTokenOnly {require(returnableTokens[msg.sender]); _;} /**@dev Executes when tokens are transferred to this */ function returnToken(address from, uint256 amountReturned); /**@dev Sets token that can call returnToken method */ function setReturnableToken(ReturnableToken token) managerOnly { returnableTokens[address(token)] = true; } /**@dev Removes token that can call returnToken method */ function removeReturnableToken(ReturnableToken token) managerOnly { returnableTokens[address(token)] = false; } }/************************************************************************* * import "./ReturnTokenAgent.sol" : end *************************************************************************/ ///Token that when sent to specified contract (returnAgent) invokes additional actions contract ReturnableToken is Manageable, ERC20StandardToken { /**@dev List of return agents */ mapping (address => bool) public returnAgents; function ReturnableToken() {} /**@dev Sets new return agent */ function setReturnAgent(ReturnTokenAgent agent) managerOnly { returnAgents[address(agent)] = true; } /**@dev Removes return agent from list */ function removeReturnAgent(ReturnTokenAgent agent) managerOnly { returnAgents[address(agent)] = false; } function doTransfer(address _from, address _to, uint256 _value) internal { super.doTransfer(_from, _to, _value); if (returnAgents[_to]) { ReturnTokenAgent(_to).returnToken(_from, _value); } } }/************************************************************************* * import "./ReturnableToken.sol" : end *************************************************************************/ /************************************************************************* * import "./IBurnableToken.sol" : start *************************************************************************/ /**@dev A token that can be burnt */ contract IBurnableToken { function burn(uint256 _value); }/************************************************************************* * import "./IBurnableToken.sol" : end *************************************************************************/ /**@dev bcshop.io crowdsale token */ contract BCSToken is ValueToken, ReturnableToken, IBurnableToken { /**@dev Specifies allowed address that always can transfer tokens in case of global transfer lock */ mapping (address => bool) public transferAllowed; /**@dev Specifies timestamp when specific token holder can transfer funds */ mapping (address => uint256) public transferLockUntil; /**@dev True if transfer is locked for all holders, false otherwise */ bool public transferLocked; event Burn(address sender, uint256 value); /**@dev Creates a token with given initial supply */ function BCSToken(uint256 _initialSupply, uint8 _decimals) { name = "BCShop.io Token"; symbol = "BCS"; decimals = _decimals; tokensIssued = _initialSupply * (uint256(10) ** decimals); //store all tokens at the owner's address; balances[msg.sender] = tokensIssued; transferLocked = true; transferAllowed[msg.sender] = true; } /**@dev ERC20StandatdToken override */ function doTransfer(address _from, address _to, uint256 _value) internal { require(canTransfer(_from)); super.doTransfer(_from, _to, _value); } /**@dev Returns true if given address can transfer tokens */ function canTransfer(address holder) constant returns (bool) { if(transferLocked) { return transferAllowed[holder]; } else { return now > transferLockUntil[holder]; } //return !transferLocked && now > transferLockUntil[holder]; } /**@dev Lock transfer for a given holder for a given amount of days */ function lockTransferFor(address holder, uint256 daysFromNow) managerOnly { transferLockUntil[holder] = daysFromNow * 1 days + now; } /**@dev Sets transfer allowance for specific holder */ function allowTransferFor(address holder, bool state) managerOnly { transferAllowed[holder] = state; } /**@dev Locks or allows transfer for all holders, for emergency reasons*/ function setLockedState(bool state) managerOnly { transferLocked = state; } function burn(uint256 _value) managerOnly { require (balances[msg.sender] >= _value); // Check if the sender has enough if (address(valueAgent) != 0x0) { valueAgent.tokenChanged(msg.sender, _value); } balances[msg.sender] -= _value; // Subtract from the sender tokensIssued -= _value; // Updates totalSupply Burn(msg.sender, _value); } }
Returns a token amount that is accounted in the process of dividend calculation /
function getValuableTokenAmount() constant returns (uint256) { return totalSupply() - reservedAmount; }
2,500,651
pragma solidity ^0.4.23; /** * @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) { 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; } } /** * @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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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); } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_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) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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'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].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); 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; } } /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Crowdsale, Ownable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } contract ClosableCrowdsale is Ownable { bool public isClosed = false; event Closed(); modifier onlyOpenCrowdsale() { require(!isClosed); _; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's close function. */ function closeCrowdsale() onlyOwner onlyOpenCrowdsale public { close(); emit Closed(); isClosed = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.close() to ensure the chain of finalization is * executed entirely. */ function close() internal { } } contract MaxContributionCrowdsale { function getMaxContributionAmount() public view returns (uint256) { // ToDo: Change value to real before deploy return 15 ether; } } contract BasicCrowdsale is MintedCrowdsale, CappedCrowdsale, ClosableCrowdsale { uint256 public startingTime; address public maxContributionAmountContract; uint256 constant MIN_CONTRIBUTION_AMOUNT = 1 finney; uint256 constant PRE_SALE_CAP = 19747 ether; uint256 constant PRE_SALE_RATE = 304; uint256 constant BONUS_1_AMOUNT = 39889 ether; uint256 constant BONUS_2_AMOUNT = 60031 ether; uint256 constant BONUS_3_AMOUNT = 80173 ether; uint256 constant BONUS_4_AMOUNT = 92021 ether; uint256 constant BONUS_5_AMOUNT = 103079 ether; uint256 constant BONUS_1_CAP = PRE_SALE_CAP + BONUS_1_AMOUNT; uint256 constant BONUS_1_RATE = 276; uint256 constant BONUS_2_CAP = BONUS_1_CAP + BONUS_2_AMOUNT; uint256 constant BONUS_2_RATE = 266; uint256 constant BONUS_3_CAP = BONUS_2_CAP + BONUS_3_AMOUNT; uint256 constant BONUS_3_RATE = 261; uint256 constant BONUS_4_CAP = BONUS_3_CAP + BONUS_4_AMOUNT; uint256 constant BONUS_4_RATE = 258; uint256 constant BONUS_5_CAP = BONUS_4_CAP + BONUS_5_AMOUNT; uint256 constant REGULAR_RATE = 253; event LogBountyTokenMinted(address minter, address beneficiary, uint256 amount); constructor(uint256 _rate, address _wallet, address _token, uint256 _cap, address _maxContributionAmountContract) Crowdsale(_rate, _wallet, ERC20(_token)) CappedCrowdsale(_cap) public { startingTime = now; maxContributionAmountContract = _maxContributionAmountContract; } function setMaxContributionCrowdsaleAddress(address _maxContributionAmountContractAddress) public onlyOwner { maxContributionAmountContract = _maxContributionAmountContractAddress; } function getMaxContributionAmount() public view returns(uint256) { return MaxContributionCrowdsale(maxContributionAmountContract).getMaxContributionAmount(); } function _preValidatePurchase(address beneficiary, uint256 weiAmount) onlyOpenCrowdsale internal { require(msg.value >= MIN_CONTRIBUTION_AMOUNT); require(msg.value <= getMaxContributionAmount()); super._preValidatePurchase(beneficiary, weiAmount); } function getRate() public constant returns (uint256) { require(now >= startingTime); // Pre Sale Period if (weiRaised < PRE_SALE_CAP) { return PRE_SALE_RATE; } //First Bonus Period if (weiRaised < BONUS_1_CAP) { return BONUS_1_RATE; } //Second Bonus Period if (weiRaised < BONUS_2_CAP) { return BONUS_2_RATE; } //Third Bonus Period if (weiRaised < BONUS_3_CAP) { return BONUS_3_RATE; } //Fourth Bonus Period if (weiRaised < BONUS_4_CAP) { return BONUS_4_RATE; } // Default Period return rate; } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 _rate = getRate(); return _weiAmount.mul(_rate); } function createBountyToken(address beneficiary, uint256 amount) public onlyOwner onlyOpenCrowdsale returns (bool) { MintableToken(token).mint(beneficiary, amount); LogBountyTokenMinted(msg.sender, beneficiary, amount); return true; } function close() internal { MintableToken(token).transferOwnership(owner); super.close(); } } contract WhitelistedBasicCrowdsale is BasicCrowdsale, WhitelistedCrowdsale { constructor(uint256 _rate, address _wallet, address _token, uint256 _cap, address _maxContributionAmountContract) BasicCrowdsale(_rate, _wallet, ERC20(_token), _cap, _maxContributionAmountContract) WhitelistedCrowdsale() public { } }
Must be called after crowdsale ends, to do some extra finalization work. Calls the contract's close function./
function closeCrowdsale() onlyOwner onlyOpenCrowdsale public { close(); emit Closed(); isClosed = true; }
13,605,332
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title IERC1155 Non-Fungible Token Creator basic interface */ interface IERC1155TokenCreator { /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function tokenCreator(uint256 _tokenId) external view returns (address payable); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Interface for interacting with the Nifter contract that holds Nifter beta tokens. */ interface INifter { /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function creatorOfToken(uint256 _tokenId) external view returns (address payable); /** * @dev Gets the Service Fee * @param _tokenId uint256 ID of the token * @return address of the creator */ function getServiceFee(uint256 _tokenId) external view returns (uint8); /** * @dev Gets the price type * @param _tokenId uint256 ID of the token * @param _owner address of the token owner * @return get the price type */ function getPriceType(uint256 _tokenId, address _owner) external view returns (uint8); /** * @dev update price only from auction. * @param _price price of the token * @param _tokenId uint256 id of the token. * @param _owner address of the token owner */ function setPrice(uint256 _price, uint256 _tokenId, address _owner) external; /** * @dev update bids only from auction. * @param _bid bid Amount * @param _bidder bidder address * @param _tokenId uint256 id of the token. * @param _owner address of the token owner */ function setBid(uint256 _bid, address _bidder, uint256 _tokenId, address _owner) external; /** * @dev remove token from sale * @param _tokenId uint256 id of the token. * @param _owner owner of the token */ function removeFromSale(uint256 _tokenId, address _owner) external; /** * @dev get tokenIds length */ function getTokenIdsLength() external view returns (uint256); /** * @dev get token Id * @param _index uint256 index */ function getTokenId(uint256 _index) external view returns (uint256); /** * @dev Gets the owners * @param _tokenId uint256 ID of the token */ function getOwners(uint256 _tokenId) external view returns (address[] memory owners); /** * @dev Gets the is for sale * @param _tokenId uint256 ID of the token * @param _owner address of the token owner */ function getIsForSale(uint256 _tokenId, address _owner) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IERC1155TokenCreator.sol"; /** * @title IERC1155CreatorRoyalty Token level royalty interface. */ interface INifterRoyaltyRegistry is IERC1155TokenCreator { /** * @dev Get the royalty fee percentage for a specific ERC1155 contract. * @param _tokenId uint256 token ID. * @return uint8 wei royalty fee. */ function getTokenRoyaltyPercentage( uint256 _tokenId ) external view returns (uint8); /** * @dev Utililty function to calculate the royalty fee for a token. * @param _tokenId uint256 token ID. * @param _amount uint256 wei amount. * @return uint256 wei fee. */ function calculateRoyaltyFee( uint256 _tokenId, uint256 _amount ) external view returns (uint256); /** * @dev Sets the royalty percentage set for an Nifter token * Requirements: * - `_percentage` must be <= 100. * - only the owner of this contract or the creator can call this method. * @param _tokenId uint256 token ID. * @param _percentage uint8 wei royalty fee. */ function setPercentageForTokenRoyalty( uint256 _tokenId, uint8 _percentage ) external returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title IERC721 Non-Fungible Token Creator basic interface */ interface INifterTokenCreatorRegistry { /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function tokenCreator(uint256 _tokenId) external view returns (address payable); /** * @dev Sets the creator of the token * @param _tokenId uint256 ID of the token * @param _creator address of the creator for the token */ function setTokenCreator( uint256 _tokenId, address payable _creator ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./INifterRoyaltyRegistry.sol"; import "./INifterTokenCreatorRegistry.sol"; import "./INifter.sol"; /** * @title IERC1155 Non-Fungible Token Creator basic interface */ contract NifterTokenCreatorRegistry is Ownable, INifterTokenCreatorRegistry { using SafeMath for uint256; ///////////////////////////////////////////////////////////////////////// // State Variables ///////////////////////////////////////////////////////////////////////// // Mapping of ERC1155 token to it's creator. mapping(uint256 => address payable) private tokenCreators; address public nifter; ///////////////////////////////////////////////////////////////////////// // tokenCreator ///////////////////////////////////////////////////////////////////////// /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function tokenCreator(uint256 _tokenId) external view override returns (address payable) { if (tokenCreators[_tokenId] != address(0)) { return tokenCreators[_tokenId]; } return address(0); } ///////////////////////////////////////////////////////////////////////// // setNifter ///////////////////////////////////////////////////////////////////////// /** * @dev Set nifter contract address * @param _nifter uint256 ID of the token */ function setNifter(address _nifter) external onlyOwner { nifter = _nifter; } ///////////////////////////////////////////////////////////////////////// // setTokenCreator ///////////////////////////////////////////////////////////////////////// /** * @dev Sets the creator of the token * @param _tokenId uint256 ID of the token * @param _creator address of the creator for the token */ function setTokenCreator( uint256 _tokenId, address payable _creator ) external override { require( _creator != address(0), "setTokenCreator::Cannot set null address as creator" ); require(msg.sender == nifter || msg.sender == owner(), "setTokenCreator::only nifter and owner allowed"); tokenCreators[_tokenId] = _creator; } /** * @dev restore data from old contract, only call by owner * @param _oldAddress address of old contract. * @param _oldNifterAddress get the token ids from the old nifter contract. * @param _startIndex start index of array * @param _endIndex end index of array */ function restore(address _oldAddress, address _oldNifterAddress, uint256 _startIndex, uint256 _endIndex) external onlyOwner { NifterTokenCreatorRegistry oldContract = NifterTokenCreatorRegistry(_oldAddress); INifter oldNifterContract = INifter(_oldNifterAddress); uint256 length = oldNifterContract.getTokenIdsLength(); require(_startIndex < length, "wrong start index"); require(_endIndex <= length, "wrong end index"); for (uint i = _startIndex; i < _endIndex; i++) { uint256 tokenId = oldNifterContract.getTokenId(i); if (tokenCreators[tokenId] != address(0)) { tokenCreators[tokenId] = oldContract.tokenCreator(tokenId); } } } } // 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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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; } }
IERC721 Non-Fungible Token Creator basic interface/
interface INifterTokenCreatorRegistry { function tokenCreator(uint256 _tokenId) external view returns (address payable); function setTokenCreator( uint256 _tokenId, address payable _creator ) external; } }
242,674
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) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // 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 { // Public variable with address of owner address public owner; /** * Log ownership transference */ 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 { // Set the contract creator as the owner owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { // Check that sender is owner 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 { // Check for a non-null owner require(newOwner != address(0)); // Log ownership transference OwnershipTransferred(owner, newOwner); // Set new owner owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply = 0; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract MintableToken is ERC20Basic, Ownable { bool public mintingFinished = false; event Mint(address indexed to, uint256 amount); event MintFinished(); modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool); /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Extended ERC20 Token contract * @dev Custom Token (ERC20 Token) transactions. */ contract StyrasToken is MintableToken { using SafeMath for uint256; string public name = "Styras"; string public symbol = "STY"; uint256 public decimals = 18; uint256 public reservedSupply; uint256 public publicLockEnd = 1516060800; // GMT: Tuesday, January 16, 2018 0:00:00 uint256 public partnersLockEnd = 1530230400; // GMT: Friday, June 29, 2018 0:00:00 uint256 public partnersMintLockEnd = 1514678400; // GMT: Sunday, December 31, 2017 0:00:00 address public partnersWallet; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); /** * Initializes contract with initial supply tokens to the creator of the contract */ function StyrasToken(address partners, uint256 reserved) public { require(partners != address(0)); partnersWallet = partners; reservedSupply = reserved; assert(publicLockEnd <= partnersLockEnd); assert(partnersMintLockEnd < partnersLockEnd); } /** * @dev Gets the balance of the specified address. * @param investor The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address investor) public constant returns (uint256 balanceOfInvestor) { return balances[investor]; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _amount The amount to be transferred. */ function transfer(address _to, uint256 _amount) public returns (bool) { require(_to != address(0)); require((msg.sender != partnersWallet && now >= publicLockEnd) || now >= partnersLockEnd); require(_amount > 0 && _amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _amount uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(_to != address(0)); require((_from != partnersWallet && now >= publicLockEnd) || now >= partnersLockEnd); require(_amount > 0 && _amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require((msg.sender != partnersWallet && now >= publicLockEnd) || now >= partnersLockEnd); require(_value > 0 && _value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } /** * @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(_to != partnersWallet); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to mint reserved tokens to partners * @return A boolean that indicates if the operation was successful. */ function mintPartners(uint256 amount) onlyOwner canMint public returns (bool) { require(now >= partnersMintLockEnd); require(reservedSupply > 0); require(amount <= reservedSupply); totalSupply = totalSupply.add(amount); reservedSupply = reservedSupply.sub(amount); balances[partnersWallet] = balances[partnersWallet].add(amount); Mint(partnersWallet, amount); Transfer(address(0), partnersWallet, amount); return true; } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _to) public { require(_to != address(0)); wallet = _to; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); require(deposited[investor] > 0); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } contract Withdrawable is Ownable { bool public withdrawEnabled = false; address public wallet; event Withdrawed(uint256 weiAmount); function Withdrawable(address _to) public { require(_to != address(0)); wallet = _to; } modifier canWithdraw() { require(withdrawEnabled); _; } function enableWithdraw() onlyOwner public { withdrawEnabled = true; } // owner can withdraw ether here function withdraw(uint256 weiAmount) onlyOwner canWithdraw public { require(this.balance >= weiAmount); wallet.transfer(weiAmount); Withdrawed(weiAmount); } } contract StyrasVault is Withdrawable, RefundVault { function StyrasVault(address wallet) public Withdrawable(wallet) RefundVault(wallet) { // NOOP } function balanceOf(address investor) public constant returns (uint256 depositedByInvestor) { return deposited[investor]; } function enableWithdraw() onlyOwner public { require(state == State.Active); withdrawEnabled = true; } } /** * @title StyrasCrowdsale * @dev This is a capped and refundable crowdsale. */ contract StyrasCrowdsale is Ownable { using SafeMath for uint256; enum State { preSale, publicSale, hasFinalized } // how many token units a buyer gets per ether // minimum amount of funds (soft-cap) to be raised in weis // maximum amount of funds (hard-cap) to be raised in weis // minimum amount of weis to invest per investor uint256 public rate; uint256 public goal; uint256 public cap; uint256 public minInvest = 100000000000000000; // 0.1 ETH // presale treats uint256 public presaleDeadline = 1511827200; // GMT: Tuesday, November 28, 2017 00:00:00 uint256 public presaleRate = 4000; // 1 ETH == 4000 STY 33% bonus uint256 public presaleCap = 50000000000000000000000000; // 50 millions STY // pubsale treats uint256 public pubsaleDeadline = 1514678400; // GMT: Sunday, December 31, 2017 0:00:00 uint256 public pubsaleRate = 3000; // 1 ETH == 3000 STY uint256 public pubsaleCap = 180000000000000000000000000; // harrd cap = pubsaleCap + reservedSupply -> 200000000 DTY uint256 public reservedSupply = 20000000000000000000000000; // 10% max totalSupply uint256 public softCap = 840000000000000000000000; // 840 thousands STY // start and end timestamps where investments are allowed (both inclusive) // flag for investments finalization uint256 public startTime = 1511276400; // GMT: Tuesday, November 21, 2017 15:00:00 uint256 public endTime; // amount of raised money in wei // address where funds are collected uint256 public weiRaised = 0; address public escrowWallet; address public partnersWallet; // contract of the token being sold // contract of the vault used to hold funds while crowdsale is running StyrasToken public token; StyrasVault public vault; State public state; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event PresaleFinalized(); event Finalized(); function StyrasCrowdsale(address escrow, address partners) public { require(now < startTime); require(partners != address(0)); require(startTime < presaleDeadline); require(presaleDeadline < pubsaleDeadline); require(pubsaleRate < presaleRate); require(presaleCap < pubsaleCap); require(softCap <= pubsaleCap); endTime = presaleDeadline; escrowWallet = escrow; partnersWallet = partners; token = new StyrasToken(partnersWallet, reservedSupply); vault = new StyrasVault(escrowWallet); rate = presaleRate; goal = softCap.div(rate); cap = presaleCap.div(rate); state = State.preSale; assert(goal < cap); assert(startTime < endTime); } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(state < State.hasFinalized); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokenAmount = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokenAmount); TokenPurchase(msg.sender, beneficiary, weiAmount, tokenAmount); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); assert(vault.balance == weiRaised); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = startTime <= now && now <= endTime; bool nonZeroPurchase = msg.value > 0; bool withinCap = weiRaised < cap; bool overMinInvest = msg.value >= minInvest || vault.balanceOf(msg.sender) >= minInvest; return withinPeriod && nonZeroPurchase && withinCap && overMinInvest; } function hardCap() public constant returns (uint256) { return pubsaleCap + reservedSupply; } function goalReached() public constant returns (bool) { return weiRaised >= goal; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool afterPeriod = now > endTime; bool capReached = weiRaised >= cap; return afterPeriod || capReached; } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(state == State.hasFinalized); require(!goalReached()); vault.refund(msg.sender); } function enableWithdraw() onlyOwner public { require(goalReached()); vault.enableWithdraw(); } // if crowdsale is successful, owner can withdraw ether here function withdraw(uint256 _weiAmountToWithdraw) onlyOwner public { require(goalReached()); vault.withdraw(_weiAmountToWithdraw); } function finalizePresale() onlyOwner public { require(state == State.preSale); require(hasEnded()); uint256 weiDiff = 0; uint256 raisedTokens = token.totalSupply(); rate = pubsaleRate; if (!goalReached()) { weiDiff = (softCap.sub(raisedTokens)).div(rate); goal = weiRaised.add(weiDiff); } weiDiff = (pubsaleCap.sub(raisedTokens)).div(rate); cap = weiRaised.add(weiDiff); endTime = pubsaleDeadline; state = State.publicSale; assert(goal < cap); assert(startTime < endTime); PresaleFinalized(); } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(state == State.publicSale); require(hasEnded()); finalization(); state = State.hasFinalized; Finalized(); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); token.mintPartners(reservedSupply); } else { vault.enableRefunds(); } vault.transferOwnership(owner); token.transferOwnership(owner); } }
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(_to != partnersWallet); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; }
7,316,246