lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.20
/// internal function    which checks whether the token with id (_tokenId)
/// is owned by the (_claimant) address
function ownsAll(address _owner, uint256[] _tokenIds) public view returns (bool) {
        require(_tokenIds.length > 0);
        for (uint i = 0; i < _tokenIds.length; i++) {
            if (partIndexToOwner[_tokenIds[i]] != _owner) {
                return false;
            }
        }
        return true;
    }
// Solidity 0.4.20
// transfers a part to another account
function transfer(address _to, uint256 _tokenId) public whenNotPaused payable {
        // payable for ERC721 --> don't actually send eth @_@
        require(msg.value == 0);

        // Safety checks to prevent accidental transfers to common accounts
        require(_to != address(0));
        require(_to != address(this));
        // can't transfer parts to the auction contract directly
        require(_to != address(auction));
        // can't transfer parts to any of the battle contracts directly
        for (uint j = 0; j < approvedBattles.length; j++) {
            require(_to != approvedBattles[j]);
        }

        // Cannot send tokens you don't own
        require(owns(msg.sender, _tokenId));

        // perform state changes necessary for transfer
        _transfer(msg.sender, _to, _tokenId);
    }
// Solidity 0.4.20
// approves the (_to) address to use the transferFrom function on the token with id (_tokenId)
// if you want to clear all approvals, simply pass the zero address
function approve(address _to, uint256 _deedId) external whenNotPaused payable {
        // payable for ERC721 --> don't actually send eth @_@
        require(msg.value == 0);
// use internal function?
        // Cannot approve the transfer of tokens you don't own
        require(owns(msg.sender, _deedId));

        // Store the approval (can only approve one at a time)
        partIndexToApproved[_deedId] = _to;

        Approval(msg.sender, _to, _deedId);
    }
// Solidity 0.4.20
// approves many token ids
function approveMany(address _to, uint256[] _tokenIds) external whenNotPaused payable {

        for (uint i = 0; i < _tokenIds.length; i++) {
            uint _tokenId = _tokenIds[i];

            // Cannot approve the transfer of tokens you don't own
            require(owns(msg.sender, _tokenId));

            // Store the approval (can only approve one at a time)
            partIndexToApproved[_tokenId] = _to;
            //create event for each approval? _tokenId guaranteed to hold correct value?
            Approval(msg.sender, _to, _tokenId);
        }
    }
// Solidity 0.4.20
// transfer the part with id (_tokenId) from (_from) to (_to)
// (_to) must already be approved for this (_tokenId)
function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused {

        // Safety checks to prevent accidents
        require(_to != address(0));
        require(_to != address(this));

        // sender must be approved
        require(partIndexToApproved[_tokenId] == msg.sender);
        // from must currently own the token
        require(owns(_from, _tokenId));

        // Reassign ownership (also clears pending approvals and emits Transfer event).
        _transfer(_from, _to, _tokenId);
    }
// Solidity 0.4.20
// This is public so it can be called by getPartsOfOwner. It should NOT be called by another contract
// as it is very gas hungry.
function getPartsOfOwnerWithinRange(address _owner, uint _start, uint _numToSearch) public view returns(bytes24[]) {
        uint256 tokenCount = balanceOf(_owner);

        uint resultIndex = 0;
        bytes24[] memory result = new bytes24[](tokenCount);
        for (uint partId = _start; partId < _start + _numToSearch; partId++) {
            if (partIndexToOwner[partId] == _owner) {
                result[resultIndex] = _partToBytes(parts[partId]);
                resultIndex++;
            }
        }
        return result; // will have 0 elements if tokenCount == 0
    }
// Solidity 0.4.20
// every level, you need 1000 more exp to go up a level
function getLevel(uint32 _exp) public pure returns(uint32) {
        uint32 c = 0;
        for (uint32 i = FIRST_LEVEL; i <= FIRST_LEVEL + _exp; i += c * INCREMENT) {
            c++;
        }
        return c;
    }
// Solidity 0.4.20
// code duplicated
function _tokenOfOwnerByIndex(address _owner, uint _index) private view returns (uint _tokenId){
        // The index should be valid.
        require(_index < balanceOf(_owner));

        // can loop through all without
        uint256 seen = 0;
        uint256 totalTokens = totalSupply();

        for (uint i = 0; i < totalTokens; i++) {
            if (partIndexToOwner[i] == _owner) {
                if (seen == _index) {
                    return i;
                }
                seen++;
            }
        }
    }
