lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.8.10
//////////////////////////////////////////////////////////////////////////
/// @notice Withdraw funds to charity address.
function _withdrawCharityBalance()
        internal
    {
        uint256 value = charityBalance;

        // checks: no money to withdraw.
        if (value == 0) {
            return;
        }

        // effects: reset charity balance to zero.
        charityBalance = 0;

        // interactions: send money to charity address.
        (bool sent, ) = charity.call{value: value}("");
        require(sent);
    }
// Solidity 0.8.10
/// @notice Withdraw funds to owner address.
/// @param destination the address that receives the funds.
function _withdrawOwnerBalance(address payable destination)
        internal
    {
        uint256 value = ownerBalance;

        // checks: no money to withdraw.
        if (value == 0) {
            return;
        }

        // effects: reset owner balance to zero.
        ownerBalance = 0;

        // interactions: send money to destination address.
        (bool sent, ) = destination.call{value: value}("");
        require(sent);
    }
// Solidity 0.8.10
/// @notice Sets the time offset of the given token id.
/// @dev Use minutes because some timezones (like IST) are offset by half an hour.
/// @param id the NFT unique id.
/// @param offsetMinutes the offset in minutes.
function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes)
        public
    {
        // checks: id exists
        if (ownerOf[id] == address(0)) {
            revert EthTime__DoesNotExist();
        }

        // checks: sender is owner.
        if (ownerOf[id] != msg.sender) {
            revert EthTime__NotOwner();
        }

        // checks: validate time offset
        _validateTimeOffset(offsetMinutes);

        // effects: update time offset
        timeOffsetMinutes[id] = offsetMinutes;

        emit TimeOffsetUpdated(id, offsetMinutes);
    }
// Solidity 0.8.10
/// @notice Mint a new NFT, transfering ownership to the given account.
/// @dev If the token id already exists, this method fails.
/// @param to the NFT ower.
/// @param offsetMinutes the time offset in minutes.
/// @param id the NFT unique id.
function mint(address to, int128 offsetMinutes, uint256 id)
        public
        payable
        nonReentrant
        virtual
    {
        // interactions: mint.
        uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value);
    
        // interactions: send back leftover value.
        if (valueLeft > 0) {
            (bool success, ) = msg.sender.call{value: valueLeft}("");
            require(success);
        }
    }
// Solidity 0.8.10
/// @notice Get the price for minting the next `count` NFT.
function getBatchMintPrice(uint256 count)
        public
        view
        returns (uint256)
    {
        // checks: can mint count nfts
        _validateBatchMintCount(count);

        uint256 supply = totalSupply;
        uint256 price = 0;
        for (uint256 i = 0; i < count; i++) {
            price += _priceAtSupplyLevel(supply + i);
        }
        
        return price;
    }
// Solidity 0.8.10
//////////////////////////////////////////////////////////////////////////
/// @notice Returns the URI with the NFT metadata.
/// @dev Returns the base64 encoded metadata inline.
/// @param id the NFT unique id
function tokenURI(uint256 id)
        public
        view
        override
        returns (string memory)
    {
        if (ownerOf[id] == address(0)) {
            revert EthTime__DoesNotExist();
        }

        string memory tokenId = Strings.toString(id);

        (uint256 hour, uint256 minute) = _adjustedHourMinutes(id);

        bytes memory topHue = _computeHue(historyAccumulator[id], id);
        bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id);

        int128 offset = timeOffsetMinutes[id];
        bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-');
        uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset));

        return
            string(
                bytes.concat(
                    'data:application/json;base64,',
                    bytes(
                        Base64.encode(
                            bytes.concat(
                                '{"name": "ETH Time #',
                                bytes(tokenId),
                                '", "description": "ETH Time", "image": "data:image/svg+xml;base64,',
                                bytes(_tokenImage(topHue, bottomHue, hour, minute)),
                                '", "attributes": [{"trait_type": "top_color", "value": "hsl(', topHue, ',100%,89%)"},',
                                '{"trait_type": "bottom_color", "value": "hsl(', bottomHue, ',77%,36%)"},',
                                '{"trait_type": "time_offset", "value": "', offsetSign, bytes(Strings.toString(offsetUnsigned)),  '"},',
                                '{"trait_type": "time", "value": "', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '"}]}'
                            )
                        )
                    )
                )
            );
    }
