lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.8.7
/**
 * @dev Function returns collateral balance of this NFT in _erc20
 * colleteral of wrapped token
 *
 * @param _wrappedId  new protocol NFT id from this contarct
 * @param _erc20 - collateral token address
 */
function getERC20CollateralBalance(uint256 _wrappedId, address _erc20) public view returns (uint256) {
        ERC20Collateral[] memory e = erc20Collateral[_wrappedId];
        for (uint256 i = 0; i < e.length; i ++) {
            if (e[i].erc20Token == _erc20) {
                return e[i].amount;
            }
        }
    }
// Solidity 0.8.7
/**
 * @dev Function returns all ERC20 collateral to user who unWrap
 * protocol token. Returns true if all tokens are transfered.
 * Otherwise returns false. In that case  need just call unWrap721
 * one more time
 *
 *
 * @param _tokenId -wrapped token
 *
 */
function _returnERC20Collateral(uint256 _tokenId) internal returns (bool) {
        //First we need release erc20 collateral, because erc20 transfers are
        // can be expencive
        ERC20Collateral[] storage e = erc20Collateral[_tokenId];
        if (e.length > 0) { 
            for (uint256 i = e.length; i > 0; i --){
                if (e[i-1].amount > 0) {
                    // we need this try for protect from malicious 
                    // erc20 contract that  can block unWrap NFT
                    try 
                        // We dont use SafeTransfer because try works only for  external function call
                        // https://docs.soliditylang.org/en/v0.8.6/control-structures.html#try-catch

                        IERC20(e[i-1].erc20Token).transfer(msg.sender,  e[i-1].amount) {
                            e[i-1].amount = 0;
                    } catch {
                        emit SuspiciousFail(e[i-1].erc20Token, e[i-1].amount);
                    } 
                    // comment string below due in some case it c can be very costly
                    // https://docs.soliditylang.org/en/v0.8.9/types.html#array-members   
                    //e.pop();
                    if (gasleft() <= 10_000) {
                        emit PartialUnWrapp(_tokenId, msg.sender);
                        return false;
                    }
                }
            }

        }
        return true;

    }
// Solidity 0.8.7
/**
 * @dev Returns a boolean array where each value corresponds to the
 * interfaces passed in and whether they're supported or not. This allows
 * you to batch check interfaces for a contract where your expectation
 * is that some interfaces may not be supported.
 *
 * See {IERC165-supportsInterface}.
 *
 * _Available since v3.4._
 */
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
        internal
        view
        returns (bool[] memory)
    {
        // an array of booleans corresponding to interfaceIds and whether they're supported or not
        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);

        // query support of ERC165 itself
        if (supportsERC165(account)) {
            // query support of each interface in interfaceIds
            for (uint256 i = 0; i < interfaceIds.length; i++) {
                interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
            }
        }

        return interfaceIdsSupported;
    }
// Solidity 0.8.7
/// !!!!For gas safe this low levelfunction has NO any check before wrap
/// So you have NO warranty to do Unwrap well
function WrapForFarming(
        address  _receiver,
        ERC20Collateral memory _erc20Collateral,
        uint256 _unwrapAfter
    ) public payable 
    {
        require(_receiver != address(0), "No zero address");
        require(!isDepricated, "Pool is depricated for new stakes");
        // 1.topup wrapper contract with erc20 that would be added in collateral
        IERC20(_erc20Collateral.erc20Token).safeTransferFrom(
            msg.sender, 
            address(this), 
            _erc20Collateral.amount
        );

        // 2.Mint wrapped NFT for receiver and populate storage
        lastWrappedNFTId += 1;
        _mint(_receiver, lastWrappedNFTId);
        wrappedTokens[lastWrappedNFTId] = NFT(
            address(0), // _original721, 
            0, // _tokenIds[i], 
            msg.value,        // native blockchain asset
            0,                // accumalated fee token
            _unwrapAfter,     // timelock
            0,                //_transferFee,
            address(0),       // _royaltyBeneficiary,
            0,                //_royaltyPercent,
            0,                //_unwraptFeeThreshold,
            address(0),       //_transferFeeToken,
            AssetType.UNDEFINED,
            0
        );

        // 3.Add erc20 collateral
        ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId];
        coll.push(ERC20Collateral({
            erc20Token: _erc20Collateral.erc20Token, 
            amount: _erc20Collateral.amount
        }));
        emit Wrapped(address(0), 0, lastWrappedNFTId);

        // 4. Register farming
        NFTReward storage r = rewards[lastWrappedNFTId];
        r.stakedDate = block.timestamp;
        emit Staked(lastWrappedNFTId, _erc20Collateral.erc20Token, _erc20Collateral.amount);
    }