// Solidity 0.4.20
// sum of perks (excluding prestige)
function _sumActivePerks(uint8[32] _perks) internal pure returns (uint256) {
        uint32 sum = 0;
        //sum from after prestige_index, to count+1 (for prestige index).
        for (uint8 i = PRESTIGE_INDEX+1; i < PERK_COUNT+1; i++) {
            sum += _perks[i];
        }
        return sum;
    }
// Solidity 0.4.20
// you can unlock a new perk every two levels (including prestige when possible)
function choosePerk(uint8 _i) external {
        require((_i >= PRESTIGE_INDEX) && (_i < PERK_COUNT+1));
        User storage currentUser = addressToUser[msg.sender];
        uint256 _numActivePerks = _sumActivePerks(currentUser.perks);
        bool canPrestige = (_numActivePerks == PERK_COUNT);

        //add prestige value to sum of perks
        _numActivePerks += currentUser.perks[PRESTIGE_INDEX] * PERK_COUNT;
        require(_numActivePerks < getLevel(currentUser.experience) / 2);

        if (_i == PRESTIGE_INDEX) {
            require(canPrestige);
            _prestige();
        } else {
            require(_isValidPerkToAdd(currentUser.perks, _i));
            _addPerk(_i);
        }
        PerkChosen(msg.sender, _i);
    }
// Solidity 0.4.20
// Calculates price and transfers purchase to owner. Part is NOT transferred to buyer.
function _purchase(uint256 _partId, uint256 _purchaseAmount) internal returns (uint256) {

        Auction storage auction = tokenIdToAuction[_partId];

        // check that this token is being auctioned
        require(_isActiveAuction(auction));

        // enforce purchase >= the current price
        uint256 price = _currentPrice(auction);
        require(_purchaseAmount >= price);

        // Store seller before we delete auction.
        address seller = auction.seller;

        // Valid purchase. Remove auction to prevent reentrancy.
        _removeAuction(_partId);

        // Transfer proceeds to seller (if there are any!)
        if (price > 0) {
            
            // Calculate and take fee from purchase

            uint256 auctioneerCut = _computeFee(price);
            uint256 sellerProceeds = price - auctioneerCut;

            PrintEvent("Seller, proceeds", seller, sellerProceeds);

            // Pay the seller
            seller.transfer(sellerProceeds);
        }

        // Calculate excess funds and return to buyer.
        uint256 purchaseExcess = _purchaseAmount - price;

        PrintEvent("Sender, excess", msg.sender, purchaseExcess);
        // Return any excess funds. Reentrancy again prevented by deleting auction.
        msg.sender.transfer(purchaseExcess);

        AuctionSuccessful(_partId, price, msg.sender);

        return price;
    }
// Solidity 0.4.20
// computes the current price of an deflating-price auction 
function _computeCurrentPrice( uint256 _startPrice, uint256 _endPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256 _price) {
        _price = _startPrice;
        if (_secondsPassed >= _duration) {
            // Has been up long enough to hit endPrice.
            // Return this price floor.
            _price = _endPrice;
            // this is a statically price sale. Just return the price.
        }
        else if (_duration > 0) {
            // This auction contract supports auctioning from any valid price to any other valid price.
            // This means the price can dynamically increase upward, or downard.
            int256 priceDifference = int256(_endPrice) - int256(_startPrice);
            int256 currentPriceDifference = priceDifference * int256(_secondsPassed) / int256(_duration);
            int256 currentPrice = int256(_startPrice) + currentPriceDifference;

            _price = uint256(currentPrice);
        }
        return _price;
    }
// Solidity 0.4.20
// Creates an auction and lists it.
function createAuction( uint256 _partId, uint256 _startPrice, uint256 _endPrice, uint256 _duration, address _seller ) external whenNotPaused {
        // Sanity check that no inputs overflow how many bits we've allocated
        // to store them in the auction struct.
        require(_startPrice == uint256(uint128(_startPrice)));
        require(_endPrice == uint256(uint128(_endPrice)));
        require(_duration == uint256(uint64(_duration)));
        require(_startPrice >= _endPrice);

        require(msg.sender == address(nftContract));
        _escrow(_seller, _partId);
        Auction memory auction = Auction(
            _seller,
            uint128(_startPrice),
            uint128(_endPrice),
            uint64(_duration),
            uint64(now) //seconds uint 
        );
        PrintEvent("Auction Start", 0x0, auction.start);
        _newAuction(_partId, auction);
    }