// Solidity 0.8.10
/// @dev Generate a preview of the token that will be minted.
/// @param to the minter.
/// @param id the NFT unique id.
function tokenImagePreview(address to, uint256 id)
        public
        view
        returns (string memory)
    {
        (uint256 hour, uint256 minute) = _adjustedHourMinutes(id);

        bytes memory topHue = _computeHue(uint160(id >> 4), id);
        bytes memory bottomHue = _computeHue(uint160(to), id);

        return _tokenImage(topHue, bottomHue, hour, minute);
    }
// Solidity 0.8.10
/// @dev Generate the SVG image for the given NFT.
function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute)
        internal
        pure
        returns (string memory)
    {

        return
            Base64.encode(
                bytes.concat(
                    '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">',
                    '<linearGradient id="bg" gradientTransform="rotate(90)">',
                    '<stop offset="0%" stop-color="hsl(', topHue, ',100%,89%)"/>',
                    '<stop offset="100%" stop-color="hsl(', bottomHue, ',77%,36%)"/>',
                    '</linearGradient>',
                    '<rect x="0" y="0" width="1000" height="1000" fill="url(#bg)"/>',
                    _binaryHour(hour),
                    _binaryMinute(minute),
                    '</svg>'
                )
            );
    }
// Solidity 0.8.10
/// @dev Returns the colors to be used to display the time.
/// The first 3 bytes are used for the first digit, the remaining 4 bytes
/// for the second digit.
function _binaryColor(uint256 n)
        internal
        pure
        returns (bytes[7] memory)
    {
        unchecked {
            uint256 firstDigit = n / 10;
            uint256 secondDigit = n % 10;

            return [
                (firstDigit & 0x1 != 0) ? onColor : offColor,
                (firstDigit & 0x2 != 0) ? onColor : offColor,
                (firstDigit & 0x4 != 0) ? onColor : offColor,

                (secondDigit & 0x1 != 0) ? onColor : offColor,
                (secondDigit & 0x2 != 0) ? onColor : offColor,
                (secondDigit & 0x4 != 0) ? onColor : offColor,
                (secondDigit & 0x8 != 0) ? onColor : offColor
            ];
        }
    }
// Solidity 0.4.24
// takes current marketcap of USD and calculates the algorithmic rebase lag
// returns 10 ** 9 rebase lag factor
function getAlgorithmicRebaseLag(int256 supplyDelta) public view returns (uint256) {
        if (dollars.totalSupply() >= 30000000 * 10 ** 9) {
            return 30 * 10 ** 9;
        } else {
            if (supplyDelta < 0) {
                uint256 dollarsToBurn = uint256(supplyDelta.abs()); // 1.238453076e15
                return uint256(100 * 10 ** 9).sub((dollars.totalSupply().sub(1000000 * 10 ** 9)).div(500000));
            } else {
                return uint256(29).mul(dollars.totalSupply().sub(1000000 * 10 ** 9)).div(35000000).add(1 * 10 ** 9);
            }
        }
    }
// Solidity 0.8.4
/**
 * @notice list the ids of all the heroes in _owner's wallet
 * @param _owner is the wallet address of the hero owner
 * */
function listMyHeroes(address _owner) 
        external 
        view 
        returns (uint256[] memory) 
    {
        uint256 nHeroes = balanceOf(_owner);
        // if zero return an empty array
        if (nHeroes == 0) {
            return new uint256[](0);
        } else {
            uint256[] memory heroList = new uint256[](nHeroes);
            uint256 ii;
            for (ii = 0; ii < nHeroes; ii++) {
                heroList[ii] = tokenOfOwnerByIndex(_owner, ii);
            }
            return heroList;
        }
    }
// Solidity 0.8.4
/**
 * @notice mint brand new HunkyHero nfts
 * @param numHeroes is the number of heroes to mint
 */
function mintHero(uint256 numHeroes) public payable saleIsLive {
        require(
            (numHeroes > 0) && (numHeroes <= MINT_MAX),
            "you can mint between 1 and 100 heroes at once"
        );
        require(
            msg.value >= (numHeroes * mintPrice),
            "not enough Ether sent with tx"
        );

        //mint dem heroes
        _mintHeroes(msg.sender, numHeroes);
        return;
    }
// Solidity 0.8.4
/**
 * @notice mint heroes from the whitelist
 * @param _sig whitelist signature
 * @param _quota wl quota awarded
 * @param _num number of Heroes to mint!
 */
function herolistMint(
        bytes calldata _sig,
        uint256 _quota,
        uint256 _num
    ) 
        public
        presaleIsLive
    {
        require(_num > 0);

        //overclaiming? already minted?
        require(_num + minted[msg.sender] <= _quota,
            "not enough WL mints left"
        );

        // check msg.sender is on the whitelist
        require(legitSigner(_sig, _quota), "invalid signature");
        
        //effects
        minted[msg.sender] += _num;

        //mint dem heroes
        _mintHeroes(msg.sender, _num);
        return;
    }
