lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.5.6
/**
 * @dev remove token and OrderObj information on exchange contract
 * @param contractAddress NFT's contract address
 * @param tokenId NFT's id
 */
function _removeToken(
        address contractAddress, 
        uint256 tokenId
    ) 
    internal 
    {
        address owner = TokenToOwner[contractAddress][tokenId];
        bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, owner));
        delete HashToOrderObj[orderHash];
        delete MatchOrderToOwner[orderHash];
        delete TokenToOwner[contractAddress][tokenId];
        uint256 tokenIndex = TokenToIndex[contractAddress][tokenId];
        uint256 lastOwnerTokenIndex = OwnerToTokens[owner][contractAddress].length.sub(1);
        if (lastOwnerTokenIndex != tokenIndex){
            uint256 lastOwnerToken = OwnerToTokens[owner][contractAddress][lastOwnerTokenIndex];
            OwnerToTokens[owner][contractAddress][tokenIndex] = lastOwnerToken;
            TokenToIndex[contractAddress][lastOwnerToken] = tokenIndex;
        }
        OwnerToTokens[owner][contractAddress].length--;
    }
// Solidity 0.8.7
// See which address owns which tokens
function tokensOfOwner(address addr)
        public
        view
        returns (uint256[] memory)
    {
        uint256 tokenCount = balanceOf(addr);
        uint256[] memory tokensId = new uint256[](tokenCount);
        for (uint256 i; i < tokenCount; i++) {
            tokensId[i] = tokenOfOwnerByIndex(addr, i);
        }
        return tokensId;
    }
// Solidity 0.8.7
// Exclusive presale minting
function mintPresale(uint256 amount) internal {
        require(amount > 0, "amount should not be zero..");
        // uint256 reservedAmt = presaleReserved[msg.sender];
        require(
            amount <= presaleReserved[msg.sender],
            "mintPresale Erorr: minted reserved tokens or not allowed"
        );
        require(presaleActive, "Presale isn't active");
        require(
            _tokenIdCounter.current() + amount <= MAX_SUPPLY - reserved,
            "Can't mint more than max supply"
        );
        require(msg.value == price * amount, "Wrong amount of ETH sent");
        for (uint256 i = 1; i <= amount; i++) {
            _safeMint(msg.sender, _tokenIdCounter.current());
            _tokenIdCounter.increment();
            presaleReserved[msg.sender] -= 1;
        }
    }
// Solidity 0.8.7
// Standard mint function1
function mintToken(uint256 amount) internal {
        require(amount <= 10, "Only 10 tokens are allowed to mint once");
        require(msg.value == price * amount, "Wrong amount of ETH sent");
        require(saleActive, "Sale isn't active");
        require(
            _tokenIdCounter.current() + amount <= MAX_SUPPLY - reserved,
            "Can't mint more than max supply"
        );
        payable(owner()).transfer(msg.value);
        for (uint256 i = 1; i <= amount; i++) {
            _safeMint(msg.sender, _tokenIdCounter.current());
            _tokenIdCounter.increment();
        }
    }
// Solidity 0.8.7
//withdraw ethers() from contract onlyy Admin
function withdrawfunds() public payable onlyOwner {
        require(
            msg.sender == owner(),
            "withdrawfunds: only Owner can call this function"
        );
        require(
            address(this).balance != 0,
            "withdrawfunds :no balance is in contract"
        );
        payable(owner()).transfer(address(this).balance);
    }
// Solidity 0.8.7
// Admin minting function to reserve tokens for the team, collabs, customs and giveaways
function mintReserved(uint256 _amount) public onlyOwner {
        // Limited to a publicly set amount
        require(_amount > 0, "Invalid amount is given");
        require(_amount <= reserved, "Can't reserve more than set amount");
        reserved -= _amount;
        for (uint256 i = 1; i <= _amount; i++) {
            _safeMint(msg.sender, _tokenIdCounter.current());
            _tokenIdCounter.increment();
        }
    }
// Solidity 0.4.24
// callable by owner only, after specified time, only for Tokens implementing ERC20
function withdrawERC20Amount(address _tokenContract, uint256 _amount) onlyOwner public {
       ERC20 token = ERC20(_tokenContract);
       uint256 tokenBalance = token.balanceOf(this);
       require(tokenBalance >= _amount, "Not enough funds in the reserve");
       token.transfer(owner, _amount);
       emit WithdrewTokens(_tokenContract, msg.sender, _amount);
    }