// Solidity 0.4.20
// Purchases an open auction
// Will transfer ownership if successful.
function purchase(uint256 _partId) external payable whenNotPaused {
        address seller = tokenIdToAuction[_partId].seller;

        // _purchase will throw if the purchase or funds transfer fails
        uint256 price = _purchase(_partId, msg.value);
        _transfer(msg.sender, _partId);
        
        // If the seller is the scrapyard, track price information.
        if (seller == address(nftContract)) {

            lastScrapPrices[scrapCounter] = price;
            if (scrapCounter == LAST_CONSIDERED - 1) {
                scrapCounter = 0;
            } else {
                scrapCounter++;
            }
        }
    }
// Solidity 0.4.20
//  Returns the details of an auction from its _partId.
function getAuction(uint256 _partId) external view returns ( address seller, uint256 startPrice, uint256 endPrice, uint256 duration, uint256 startedAt ) {
        Auction storage auction = tokenIdToAuction[_partId];
        require(_isActiveAuction(auction));
        return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.start);
    }
// Solidity 0.4.20
// list a part for auction.
function createAuction(
        uint256 _partId,
        uint256 _startPrice,
        uint256 _endPrice,
        uint256 _duration ) external whenNotPaused 
    {


        // user must have current control of the part
        // will lose control if they delegate to the auction
        // therefore no duplicate auctions!
        require(owns(msg.sender, _partId));

        _approve(_partId, auction);

        // will throw if inputs are invalid
        // will clear transfer approval
        DutchAuction(auction).createAuction(_partId,_startPrice,_endPrice,_duration,msg.sender);
    }
// Solidity 0.4.20
///  An internal method that creates a new part and stores it. This
///  method doesn't do any checking and should only be called when the
///  input data is known to be valid. Will generate both a Forge event
///  and a Transfer event.
function _createPart(uint8[4] _partArray, address _owner) internal returns (uint) {
        uint32 newPartId = uint32(parts.length);
        assert(newPartId == parts.length);

        Part memory _part = Part({
            tokenId: newPartId,
            partType: _partArray[0],
            partSubType: _partArray[1],
            rarity: _partArray[2],
            element: _partArray[3],
            battlesLastDay: 0,
            experience: 0,
            forgeTime: uint32(now),
            battlesLastReset: uint32(now)
        });
        assert(newPartId == parts.push(_part) - 1);

        // emit the FORGING!!!
        Forge(_owner, newPartId, _part);

        // This will assign ownership, and also emit the Transfer event as
        // per ERC721 draft
        _transfer(0, _owner, newPartId);

        return newPartId;
    }
// Solidity 0.4.20
// uint8[] public defenceElementBySubtypeIndex = [1,2,4,3,4,1,3,3,2,1,4];
// uint8[] public meleeElementBySubtypeIndex = [3,1,3,2,3,4,2,2,1,1,1,1,4,4];
// uint8[] public bodyElementBySubtypeIndex = [2,1,2,3,4,3,1,1,4,2,3,4,1,0,1]; // no more lambos :'(
// uint8[] public turretElementBySubtypeIndex = [4,3,2,1,2,1,1,3,4,3,4];
function setRewardChance(uint _newChance) external onlyOwner {
        require(_newChance > 980); // not too hot
        require(_newChance <= 1000); // not too cold
        PART_REWARD_CHANCE = _newChance; // just right
        // come at me goldilocks
    }
// Solidity 0.4.20
// function _randomIndex(uint _rand, uint8 _startIx, uint8 _endIx, uint8 _modulo) internal pure returns (uint8) {
//     require(_startIx < _endIx);
//     bytes32 randBytes = bytes32(_rand);
//     uint result = 0;
//     for (uint8 i=_startIx; i<_endIx; i++) {
//         result = result | uint8(randBytes[i]);
//         result << 8;
//     }
//     uint8 resultInt = uint8(uint(result) % _modulo);
//     return resultInt;
// }
// This function takes a random uint, an owner and randomly generates a valid part.
// It then transfers that part to the owner.
function _generateRandomPart(uint _rand, address _owner) internal {
        // random uint 20 in length - MAYBE 20.
        // first randomly gen a part type
        _rand = uint(keccak256(_rand));
        uint8[4] memory randomPart;
        randomPart[0] = uint8(_rand % 4) + 1;
        _rand = uint(keccak256(_rand));

        // randomPart[0] = _randomIndex(_rand,0,4,4) + 1; // 1, 2, 3, 4, => defence, melee, body, turret

        if (randomPart[0] == DEFENCE) {
            randomPart[1] = _getRandomPartSubtype(_rand,defenceElementBySubtypeIndex);
            randomPart[3] = _getElement(defenceElementBySubtypeIndex, randomPart[1]);

        } else if (randomPart[0] == MELEE) {
            randomPart[1] = _getRandomPartSubtype(_rand,meleeElementBySubtypeIndex);
            randomPart[3] = _getElement(meleeElementBySubtypeIndex, randomPart[1]);

        } else if (randomPart[0] == BODY) {
            randomPart[1] = _getRandomPartSubtype(_rand,bodyElementBySubtypeIndex);
            randomPart[3] = _getElement(bodyElementBySubtypeIndex, randomPart[1]);

        } else if (randomPart[0] == TURRET) {
            randomPart[1] = _getRandomPartSubtype(_rand,turretElementBySubtypeIndex);
            randomPart[3] = _getElement(turretElementBySubtypeIndex, randomPart[1]);

        }
        _rand = uint(keccak256(_rand));
        randomPart[2] = _getRarity(_rand);
        // randomPart[2] = _getRarity(_randomIndex(_rand,8,12,3)); // rarity
        _createPart(randomPart, _owner);
    }