// Solidity 0.8.4
/**
 * @notice transfer team membership to a different address
 * team members have admin rights with onlyTeam modifier
 * @param to is the address to transfer admin rights to
 */
function transferMembership(address to) public onlyTeam {
        teamMap[msg.sender] = false;
        teamMap[to] = true;

        for (uint256 i = 0; i < 3; i++) {
            if (teamList[i] == msg.sender) {
                teamList[i] = to;
            }
        }
        emit MembershipTransferred(msg.sender, to);
    }
// Solidity 0.8.4
/**
 * @notice mint function called by multiple other functions
 * @notice token IDs start at 1 (not 0)
 * @param _to address to mint to
 * @param _num number of heroes to mint
 */
function _mintHeroes(address _to, uint256 _num) private {
        require(currentSupply + _num <= MAX_HEROES, "not enough Heroes left");

        for (uint256 h = 0; h < _num; h++) {
            currentSupply ++;
            _safeMint(_to, currentSupply);
        }
    }
// Solidity 0.8.4
/**
 * @notice does signature _sig contain a legit hash and 
 * was it signed by msgSigner?
 * @param _sig the signature to inspect
 * @dev the signer is recovered and compared to msgSigner
 */
function legitSigner(bytes memory _sig, uint256 _numHashed)
    private
    view
    returns (bool)
    {
        //hash the sender and this address
        bytes32 checkHash = keccak256(abi.encodePacked(
            msg.sender,
            address(this),
            _numHashed
        ));

        //the _sig should be a signed version of checkHash
        bytes32 ethHash = ECDSA.toEthSignedMessageHash(checkHash);
        address recoveredSigner = ECDSA.recover(ethHash, _sig);
        return (recoveredSigner == msgSigner);
    }
// Solidity 0.5.17
/**
 * @dev Returns the URI for a given token ID. May return an empty string.
 *
 * If the token's URI is non-empty and a base URI was set (via
 * {_setBaseURI}), it will be added to the token ID's URI as a prefix.
 *
 * Reverts if the token ID does not exist.
 */
function tokenURI(uint256 tokenId) external view returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory _tokenURI = _tokenURIs[tokenId];

        // Even if there is a base URI, it is only appended to non-empty token-specific URIs
        if (bytes(_tokenURI).length == 0) {
            return "";
        } else {
            // abi.encodePacked is being used to concatenate strings
            return string(abi.encodePacked(_baseURI, _tokenURI));
        }
    }
// Solidity 0.8.3
/**
 * @dev Returns timestamp at which accumulated M26s have last been claimed for a {tokenIndex}.
 */
function lastClaim(uint256 tokenIndex) public view returns (uint256) {
        require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
        require(tokenIndex < _mars.totalSupply(), "NFT at index has not been minted yet");

        uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : _emissionStartTimestamp;
        return lastClaimed;
    }
// Solidity 0.8.3
/**
 * @dev Returns amount of accumulated M26s for {tokenIndex}.
 */
function accumulated(uint256 tokenIndex) public view returns (uint256) {
        require(block.timestamp > _emissionStartTimestamp, "Emission has not started yet");
        require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
        require(tokenIndex < _mars.totalSupply(), "NFT at index has not been minted yet");

        uint256 lastClaimed = lastClaim(tokenIndex);

        // Sanity check if last claim was on or after emission end
        if (lastClaimed >= _emissionEndTimestamp) return 0;

        uint256 accumulationPeriod = block.timestamp < _emissionEndTimestamp
            ? block.timestamp
            : _emissionEndTimestamp; // Getting the min value of both
        uint256 totalAccumulated = accumulationPeriod
            .sub(lastClaimed)
            .mul(_emissionPerDay)
            .div(_SECONDS_IN_A_DAY);

        // If claim hasn't been done before for the index, add initial allotment (plus prereveal multiplier if applicable)
        if (lastClaimed == _emissionStartTimestamp) {
            uint256 initialAllotment = _mars.isMintedBeforeReveal(tokenIndex) == true
                ? INITIAL_ALLOTMENT.mul(PRE_REVEAL_MULTIPLIER)
                : INITIAL_ALLOTMENT;
            totalAccumulated = totalAccumulated.add(initialAllotment);
        }

        return totalAccumulated;
    }
// Solidity 0.8.3
/**
 * @dev Sets token hashes in the initially set order starting at {startIndex}.
 */