// Solidity 0.8.7
////////////////////////////////////////////////////////////////
//////////     Admins                                     //////
////////////////////////////////////////////////////////////////
function setRewardSettings(
        address _erc20, 
        uint256 _settingsSlotId, 
        uint256 _period, 
        uint256 _percent
    ) external onlyOwner {
        
        require(rewardSettings[_erc20].length > 0, "There is no settings for this token");
        RewardSettings[] storage set = rewardSettings[_erc20];
        set[_settingsSlotId].period = _period;
        emit SettingsChanged(_erc20, _settingsSlotId);
    }
// Solidity 0.8.7
/**
 * @dev Function returns tokenURI of **underline original token**
 *
 * @param _tokenId id of protocol token (new wrapped token)
 */
function tokenURI(uint256 _tokenId) public view virtual override 
        returns (string memory) 
    {
        NFT storage nft = wrappedTokens[_tokenId];
        if (nft.tokenContract != address(0)) {
            return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId);
        } else {
            return string(abi.encodePacked(
            _baseURI(),
            uint160(address(this)).toHexString(),
            "/", _tokenId.toString())
            );
        }    
        
    }
// Solidity 0.5.16
/**
 * @dev Adds a new batch to the `batchMapping` and increases the
 *      count of `totalNumberOfBatches`
 */
function addNewBatch(
        uint256 _totalSpots,
        uint256 _batchStartTimestamp,
        uint256 _depositAmount
    )
        public
        onlyOwner
    {
        require(
            _batchStartTimestamp >= currentTimestamp(),
            "WaitlistBatch: batch start time cannot be in the past"
        );

        require(
            _depositAmount > 0,
            "WaitlistBatch: deposit amount cannot be 0"
        );

        require(
            _totalSpots > 0,
            "WaitlistBatch: batch cannot have 0 spots"
        );

        Batch memory batch = Batch(
            _totalSpots,
            0,
            _batchStartTimestamp,
            _depositAmount,
            0
        );

        batchMapping[nextBatchNumber] = batch;
        nextBatchNumber = nextBatchNumber + 1;

        emit NewBatchAdded(
            _totalSpots,
            _batchStartTimestamp,
            _depositAmount,
            nextBatchNumber - 1
        );
    }
// Solidity 0.5.16
/**
 * @dev Approves a batch. Users can then start reclaiming their deposit
 *      after the retrieval date delay.
 */
function approveBatch(
        uint256 _batchNumber
    )
        external
        onlyOwner
    {
        require(
            _batchNumber > 0 && _batchNumber < nextBatchNumber,
            "WaitlistBatch: the batch does not exist"
        );

        Batch storage batch = batchMapping[_batchNumber];

        require(
            batch.approvedAt == 0,
            "WaitlistBatch: the batch is already approved"
        );

        batch.approvedAt = currentTimestamp();

        emit BatchApproved(_batchNumber);
    }
// Solidity 0.8.9
/// @notice Check if ID is valid.
function validId(uint16 tokenId) public pure returns (bool) {
        return tokenId >= 11111 && tokenId <= 55555
            && tokenId % 10 > 0 && tokenId % 10 <= 5
            && tokenId % 100 > 10 && tokenId % 100 <= 55
            && tokenId % 1000 > 100 && tokenId % 1000 <= 555
            && tokenId % 10000 > 1000 && tokenId % 10000 <= 5555;
    }
// Solidity 0.6.12
/**
 * @notice Adds a new acceted code hash.
 * @param _code The new code hash.
 */
function addCode(bytes32 _code) public onlyOwner {
        require(_code != bytes32(0), "AWR: empty _code");
        Info storage code = acceptedCodes[_code];
		if(!code.exists) {
			codes.push(_code);
			code.exists = true;
        	code.index = uint128(codes.length - 1);
			emit CodeAdded(_code);
		}
    }