// Solidity 0.6.2
/// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `_implementer` or not.
/// @param _interfaceHash keccak256 hash of the name of the interface
/// @param _implementer Address for which the contract will implement the interface
/// @return ERC1820_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `_implementer`.
function canImplementInterfaceForAddress(bytes32 _interfaceHash, address _implementer) external view returns(bytes32) {
		// keccak256(abi.encodePacked("ERC777TokensRecipient")) == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b
		if (_implementer == address(this) && _interfaceHash == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b) {
			// keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")) == 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4
			return 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4;
		} else {
			return bytes32(0);
		}
	}
// Solidity 0.6.2
// this function is effectively map.entries.slice(1:), but that doesn't work with storage arrays in this version of solc so we have to do it by hand
function enumerate(Map storage map) internal view returns (Entry[] memory) {
		// output array is one shorter because we use a 1-indexed array
		Entry[] memory output = new Entry[](map.entries.length - 1);

		// first element in the array is just a placeholder (0,0), so we copy from element 1 to end
		for (uint256 i = 1; i < map.entries.length; ++i) {
			output[i - 1] = map.entries[i];
		}
		return output;
	}
// Solidity 0.6.2
/// @notice starts the recovery process.  must be called by a previously registered recovery address.  recovery will complete in a number of days dependent on the address that initiated the recovery
function startRecovery() external {
		require(recoveryDelaysInDays.contains(msg.sender), "Caller is not registered as a recoverer for this wallet.");
		uint16 _proposedRecoveryDelayInDays = recoveryDelaysInDays.get(msg.sender);

		bool _inRecovery = activeRecoveryAddress != address(0);
		if (_inRecovery) {
			// NOTE: the delay for a particular recovery address cannot be changed during recovery nor can addresses be removed during recovery, so we can rely on this being != 0
			uint16 _activeRecoveryDelayInDays = recoveryDelaysInDays.get(activeRecoveryAddress);
			require(_proposedRecoveryDelayInDays < _activeRecoveryDelayInDays, "Recovery is already under way and new recoverer doesn't have a higher priority.");
			emit RecoveryCancelled(activeRecoveryAddress);
		}

		activeRecoveryAddress = msg.sender;
		activeRecoveryEndTime = block.timestamp + _proposedRecoveryDelayInDays * 1 days;
		emit RecoveryStarted(msg.sender);
	}
// Solidity 0.6.2
/// @notice finishes the recovery process after the necessary delay has elapsed.  callable by anyone in case the keys controlling the active recovery address have been lost, since once this is called a new recovery (with a potentially lower recovery priority) can begin.
function finishRecovery() external onlyDuringRecovery {
		require(block.timestamp >= activeRecoveryEndTime, "You must wait until the recovery delay is over before finishing the recovery.");

		address _oldOwner = owner;
		owner = activeRecoveryAddress;
		resetRecovery();
		emit RecoveryFinished(_oldOwner, owner);
	}
// Solidity 0.6.2
/// @notice deploy a contract from this contract.
/// @dev uses create2, so the address of the deployed contract will be deterministic
/// @param _value the amount of ETH that should be supplied to the contract creation call
/// @param _data the deployment bytecode to execute
/// @param _salt the salt used for deterministic contract creation.  see documentation at https://eips.ethereum.org/EIPS/eip-1014 for details on how the address is computed
function deploy(uint256 _value, bytes calldata _data, uint256 _salt) external payable onlyOwner onlyOutsideRecovery returns (address) {
		require(address(this).balance >= _value, "Wallet does not have enough funds available to deploy the contract.");
		require(_data.length != 0, "Contract deployment must contain bytecode to deploy.");
		bytes memory _data2 = _data;
		address newContract;
		/* solium-disable-next-line */
		assembly { newContract := create2(_value, add(_data2, 32), mload(_data2), _salt) }
		require(newContract != address(0), "Contract creation returned address 0, indicating failure.");
		return newContract;
	}
// Solidity 0.6.2
/// @notice executes an arbitrary contract call by this wallet.  allows the wallet to send ETH, transfer tokens, use dapps, etc.
/// @param _to contract address to call or send to
/// @param _value the amount of ETH to attach to the call
/// @param _data the calldata to supply to `_to`
/// @dev `_data` is of the same form used to call a contract from the JSON-RPC API, so for Solidity contract calls it is the target function hash followed by the ABI encoded parameters for that function
function execute(address payable _to, uint256 _value, bytes calldata _data) external payable onlyOwner onlyOutsideRecovery returns (bytes memory) {
		require(_to != address(0), "Transaction execution must contain a destination.  If you meant to deploy a contract, use deploy instead.");
		require(address(this).balance >= _value, "Wallet does not have enough funds available to execute the desired transaction.");
		(bool _success, bytes memory _result) = _to.call.value(_value)(_data);
		require(_success, "Contract execution failed.");
		return _result;
	}