function setInitialSequenceTokenHashesAtIndex(
        uint256 startIndex,
        bytes32[] memory tokenHashes
    ) public onlyOwner {
        require(startIndex <= _intitialSequenceTokenHashes.length);

        for (uint256 i = 0; i < tokenHashes.length; i++) {
            if ((i + startIndex) >= _intitialSequenceTokenHashes.length) {
                _intitialSequenceTokenHashes.push(tokenHashes[i]);
            } else {
                _intitialSequenceTokenHashes[i + startIndex] = tokenHashes[i];
            }
        }

        require(_intitialSequenceTokenHashes.length <= _maxSupply);
    }
// Solidity 0.8.3
// Source: verifyIPFS (https://github.com/MrChico/verifyIPFS/blob/master/contracts/verifyIPFS.sol)
// @author Martin Lundfall (martin.lundfall@consensys.net)
// @dev Converts hex string to base 58
function _toBase58(bytes memory source)
        internal
        pure
        returns (string memory)
    {
        if (source.length == 0) return new string(0);
        uint8[] memory digits = new uint8[](46);
        digits[0] = 0;
        uint8 digitlength = 1;
        for (uint256 i = 0; i < source.length; ++i) {
            uint256 carry = uint8(source[i]);
            for (uint256 j = 0; j < digitlength; ++j) {
                carry += uint256(digits[j]) * 256;
                digits[j] = uint8(carry % 58);
                carry = carry / 58;
            }

            while (carry > 0) {
                digits[digitlength] = uint8(carry % 58);
                digitlength++;
                carry = carry / 58;
            }
        }
        return string(_toAlphabet(_reverse(_truncate(digits, digitlength))));
    }
// Solidity 0.4.18
// ------------------------------------------------------------------------
// 1000 Paparazzo Tokens per 1 ETH
// ------------------------------------------------------------------------
function () public payable {
        require(now >= startDate && now <= endDate);
        uint tokens;
        if (now <= bonusEnds) {
            tokens = msg.value * 10000;
        } else {
            tokens = msg.value * 1000;
        }
        balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
        _totalSupply = safeAdd(_totalSupply, tokens);
        Transfer(address(0), msg.sender, tokens);
        owner.transfer(msg.value);
    }
// Solidity 0.7.6
/**
 * @param beneficiary Token beneficiary
 * @param paymentToken ERC20 payment token address
 * @param weiAmount Amount of wei contributed
 * @param tokenAmount Number of tokens to be purchased
 */
function _preValidatePurchase(
        address beneficiary,
        address paymentToken,
        uint256 weiAmount,
        uint256 tokenAmount
    )
        internal
        view
        override
        whenNotPaused
        onlyWhileOpen
        tokenCapNotExceeded(tokensSold, tokenAmount)
        holdsSufficientTokens(beneficiary)
        isWhitelisted(beneficiary)
    {
        // TODO: Investigate why modifier and require() don't work consistently for beneficiaryCapNotExceeded()
        if (
            getTokensPurchasedBy(beneficiary).add(tokenAmount) >
            getBeneficiaryCap(beneficiary)
        ) {
            revert("LaunchpadCrowdsaleWithVesting: beneficiary cap exceeded");
        }

        super._preValidatePurchase(
            beneficiary,
            paymentToken,
            weiAmount,
            tokenAmount
        );
    }
// Solidity 0.8.3
/**
 * @dev Returns the set token URI, i.e. IPFS v0 CID, of {tokenId}.
 * Prefixed with ipfs://
 */
function tokenURI(uint256 tokenId) public view override returns (string memory) {
        require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
        require(_startingIndex > 0, "Tokens have not been assigned yet");

        uint256 initialSequenceIndex = _toInitialSequenceIndex(tokenId);
        return tokenURIOfInitialSequenceIndex(initialSequenceIndex);
    }