// Solidity 0.6.12
/**
 * @notice Adds a new acceted implementation.
 * @param _impl The new implementation.
 */
function addImplementation(address _impl) public onlyOwner {
        require(_impl != address(0), "AWR: empty _impl");
        Info storage impl = acceptedImplementations[_impl];
		if(!impl.exists) {
			implementations.push(_impl);
			impl.exists = true;
        	impl.index = uint128(implementations.length - 1);
			emit ImplementationAdded(_impl);
		}
    }
// Solidity 0.5.12
/**
 * @dev Withdraw ether and token
 * @param message Signed message
 * @param v Signature hash
 * @param r Signature hash
 * @param s Signature hash
 * @param tokenaddr Token address to be withdraw
 * @param to Receiver address 
 * @param amount Amount to be withdraw 
 */
function withdraw(string memory message, uint8  v, bytes32 r, bytes32 s, uint8 type_, address tokenaddr, address payable _from, address payable to, uint256 amount, uint256 profitValue) contractStatus public  returns(bool) {
        require(hashComformation[message] != true); 
        require(verify(string(strConcat(string(code),message)),v,r,s) == msg.sender);
        require(type_ == 0 || type_ == 1);
         if(type_ == 0){
             require(tokenaddr == address(0));
             if(amount >= userBalance[_from][tokenaddr] && amount <= 0) revert();
                to.transfer(amount);    
                userBalance[_from][tokenaddr] = userBalance[_from][tokenaddr].sub(amount);
                adminProfit[admin][address(0)] = adminProfit[admin][address(0)].add(profitValue);
        }
        else{
            require(tokenaddr != address(0) && amount > 0);
            require(userBalance[_from][tokenaddr] >= amount);
            ERC20(tokenaddr).transfer(to, amount);
            userBalance[_from][tokenaddr] = userBalance[_from][tokenaddr].sub(amount);
            adminProfit[admin][tokenaddr] = adminProfit[admin][tokenaddr].add(profitValue);
        }
        hashComformation[message] = true;
        return true;
    }
// Solidity 0.5.12
/**
 * @dev Profit Withdraw of the admin
 * @param type_ Either token or ether
 * @param tokenAddr Token address 
 * @param amount Amount to be Withdraw
 */
function profitWithdraw(uint256 type_,address tokenAddr,uint256 amount) onlyOwner public returns(bool){
        require(amount > 0);
        require(type_ ==0 || type_ == 1);
        
        if(type_== 0){
            require(amount > 0 && amount <= adminProfit[admin][address(0)]);
            msg.sender.transfer(amount);
            adminProfit[admin][address(0)] = adminProfit[admin][address(0)].sub(amount);
        }
        else{
            require(tokenAddr != address(0)) ;
            require(getTokenBalance(tokenAddr,address(this)) >= amount);
            ERC20(tokenAddr).transfer(admin, amount);
            adminProfit[admin][tokenAddr] = adminProfit[admin][tokenAddr].sub(amount);
        }
    }
// Solidity 0.5.12
/**
 * @dev String concatenation
 */
function strConcat(string memory _a, string memory _b) private pure returns (bytes memory){
        bytes memory _ba = bytes(_a);
        bytes memory _bb = bytes(_b);
        string memory ab = new string(_ba.length + _bb.length);
        bytes memory babcde = bytes(ab);
        uint k = 0;
        for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
        for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
        return babcde;
    }
// Solidity 0.5.12
/**
 * @dev Verification of the Signature
 */
function verify(string memory  message, uint8 v, bytes32 r, bytes32 s) private pure returns (address signer) {
        string memory header = "\x19Ethereum Signed Message:\n000000";
        uint256 lengthOffset;
        uint256 length;
        assembly {
            length := mload(message)
            lengthOffset := add(header, 57)
        }
        require(length <= 999999);
        uint256 lengthLength = 0;
        uint256 divisor = 100000; 
        while (divisor != 0) {
            uint256 digit = length / divisor;
            if (digit == 0) {
             
                if (lengthLength == 0) {
                      divisor /= 10;
                      continue;
                    }
            }
            lengthLength++;
            length -= digit * divisor;
            divisor /= 10;
            digit += 0x30;
            lengthOffset++;
            assembly {
                mstore8(lengthOffset, digit)
            }
        }  
        if (lengthLength == 0) {
            lengthLength = 1 + 0x19 + 1;
        } else {
            lengthLength += 1 + 0x19;
        }
        assembly {
            mstore(header, lengthLength)
        }
        bytes32 check = keccak256(abi.encodePacked(header, message));
        return ecrecover(check, v, r, s);
    }