// Solidity 0.5.2
/// @notice determines the amount of needed collateral for a given position (qty and price)
/// @param priceFloor lowest price the contract is allowed to trade before expiration
/// @param priceCap highest price the contract is allowed to trade before expiration
/// @param qtyMultiplier multiplier for qty from base units
/// @param longQty qty to redeem
/// @param shortQty qty to redeem
/// @param price of the trade
function calculateCollateralToReturn(
        uint priceFloor,
        uint priceCap,
        uint qtyMultiplier,
        uint longQty,
        uint shortQty,
        uint price
    ) pure internal returns (uint)
    {
        uint neededCollateral = 0;
        uint maxLoss;
        if (longQty > 0) {   // calculate max loss from entry price to floor
            if (price <= priceFloor) {
                maxLoss = 0;
            } else {
                maxLoss = subtract(price, priceFloor);
            }
            neededCollateral = multiply(multiply(maxLoss, longQty),  qtyMultiplier);
        }

        if (shortQty > 0) {  // calculate max loss from entry price to ceiling;
            if (price >= priceCap) {
                maxLoss = 0;
            } else {
                maxLoss = subtract(priceCap, price);
            }
            neededCollateral = add(neededCollateral, multiply(multiply(maxLoss, shortQty),  qtyMultiplier));
        }
        return neededCollateral;
    }
// Solidity 0.5.2
//  expiration date or outside of our tradeable ranges.
function checkSettlement() internal {
        require(!isSettled, "Contract is already settled"); // already settled.

        uint newSettlementPrice;
        if (now > EXPIRATION) {  // note: miners can cheat this by small increments of time (minutes, not hours)
            isSettled = true;                   // time based expiration has occurred.
            newSettlementPrice = lastPrice;
        } else if (lastPrice >= PRICE_CAP) {    // price is greater or equal to our cap, settle to CAP price
            isSettled = true;
            newSettlementPrice = PRICE_CAP;
        } else if (lastPrice <= PRICE_FLOOR) {  // price is lesser or equal to our floor, settle to FLOOR price
            isSettled = true;
            newSettlementPrice = PRICE_FLOOR;
        }

        if (isSettled) {
            settleContract(newSettlementPrice);
        }
    }
// Solidity 0.5.2
/// @notice Called by a user that currently holds both short and long position tokens and would like to redeem them
/// for their collateral.
/// @param marketContractAddress            address of the market contract to redeem tokens for
/// @param qtyToRedeem                      quantity of long / short tokens to redeem.
function redeemPositionTokens(
        address marketContractAddress,
        uint qtyToRedeem
    ) external onlyWhiteListedAddress(marketContractAddress)
    {
        MarketContract marketContract = MarketContract(marketContractAddress);

        marketContract.redeemLongToken(qtyToRedeem, msg.sender);
        marketContract.redeemShortToken(qtyToRedeem, msg.sender);

        // calculate collateral to return and update pool balance
        uint collateralToReturn = MathLib.multiply(qtyToRedeem, marketContract.COLLATERAL_PER_UNIT());
        contractAddressToCollateralPoolBalance[marketContractAddress] = contractAddressToCollateralPoolBalance[
            marketContractAddress
        ].subtract(collateralToReturn);

        // EXTERNAL CALL
        // transfer collateral back to user
        ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransfer(msg.sender, collateralToReturn);

        emit TokensRedeemed(
            marketContractAddress,
            msg.sender,
            qtyToRedeem,
            qtyToRedeem,
            collateralToReturn
        );
    }