// Solidity 0.4.24
// amount in is 10 ** 9 decimals
function burn(uint256 amount)
        external
        updateAccount(msg.sender)
    {
        require(!reEntrancyMutex, "RE-ENTRANCY GUARD MUST BE FALSE");
        reEntrancyMutex = true;

        require(amount != 0, 'AMOUNT_MUST_BE_POSITIVE');
        require(_remainingDollarsToBeBurned != 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO');
        require(amount <= _dollarBalances[msg.sender], 'INSUFFICIENT_DOLLAR_BALANCE');
        require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS');

        _burn(msg.sender, amount);

        reEntrancyMutex = false;
    }
// Solidity 0.8.3
/**
 * @dev Gets current NFT price based on already sold tokens.
 */
function getNFTPrice() public view returns (uint256) {
        if (_numSoldTokens < 800) {
            return 0.01 ether; 
        } else if (_numSoldTokens < 4400) {
            return 0.02 ether; 
        } else if (_numSoldTokens < 8800) {
            return 0.03 ether; 
        } else if (_numSoldTokens < 12600) {
            return 0.05 ether; 
        } else if (_numSoldTokens < 14040) {
            return 0.1 ether;
        } else if (_numSoldTokens < 14392) {
            return 0.3 ether;
        } else {
            return 1 ether;
        }
    }
// Solidity 0.8.3
/**
 * @dev Mints Mars NFTs
 */
function mint(uint256 numberOfNfts) public payable {
        require(block.timestamp >= _saleStartTimestamp, "Sale has not started");
        require(totalSupply() < MAX_SUPPLY, "Sale has already ended");
        require(numberOfNfts > 0, "Cannot buy 0 NFTs");
        require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once");
        require(_numSoldTokens.add(numberOfNfts) <= MAX_SUPPLY.sub(RESERVED_SUPPLY), "Exceeds max number of sellable NFTs");
        require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct");

        for (uint i = 0; i < numberOfNfts; i++) {
            uint mintIndex = totalSupply();

            _numSoldTokens++;
            require(mintIndex < MAX_SUPPLY, "Exceeds max number of NFTs in existence");

            if (block.timestamp < _revealTimestamp) {
                _mintedBeforeReveal[mintIndex] = true;
            }
            _safeMint(msg.sender, mintIndex);
        }

        // Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense 
        if (_startingIndexBlock == 0 && (_numSoldTokens >= MAX_SUPPLY.sub(RESERVED_SUPPLY) || block.timestamp >= _revealTimestamp)) {
            _startingIndexBlock = block.number;
        }
    }
// Solidity 0.8.3
/**
 * @dev Used to migrate already minted NFTs of old contract.
 */
function mintReserved(address to, uint256 numOfNFTs) public onlyOwner {
        require(totalSupply().add(numOfNFTs) <= MAX_SUPPLY, "Exceeds max supply of NFTs");
        require(_numMintedReservedTokens.add(numOfNFTs) <= RESERVED_SUPPLY, "Exceeds max num of reserved NFTs");

        for (uint j = 0; j < numOfNFTs; j++) {
            uint tokenId = totalSupply();

            if (block.timestamp < _revealTimestamp) {
                _mintedBeforeReveal[tokenId] = true;
            }
            _numMintedReservedTokens++;
            _safeMint(to, tokenId);
        }
    }
// Solidity 0.8.3
/**
 * @dev Finalize starting index
 */
function finalizeStartingIndex() public {
        require(_startingIndex == 0, "Starting index is already set");
        require(_startingIndexBlock != 0, "Starting index block must be set");
        
        _startingIndex = uint(blockhash(_startingIndexBlock)) % MAX_SUPPLY;
        // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
        if (block.number.sub(_startingIndexBlock) > 255) {
            _startingIndex = uint(blockhash(block.number - 1)) % MAX_SUPPLY;
        }
        // Prevent default sequence
        if (_startingIndex == 0) {
            _startingIndex = _startingIndex.add(1);
        }
    }
// Solidity 0.8.3
/**
 * @dev Changes the name for Mars tile tokenId
 */
function changeName(uint256 tokenId, string memory newName) public {
        address owner = ownerOf(tokenId);

        require(_msgSender() == owner, "ERC721: caller is not the owner");
        require(_validateName(newName) == true, "Not a valid new name");
        require(sha256(bytes(newName)) != sha256(bytes(_tokenNames[tokenId])), "New name is same as the current one");
        require(isNameReserved(newName) == false, "Name already reserved");

        _m26.transferFrom(msg.sender, address(this), _nameChangePrice);
        // If already named, dereserve old name
        if (bytes(_tokenNames[tokenId]).length > 0) {
            _toggleReserveName(_tokenNames[tokenId], false);
        }
        _toggleReserveName(newName, true);
        _tokenNames[tokenId] = newName;
        _m26.burn(_nameChangePrice);
        emit NameChange(tokenId, newName);
    }
// Solidity 0.6.12
/**
 * Get staked rank
 */
function getStakedRank(address staker) external view returns (uint256) {
        uint256 rank = 1;
        uint256 senderStakedAmount = _stakeMap[staker].stakedAmount;
        
        for(uint i=0; i<_stakers.length; i++) {
            if(_stakers[i] != staker && senderStakedAmount < _stakeMap[_stakers[i]].stakedAmount)
                rank = rank.add(1);
        }
        return rank;
    }