// Solidity 0.4.20
// scraps a part for shards
function scrap(uint partId) external {
        require(owns(msg.sender, partId));
        User storage u = addressToUser[msg.sender];
        _addShardsToUser(u, (SHARDS_TO_PART * scrapPercent) / 100);
        Scrap(msg.sender, partId);
        // this doesn't need to be secure
        // no way to manipulate it apart from guaranteeing your parts are resold
        // or burnt
        if (uint(keccak256(scrapCount)) % 100 >= burnRate) {
            _transfer(msg.sender, address(this), partId);
            _createScrapPartAuction(partId);
        } else {
            _transfer(msg.sender, address(0), partId);
        }
        scrapCount++;
    }
// Solidity 0.4.20
// store the part information of purchased crates
function openAll() public {
        uint len = addressToPurchasedBlocks[msg.sender].length;
        require(len > 0);
        uint8 count = 0;
        // len > i to stop predicatable wraparound
        for (uint i = len - 1; i >= 0 && len > i; i--) {
            uint crateBlock = addressToPurchasedBlocks[msg.sender][i];
            require(block.number > crateBlock);
            // can't open on the same timestamp
            var hash = block.blockhash(crateBlock);
            if (uint(hash) != 0) {
                // different results for all different crates, even on the same block/same user
                // randomness is already taken care of
                uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);
                userToRobots[msg.sender].push(rand);
                count++;
            } else {
                // all others will be expired
                expiredCrates[msg.sender] += (i + 1);
                break;
            }
        }
        CratesOpened(msg.sender, count);
        delete addressToPurchasedBlocks[msg.sender];
    }
// Solidity 0.4.20
// convert old string representation of robot into 4 new ERC721 parts
function _convertBlueprint(string original) pure private returns(uint8[4] body,uint8[4] melee, uint8[4] turret, uint8[4] defence ) {

        /* ------ CONVERSION TIME ------ */
        

        body[0] = BODY; 
        body[1] = _getPartId(original, 3, 5, 15);
        body[2] = _getRarity(original, 0, 3);
        body[3] = _getElement(BODY_ELEMENT_BY_ID, body[1]);
        
        turret[0] = TURRET;
        turret[1] = _getPartId(original, 8, 10, 11);
        turret[2] = _getRarity(original, 5, 8);
        turret[3] = _getElement(TURRET_ELEMENT_BY_ID, turret[1]);

        melee[0] = MELEE;
        melee[1] = _getPartId(original, 13, 15, 14);
        melee[2] = _getRarity(original, 10, 13);
        melee[3] = _getElement(MELEE_ELEMENT_BY_ID, melee[1]);

        defence[0] = DEFENCE;
        var len = bytes(original).length;
        // string of number does not have preceding 0's
        if (len == 20) {
            defence[1] = _getPartId(original, 18, 20, 11);
        } else if (len == 19) {
            defence[1] = _getPartId(original, 18, 19, 11);
        } else { //unlikely to have length less than 19
            defence[1] = uint8(1);
        }
        defence[2] = _getRarity(original, 15, 18);
        defence[3] = _getElement(DEFENCE_ELEMENT_BY_ID, defence[1]);

        // implicit return
    }