// Solidity 0.5.2
/// @param marketContractAddress address of the MARKET Contract being traded.
/// @param longQtyToRedeem qty to redeem of long tokens
/// @param shortQtyToRedeem qty to redeem of short tokens
function settleAndClose(
        address marketContractAddress,
        uint longQtyToRedeem,
        uint shortQtyToRedeem
    ) external onlyWhiteListedAddress(marketContractAddress)
    {
        MarketContract marketContract = MarketContract(marketContractAddress);
        require(marketContract.isPostSettlementDelay(), "Contract is not past settlement delay");

        // burn tokens being redeemed.
        if (longQtyToRedeem > 0) {
            marketContract.redeemLongToken(longQtyToRedeem, msg.sender);
        }

        if (shortQtyToRedeem > 0) {
            marketContract.redeemShortToken(shortQtyToRedeem, msg.sender);
        }


        // calculate amount of collateral to return and update pool balances
        uint collateralToReturn = MathLib.calculateCollateralToReturn(
            marketContract.PRICE_FLOOR(),
            marketContract.PRICE_CAP(),
            marketContract.QTY_MULTIPLIER(),
            longQtyToRedeem,
            shortQtyToRedeem,
            marketContract.settlementPrice()
        );

        contractAddressToCollateralPoolBalance[marketContractAddress] = contractAddressToCollateralPoolBalance[
            marketContractAddress
        ].subtract(collateralToReturn);

        // return collateral tokens
        ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransfer(msg.sender, collateralToReturn);

        emit TokensRedeemed(
            marketContractAddress,
            msg.sender,
            longQtyToRedeem,
            shortQtyToRedeem,
            collateralToReturn
        );
    }
// Solidity 0.5.2
/// @dev allows the owner to remove the fees paid into this contract for minting
/// @param feeTokenAddress - address of the erc20 token fees have been paid in
/// @param feeRecipient - Recipient address of fees
function withdrawFees(address feeTokenAddress, address feeRecipient) public onlyOwner {
        uint feesAvailableForWithdrawal = feesCollectedByTokenAddress[feeTokenAddress];
        require(feesAvailableForWithdrawal != 0, "No fees available for withdrawal");
        require(feeRecipient != address(0), "Cannot send fees to null address");
        feesCollectedByTokenAddress[feeTokenAddress] = 0;
        // EXTERNAL CALL
        ERC20(feeTokenAddress).safeTransfer(feeRecipient, feesAvailableForWithdrawal);
    }
// Solidity 0.4.17
/**
 * @dev Print number of block till next expected dividend payment
 */
function dividendsBlocks() constant external returns (uint) {
        if(investStart > 0) {
            return(0);
        }
        uint period = (block.number - hashFirst) / (10 * hashesSize);
        if(period > dividendPeriod) {
            return(0);
        }
        return((10 * hashesSize) - ((block.number - hashFirst) % (10 * hashesSize)));
    }
// Solidity 0.4.17
/**
 * @dev Move funds to cold storage
 * @dev investBalance and walletBalance is protected from withdraw by owner
 * @dev if funding is > 50% admin can withdraw only 0.25% of balance weekly
 * @param _amount The amount of wei to move to cold storage
 */
function coldStore(uint _amount) external onlyOwner {
        houseKeeping();
        require(_amount > 0 && this.balance >= (investBalance * 9 / 10) + walletBalance + _amount);
        if(investBalance >= investBalanceGot / 2){ // additional jackpot protection
            require((_amount <= this.balance / 400) && coldStoreLast + 60 * 60 * 24 * 7 <= block.timestamp);
        }
        msg.sender.transfer(_amount);
        coldStoreLast = block.timestamp;
    }
// Solidity 0.4.17
/**
 * @dev Update accounting
 */
function houseKeeping() public {
        if(investStart > 1 && block.number >= investStart + (hashesSize * 5)){ // ca. 14 days
            investStart = 0; // start dividend payments
        }
        else {
            if(hashFirst > 0){
		        uint period = (block.number - hashFirst) / (10 * hashesSize );
                if(period > dividends.length - 2) {
                    dividends.push(0);
                }
                if(period > dividendPeriod && investStart == 0 && dividendPeriod < dividends.length - 1) {
                    dividendPeriod++;
                }
            }
        }
    }
// Solidity 0.4.17
/**
 * @dev Delete all tokens owned by sender and return unpaid dividends and 90% of initial investment
 */
function disinvest() external {
        require(investStart == 0);
        commitDividend(msg.sender);
        uint initialInvestment = balances[msg.sender] * 10**15;
        Transfer(msg.sender,address(0),balances[msg.sender]); // for etherscan
        delete balances[msg.sender]; // totalSupply stays the same, investBalance is reduced
        investBalance -= initialInvestment;
        wallets[msg.sender].balance += uint208(initialInvestment * 9 / 10);
        payWallet();
    }
// Solidity 0.4.17
/**
 * @dev Commit remaining dividends before transfer of tokens
 */