// Solidity 0.8.7
// // public view functions
// never use these for functions ever, they are expensive af and for view only 
function walletOfOwner(address address_) public virtual view 
    returns (uint256[] memory) {
        uint256 _balance = balanceOf[address_];
        uint256[] memory _tokens = new uint256[] (_balance);
        uint256 _index;
        uint256 _loopThrough = totalSupply;
        for (uint256 i = 0; i < _loopThrough; i++) {
            if (ownerOf[i] == address(0x0) && _tokens[_balance - 1] == 0) {
                _loopThrough++; 
            }
            if (ownerOf[i] == address_) { 
                _tokens[_index] = i; _index++; 
            }
        }
        return _tokens;
    }
// Solidity 0.8.7
// Fusion Mechanism
function fusion(uint256 parent1_, uint256 parent2_, uint256 amount_) external publicMintEnabled {
        require(parent1_ != parent2_,
            "Parents can't be the same!");
        require(msg.sender == SpaceYetis.ownerOf(parent1_) 
            && msg.sender == SpaceYetis.ownerOf(parent2_),
            "You do not own these Yetis!");
        
        uint256 _totalFusionCost = fusionCost * amount_;

        require(Plasma.balanceOf(msg.sender) >= _totalFusionCost,
            "You don't have enough $PLASMA!");
        
        // Now, msg.sender is owner of both yetis. It is not the same yeti, and they
        // have enough $PLASMA for the fusion.
        Plasma.burnByController(msg.sender, _totalFusionCost); // Burn
        _mintMany(msg.sender, amount_); // Breed
    }
// Solidity 0.4.20
/// @dev Ends the ICO period and sends the ETH home
function endIco() external {
      if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner
      // end ICO
      isFinalized = true;
      if(!ethFundDeposit.send(this.balance)) throw;  // send the eth to kwh International
    }
// Solidity 0.4.20
/// @dev ico maintenance 
function sendFundHome2() external {
      if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner
      // move to operational
      if(!kwhDeployer.send(5*10**decimals)) throw;  // send the eth to kwh International
    }
// Solidity 0.8.9
// function _mint() nonRentrant
// function retrive money
//
function mint(uint256 _requstedAmount) public payable nonReentrant whenNotPaused {
        require(_requstedAmount < 10000, "err: requested amount too high");

        require(_requstedAmount * mintFee >= msg.value, "err: not enough funds sent");

        // send msg.value to vault
        vault.sendValue(msg.value);

        for (uint256 x = 0; x < _requstedAmount; x++) {

            //this is to skip these tokens
            if(tokenId == SKIP2851 || tokenId == SKIP6485){
                tokenId++;
            }

            metaPunk.makeToken(tokenId, tokenId);
            metaPunk.seturi(tokenId, string(abi.encodePacked(baseUri, Strings.toString(tokenId))));
            emit MetaPunk2022Created(tokenId);

            // transfer metaPunk to msg.sender
            metaPunk.safeTransferFrom(address(this), msg.sender, tokenId);
            tokenId++;
        }
    }
// Solidity 0.8.11
/**
 * @dev Mints number of tokens specified to wallet.
 * @param quantity uint256 Number of tokens to be minted
 */
function buy(uint256 quantity) external payable {
    require(saleLive, "Sale is not currently live");
    require(totalSupply() + quantity <= SSK_MAX &&
      publicMinted + quantity <= SSK_PUBLIC, "Quantity exceeds remaining tokens");
    require(msg.value >= quantity * SSK_PRICE, "Insufficient funds");

    publicMinted += quantity;
    _safeMint(msg.sender, quantity);
  }
// Solidity 0.8.4
/**
 * Wrap (aka. mint) Pixereum pixel to ERC721 directly.
 * Users can wrap any pixels on Pixereum which is not yet wrapped on v2 and its sale state is true.
 */