// Solidity 0.4.20
// Users can open pending crates on the new contract.
function openCrates() public whenNotPaused {
        uint[] memory pc = pendingCrates[msg.sender];
        require(pc.length > 0);
        uint8 count = 0;
        for (uint i = 0; i < pc.length; i++) {
            uint crateBlock = pc[i];
            require(block.number > crateBlock);
            // can't open on the same timestamp
            var hash = block.blockhash(crateBlock);
            if (uint(hash) != 0) {
                // different results for all different crates, even on the same block/same user
                // randomness is already taken care of
                uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);
                _migrateRobot(uintToString(rand));
                count++;
            }
        }
        CratesOpened(msg.sender, count);
        delete pendingCrates[msg.sender];
    }
// Solidity 0.4.20
// in PerksRewards
function redeemBattleCrates() external {
        uint8 count = 0;
        uint len = pendingRewards[msg.sender].length;
        require(len > 0);
        for (uint i = 0; i < len; i++) {
            Reward memory rewardStruct = pendingRewards[msg.sender][i];
            // can't open on the same timestamp
            require(block.number > rewardStruct.blocknumber);
            // ensure user has converted all pendingRewards
            require(rewardStruct.blocknumber != 0);

            var hash = block.blockhash(rewardStruct.blocknumber);

            if (uint(hash) != 0) {
                // different results for all different crates, even on the same block/same user
                // randomness is already taken care of
                uint rand = uint(keccak256(hash, msg.sender, i));
                _generateBattleReward(rand,rewardStruct.exp);
                count++;
            } else {
                // Do nothing, no second chances to secure integrity of randomness.
            }
        }
        CratesOpened(msg.sender, count);
        delete pendingRewards[msg.sender];
    }
// Solidity 0.4.20
// don't need to do any scaling
// should already have been done by previous stages
function _addUserExperience(address user, int32 exp) internal {
        // never allow exp to drop below 0
        User memory u = addressToUser[user];
        if (exp < 0 && uint32(int32(u.experience) + exp) > u.experience) {
            u.experience = 0;
            return;
        } else if (exp > 0) {
            // check for overflow
            require(uint32(int32(u.experience) + exp) > u.experience);
        }
        addressToUser[user].experience = uint32(int32(u.experience) + exp);
        //_addUserReward(user, exp);
    }
// Solidity 0.4.20
//requires parts in order
function hasOrderedRobotParts(uint[] partIds) external view returns(bool) {
        uint len = partIds.length;
        if (len != 4) {
            return false;
        }
        for (uint i = 0; i < len; i++) {
            if (parts[partIds[i]].partType != i+1) {
                return false;
            }
        }
        return true;
    }
// Solidity 0.8.5
/*
 * @notice Mints specified amount of tokens on the public sale
 * @dev Non reentrant. Emits PublicSaleMint event
 * @param _amount Amount of tokens to mint
 */
function publicSaleMint(uint256 _amount) external payable nonReentrant whenNotPaused {
        require(saleState == 3, "public sale isn't active");
        require(_amount > 0 && _amount <= publicSaleLimitPerTx, "invalid amount");
        uint256 maxTotalSupply_ = maxTotalSupply;
        uint256 totalSupply_ = totalSupply();
        require(totalSupply_ + _amount <= maxTotalSupply_, "already sold out");
        require(mintCounter + _amount <= maxTotalSupply_ - amountForGiveAway, "the rest is reserved");
        _buyAndRefund(_amount, publicSalePrice);
        if (totalSupply_ + _amount == maxTotalSupply_) emit SoldOut();
        emit PublicSaleMint(_msgSender(), _amount);
    }
// Solidity 0.8.5
/*
 * @notice Mints specified IDs to specified addresses
 * @dev Only owner can call it. Lengths of arrays must be equal.
 * @param _accounts The list of addresses to mint tokens to
 */
function giveaway(address[] memory _accounts) external onlyOwner {
        uint256 maxTotSup = maxTotalSupply;
        uint256 currentTotalSupply = totalSupply();
        require(_accounts.length <= publicSaleLimitPerTx, "Limit per transaction exceeded");
        require(airdropCounter + _accounts.length <= amountForGiveAway, "limit for airdrop exceeded");
        require(currentTotalSupply + _accounts.length <= maxTotSup, "maxTotalSupply exceeded");
        uint256 counter = currentTotalSupply;
        for (uint256 i; i < _accounts.length; i++) {
            _safeMint(_accounts[i], uint8(1));
            counter++;
        }
        airdropCounter += uint16(_accounts.length);
        if (currentTotalSupply + _accounts.length == maxTotSup) emit SoldOut();  // emit SoldOut in case some tokens were airdropped after the sale
        emit GiveAway(_accounts);
    }