function commitDividend(address _who) internal {
        uint last = wallets[_who].lastDividendPeriod;
        if((balances[_who]==0) || (last==0)){
            wallets[_who].lastDividendPeriod=uint16(dividendPeriod);
            return;
        }
        if(last==dividendPeriod) {
            return;
        }
        uint share = balances[_who] * 0xffffffff / totalSupply;
        uint balance = 0;
        for(;last<dividendPeriod;last++) {
            balance += share * dividends[last];
        }
        balance = (balance / 0xffffffff);
        walletBalance += balance;
        wallets[_who].balance += uint208(balance);
        wallets[_who].lastDividendPeriod = uint16(last);
        LogDividend(_who,balance,last);
    }
// Solidity 0.4.17
/* lottery functions */
function betPrize(Bet _player, uint24 _hash) constant private returns (uint) { // house fee 13.85%
        uint24 bethash = uint24(_player.betHash);
        uint24 hit = bethash ^ _hash;
        uint24 matches =
            ((hit & 0xF) == 0 ? 1 : 0 ) +
            ((hit & 0xF0) == 0 ? 1 : 0 ) +
            ((hit & 0xF00) == 0 ? 1 : 0 ) +
            ((hit & 0xF000) == 0 ? 1 : 0 ) +
            ((hit & 0xF0000) == 0 ? 1 : 0 ) +
            ((hit & 0xF00000) == 0 ? 1 : 0 );
        if(matches == 6){
            return(uint(_player.value) * 7000000);
        }
        if(matches == 5){
            return(uint(_player.value) * 20000);
        }
        if(matches == 4){
            return(uint(_player.value) * 500);
        }
        if(matches == 3){
            return(uint(_player.value) * 25);
        }
        if(matches == 2){
            return(uint(_player.value) * 3);
        }
        return(0);
    }
// Solidity 0.4.17
/**
 * @dev Check if won in lottery
 */
function betOf(address _who) constant external returns (uint)  {
        Bet memory player = bets[_who];
        if( (player.value==0) ||
            (player.blockNum<=1) ||
            (block.number<player.blockNum) ||
            (block.number>=player.blockNum + (10 * hashesSize))){
            return(0);
        }
        if(block.number<player.blockNum+256){
            return(betPrize(player,uint24(block.blockhash(player.blockNum))));
        }
        if(hashFirst>0){
            uint32 hash = getHash(player.blockNum);
            if(hash == 0x1000000) { // load hash failed :-(, return funds
                return(uint(player.value));
            }
            else{
                return(betPrize(player,uint24(hash)));
            }
	}
        return(0);
    }
// Solidity 0.4.17
/**
 * @dev Send ether to buy tokens during ICO
 * @dev or send less than 1 ether to contract to play
 * @dev or send 0 to collect prize
 */
function () payable external {
        if(msg.value > 0){
            if(investStart>1){ // during ICO payment to the contract is treated as investment
                invest(owner);
            }
            else{ // if not ICO running payment to contract is treated as play
                play();
            }
            return;
        }
        //check for dividends and other assets
        if(investStart == 0 && balances[msg.sender]>0){
            commitDividend(msg.sender);}
        won(); // will run payWallet() if nothing else available
    }
// Solidity 0.4.17
/**
 * @dev Play in lottery with own numbers
 * @param _partner Affiliate partner
 */
function playSystem(uint _hash, address _partner) payable public returns (uint) {
        won(); // check if player did not win 
        uint24 bethash = uint24(_hash);
        require(msg.value <= 1 ether && msg.value < hashBetMax);
        if(msg.value > 0){
            if(investStart==0) { // dividends only after investment finished
                dividends[dividendPeriod] += msg.value / 20; // 5% dividend
            }
            if(_partner != address(0)) {
                uint fee = msg.value / 100;
                walletBalance += fee;
                wallets[_partner].balance += uint208(fee); // 1% for affiliates
            }
            if(hashNext < block.number + 3) {
                hashNext = block.number + 3;
                hashBetSum = msg.value;
            }
            else{
                if(hashBetSum > hashBetMax) {
                    hashNext++;
                    hashBetSum = msg.value;
                }
                else{
                    hashBetSum += msg.value;
                }
            }
            bets[msg.sender] = Bet({value: uint192(msg.value), betHash: uint32(bethash), blockNum: uint32(hashNext)});
            LogBet(msg.sender,uint(bethash),hashNext,msg.value);
        }
        putHashes(25); // players help collecing data, now much more than in last contract
        return(hashNext);
    }