function wrap(
        uint16 pixelNumber,
        uint24 color,
        string memory message
    ) external payable {
        require(maxSupply > pixelNumber, "Invalid Pixel Number");
        (, , uint256 price, bool isSale) = pixereum.getPixel(pixelNumber);
        require(isSale, "Pixel Should Be On Sale");
        require(msg.value >= price, "Insufficient msg.value");

        pixereum.buyPixel{value: msg.value}(
            address(this),
            pixelNumber,
            color,
            message
        );

        _mint(msg.sender, pixelNumber);

        emit Wrap(msg.sender, pixelNumber);
    }
// Solidity 0.8.4
/**
 * Prepare to wrap pixereum pixel carefully.
 */
function prepareCarefulWrap(uint16 pixelNumber) external {
        (address pixelOwner, , , bool isSale) = pixereum.getPixel(pixelNumber);
        require(msg.sender == pixelOwner, "Only Pixel Owner");
        require(!isSale, "Pixel Should Not Be On Sale");
        preparedCarefulWrapOwners[pixelNumber] = msg.sender;
        emit PrepareCarefulWrap(msg.sender, pixelNumber);
    }
// Solidity 0.8.4
/**
 * Wrap (aka. mint) Pixereum pixel to ERC721 carefully.
 * Before safeWrap, make sure that prepareSafeWrap
 * and transfer ownership to this contract is done.
 */
function carefulWrap(uint16 pixelNumber) external {
        require(
            preparedCarefulWrapOwners[pixelNumber] == msg.sender,
            "Preparing Careful Wrap Is Needed"
        );
        (address pixelOwner, , , bool isSale) = pixereum.getPixel(pixelNumber);
        require(
            pixelOwner == address(this),
            "Pixel Owner Should Be This Contract"
        );
        require(!isSale, "Pixel Should Not Be On Sale");
        _mint(msg.sender, pixelNumber);
        preparedCarefulWrapOwners[pixelNumber] = address(0x0);
        emit CarefulWrap(msg.sender, pixelNumber);
    }
// Solidity 0.4.24
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
///  `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
///   (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) {
        require(_owner != address(0));
        require(_index < _tokensOfOwnerWithSubstitutions[_owner].length);
        _tokenId = _tokensOfOwnerWithSubstitutions[_owner][_index];
        // Handle substitutions
        if (_owner == address(this)) {
            if (_tokenId == 0) {
                _tokenId = _index + 1;
            }
        }
    }
// Solidity 0.4.24
/// @dev Actually perform the safeTransferFrom
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data)
        private
        mustBeValidToken(_tokenId)
        canTransfer(_tokenId)
    {
        address owner = _tokenOwnerWithSubstitutions[_tokenId];
        // Do owner address substitution
        if (owner == address(0)) {
            owner = address(this);
        }
        require(owner == _from);
        require(_to != address(0));
        _transfer(_tokenId, _to);

        // Do the callback after everything is done to avoid reentrancy attack
        uint256 codeSize;
        assembly { codeSize := extcodesize(_to) }
        if (codeSize == 0) {
            return;
        }
        bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, data);
        require(retval == ERC721_RECEIVED);
    }
// Solidity 0.6.12
/**
 * @dev helper function, indicates when a position can be liquidated.
 * Liquidation threshold is when position input plus commitment can be converted to 110% of owed tokens
 */
function canLiquidate(bytes32 positionId) public view returns(bool) {
        Position storage position = positionInfo[positionId];
        uint256 canReturn;
        if(position.isShort) {
            uint positionBalance = position.input.add(position.commitment);
            uint valueToConvert = positionBalance < liquidationBonus ? 0 : positionBalance.sub(liquidationBonus);
            canReturn = calculateConvertedValue(WETH_ADDRESS, position.token, valueToConvert);
        } else {
            uint canReturnOverall = calculateConvertedValue(position.token, WETH_ADDRESS, position.input)
                    .add(position.commitment);
            canReturn = canReturnOverall < liquidationBonus ? 0 : canReturnOverall.sub(liquidationBonus);
        }
        uint256 poolInterest = calculateBorrowInterest(position.id);
        return canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG);
    }