lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.26
/**
 * @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens
 * we take this input in order to allow specifying the corresponding reserve amounts in any order
 *
 * @param _reserveTokens   array of reserve tokens
 * @param _reserveAmounts  array of reserve amounts
 * @param _amount          token amount
 */
function verifyLiquidityInput(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _amount) private view {
        uint256 i;
        uint256 j;

        uint256 length = reserveTokens.length;
        require(length == _reserveTokens.length, "ERR_INVALID_RESERVE");
        require(length == _reserveAmounts.length, "ERR_INVALID_AMOUNT");

        for (i = 0; i < length; i++) {
            // verify that every input reserve token is included in the reserve tokens
            require(reserves[_reserveTokens[i]].isSet, "ERR_INVALID_RESERVE");
            for (j = 0; j < length; j++) {
                if (reserveTokens[i] == _reserveTokens[j])
                    break;
            }
            // verify that every reserve token is included in the input reserve tokens
            require(j < length, "ERR_INVALID_RESERVE");
            // verify that every input reserve token amount is larger than zero
            require(_reserveAmounts[i] > 0, "ERR_INVALID_AMOUNT");
        }

        // verify that the input token amount is larger than zero
        require(_amount > 0, "ERR_ZERO_AMOUNT");
    }
// Solidity 0.4.26
/**
 * @dev adds liquidity (reserve) to the pool when it's empty
 *
 * @param _reserveTokens   address of each reserve token
 * @param _reserveAmounts  amount of each reserve token
 */
function addLiquidityToEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts)
        private
        returns (uint256)
    {
        // calculate the geometric-mean of the reserve amounts approved by the user
        uint256 amount = geometricMean(_reserveAmounts);

        // transfer each one of the reserve amounts from the user to the pool
        for (uint256 i = 0; i < _reserveTokens.length; i++) {
            if (_reserveTokens[i] != ETH_RESERVE_ADDRESS) // ETH has already been transferred as part of the transaction
                safeTransferFrom(_reserveTokens[i], msg.sender, this, _reserveAmounts[i]);

            reserves[_reserveTokens[i]].balance = _reserveAmounts[i];

            emit LiquidityAdded(msg.sender, _reserveTokens[i], _reserveAmounts[i], _reserveAmounts[i], amount);

            // dispatch the `TokenRateUpdate` event for the pool token
            uint32 reserveWeight = reserves[_reserveTokens[i]].weight;
            dispatchPoolTokenRateEvent(amount, _reserveTokens[i], _reserveAmounts[i], reserveWeight);
        }

        return amount;
    }
// Solidity 0.4.26
/**
 * @dev removes liquidity (reserve) from the pool
 *
 * @param _reserveTokens           address of each reserve token
 * @param _reserveMinReturnAmounts minimum return-amount of each reserve token
 * @param _totalSupply             token total supply
 * @param _amount                  token amount
 */
function removeLiquidityFromPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts, uint256 _totalSupply, uint256 _amount)
        private
    {
        syncReserveBalances();

        IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
        uint256 newPoolTokenSupply = _totalSupply.sub(_amount);

        for (uint256 i = 0; i < _reserveTokens.length; i++) {
            IERC20Token reserveToken = _reserveTokens[i];
            uint256 rsvBalance = reserves[reserveToken].balance;
            uint256 reserveAmount = formula.liquidateReserveAmount(_totalSupply, rsvBalance, reserveRatio, _amount);
            require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT");

            uint256 newReserveBalance = rsvBalance.sub(reserveAmount);
            reserves[reserveToken].balance = newReserveBalance;

            // transfer each one of the reserve amounts from the pool to the user
            if (reserveToken == ETH_RESERVE_ADDRESS)
                msg.sender.transfer(reserveAmount);
            else
                safeTransfer(reserveToken, msg.sender, reserveAmount);

            emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply);

            // dispatch the `TokenRateUpdate` event for the pool token
            uint32 reserveWeight = reserves[reserveToken].weight;
            dispatchPoolTokenRateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserveWeight);
        }
    }
// Solidity 0.4.26
/**
 * @dev calculates the average number of decimal digits in a given list of values
 *
 * @param _values  list of values (each of which assumed positive)
 * @return the average number of decimal digits in the given list of values
 */
function geometricMean(uint256[] memory _values) public pure returns (uint256) {
        uint256 numOfDigits = 0;
        uint256 length = _values.length;
        for (uint256 i = 0; i < length; i++)
            numOfDigits += decimalLength(_values[i]);
        return uint256(10) ** (roundDiv(numOfDigits, length) - 1);
    }
// Solidity 0.4.26
/**
 * @dev dispatches rate events for both reserves / pool tokens
 * only used to circumvent the `stack too deep` compiler error
 *
 * @param _sourceToken address of the source reserve token
 * @param _targetToken address of the target reserve token
 */
function dispatchRateEvents(IERC20Token _sourceToken, IERC20Token _targetToken) private {
        uint256 poolTokenSupply = ISmartToken(anchor).totalSupply();
        uint256 sourceReserveBalance = reserveBalance(_sourceToken);
        uint256 targetReserveBalance = reserveBalance(_targetToken);
        uint32 sourceReserveWeight = reserves[_sourceToken].weight;
        uint32 targetReserveWeight = reserves[_targetToken].weight;

        // dispatch token rate update event
        uint256 rateN = targetReserveBalance.mul(sourceReserveWeight);
        uint256 rateD = sourceReserveBalance.mul(targetReserveWeight);
        emit TokenRateUpdate(_sourceToken, _targetToken, rateN, rateD);

        // dispatch the `TokenRateUpdate` event for the pool token
        dispatchPoolTokenRateEvent(poolTokenSupply, _sourceToken, sourceReserveBalance, sourceReserveWeight);
        dispatchPoolTokenRateEvent(poolTokenSupply, _targetToken, targetReserveBalance, targetReserveWeight);

        // dispatch price data update events (deprecated events)
        emit PriceDataUpdate(_sourceToken, poolTokenSupply, sourceReserveBalance, sourceReserveWeight);
        emit PriceDataUpdate(_targetToken, poolTokenSupply, targetReserveBalance, targetReserveWeight);
    }
// Solidity 0.8.7
//backend mint
function mintInternal(address wallet, uint amount) internal {
        uint currentTokenSupply = _tokenIdCounter.current();
        require((currentTokenSupply + amount) <= maxSupply, "Not enough tokens left");
            for(uint i = 0; i< amount; i++){
            currentTokenSupply++;
            _safeMint(wallet, currentTokenSupply);
            _tokenIdCounter.increment();
        }
        }
// Solidity 0.8.4
/** Used to determine if a staked token is owned. Used to allow game logic to occur outside this contract.
 * This might not be necessary if the training mechanic is in this contract instead */
function ownsToken(uint256 tokenId) external view returns (bool) {
    uint64 lastTokenWrite = wndNFT.getTokenWriteBlock(tokenId);
    // Must check this, as getTokenTraits will be allowed since this contract is an admin
    require(lastTokenWrite < block.number, "hmmmm what doing?");
    IWnD.WizardDragon memory s = wndNFT.getTokenTraits(tokenId);
    if(s.isWizard) {
        return tower[tokenId].owner == tx.origin || training[tokenId].owner == tx.origin;
    }
    uint8 rank = _rankForDragon(tokenId);
    return flight[rank][flightIndices[tokenId]].owner == tx.origin;
  }
// Solidity 0.8.4
/**
 * adds Wizards and Dragons to the Tower and Flight
 * @param tokenIds the IDs of the Wizards and Dragons to stake
 */
function addManyToTowerAndFlight(address tokenOwner, uint16[] calldata tokenIds) external override nonReentrant {
    require(admins[_msgSender()], "Only admins can stake");
    for (uint i = 0; i < tokenIds.length; i++) {
      if (wndNFT.ownerOf(tokenIds[i]) != address(this)) { // a mint + stake will send directly to the staking contract
        require(wndNFT.ownerOf(tokenIds[i]) == tokenOwner, "You don't own this token");
        wndNFT.transferFrom(tokenOwner, address(this), tokenIds[i]);
      } else if (tokenIds[i] == 0) {
        continue; // there may be gaps in the array for stolen tokens
      }

      if (wndNFT.isWizard(tokenIds[i])) 
        _addWizardToTower(tokenOwner, tokenIds[i]);
      else 
        _addDragonToFlight(tokenOwner, tokenIds[i]);
    }
  }
// Solidity 0.8.4
/**
 * adds Wizards and Dragons to the Tower and Flight
 * @param seed the seed for random logic
 * @param tokenIds the IDs of the Wizards and Dragons to stake
 */
function addManyToTrainingAndFlight(uint256 seed, address tokenOwner, uint16[] calldata tokenIds) external override nonReentrant {
    require(admins[_msgSender()], "Only admins can stake");
    for (uint i = 0; i < tokenIds.length; i++) {
        require(wndNFT.ownerOf(tokenIds[i]) == tokenOwner, "You don't own this token");
        seed = uint256(keccak256(abi.encodePacked(
            tx.origin,
            seed
        )));
        address recipient = selectRecipient(seed, tokenOwner);
        if(tokenIds[i] <= 15000) {
            // Don't allow gen0 tokens from being stolen
            recipient = tokenOwner;
        }
        if(recipient != tokenOwner) { // stolen
            wndNFT.transferFrom(tokenOwner, recipient, tokenIds[i]);
            continue;
        }
        wndNFT.transferFrom(tokenOwner, address(this), tokenIds[i]);
        if (wndNFT.isWizard(tokenIds[i])) {
            _addWizardToTraining(recipient, tokenIds[i]);
        }
        else {
            _addDragonToFlight(recipient, tokenIds[i]);
        }
    }
  }
// Solidity 0.8.4
/**
 * adds a single Dragon to the Flight
 * @param account the address of the staker
 * @param tokenId the ID of the Dragon to add to the Flight
 */
function _addDragonToFlight(address account, uint256 tokenId) internal {
    uint8 rank = _rankForDragon(tokenId);
    totalRankStaked += rank; // Portion of earnings ranges from 8 to 5
    flightIndices[tokenId] = flight[rank].length; // Store the location of the dragon in the Flight
    flight[rank].push(StakeDragon({
      owner: account,
      tokenId: uint16(tokenId),
      lastClaimTime: uint80(block.timestamp),
      value: gpPerRank
    })); // Add the dragon to the Flight
    _deposits[account].dragons.add(tokenId);
    emit TokenStaked(account, tokenId, false, true);
  }
// Solidity 0.8.4
/**
 * realize $GP earnings and optionally unstake tokens from the Tower / Flight
 * to unstake a Wizard it will require it has 2 days worth of $GP unclaimed
 * @param tokenIds the IDs of the tokens to claim earnings from
 * @param unstake whether or not to unstake ALL of the tokens listed in tokenIds
 */
function claimManyFromTowerAndFlight(address tokenOwner, uint16[] calldata tokenIds, bool unstake) external override whenNotPaused _updateEarnings nonReentrant {
    require(admins[_msgSender()], "Only admins can stake");
    uint256 owed = 0;
    uint16 owedRunes = 0;
    for (uint i = 0; i < tokenIds.length; i++) {
      if (wndNFT.isWizard(tokenIds[i])) {
        owed += _claimWizardFromTower(tokenIds[i], unstake, tokenOwner);
      }
      else {
        (uint256 gpOwed, uint16 runes) = _claimDragonFromFlight(tokenIds[i], unstake, tokenOwner);
        owed += gpOwed;
        owedRunes += runes;
      }
    }
    gpToken.updateOriginAccess();
    if(owed > 0) {
        gpToken.mint(tokenOwner, owed);
    }
    if(owedRunes > 0 && curMagicRunesEmitted + owedRunes <= MAX_MAGIC_RUNE_EMISSION) {
        curMagicRunesEmitted += owedRunes;
        alter.mint(magicRune, owedRunes, tokenOwner);
    }
  }
// Solidity 0.8.4
/** Get the tax percent owed to dragons. If the address doesn't contain a 1:10 ratio of whips to staked wizards,
 *  they are subject to an untrained tax */
function getTaxPercent(address addr) internal returns (uint256) {
      if(_deposits[addr].towerWizards.length() <= 10) {
          // 
          return alter.balanceOf(addr, whip) >= 1 ? GP_CLAIM_TAX_PERCENTAGE : GP_CLAIM_TAX_PERCENTAGE_UNTRAINED;
      }
      return alter.balanceOf(addr, whip) >= _deposits[addr].towerWizards.length() / 10 ? GP_CLAIM_TAX_PERCENTAGE : GP_CLAIM_TAX_PERCENTAGE_UNTRAINED;
  }
// Solidity 0.8.4
/**
 * chooses a random Dragon thief when a newly minted token is stolen
 * @param seed a random value to choose a Dragon from
 * @return the owner of the randomly selected Dragon thief
 */
function randomDragonOwner(uint256 seed) public view override returns (address) {
    if (totalRankStaked == 0) {
      return address(0x0);
    }
    uint256 bucket = (seed & 0xFFFFFFFF) % totalRankStaked; // choose a value from 0 to total rank staked
    uint256 cumulative;
    seed >>= 32;
    // loop through each bucket of Dragons with the same rank score
    for (uint i = MAX_RANK - 3; i <= MAX_RANK; i++) {
      cumulative += flight[i].length * i;
      // if the value is not inside of that bucket, keep going
      if (bucket >= cumulative) continue;
      // get the address of a random Dragon with that rank score
      return flight[i][seed % flight[i].length].owner;
    }
    return address(0x0);
  }
// Solidity 0.8.4
/**
 * add $GP to claimable pot for the Flight
 * @param amount $GP to add to the pot
 */
function _payDragonTax(uint256 amount) internal {
    if (totalRankStaked == 0) { // if there's no staked dragons
      unaccountedRewards += amount; // keep track of $GP due to dragons
      return;
    }
    // makes sure to include any unaccounted $GP 
    gpPerRank += (amount + unaccountedRewards) / totalRankStaked;
    unaccountedRewards = 0;
  }
// Solidity 0.8.11
// Overrides
function tokenURI(uint256 tokenId)
        public
        view
        override(ERC721)
        returns (string memory)
    {
        require(
            _exists(tokenId),
            "ERC721Metadata: URI query for nonexistent token"
        );

        if (revealed == false) {
            return unrevealedURL;
        }

        return
            bytes(baseURI).length > 0
                ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json"))
                : "";
    }
// Solidity 0.6.12
/// @dev send ETH from this contract to its creator
function sendETHToCreator(uint256 _amount) external {
        require(msg.sender == creator, "Sender must be creator");
        // we use `call` here following the recommendation from
        // https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/
        (bool success,  ) = creator.call{value: _amount}("");
        require(success, "Transfer failed");
    }
// Solidity 0.8.0
// to caclulate the amounts for recipient and distributer after fees have been applied
function calculateFeesBeforeSend(
        address sender,
        address recipient,
        uint256 amount
    ) public view returns (uint256, uint256) {
       
        if(UniSwapReciever[recipient] && UniSwapSaleEnds){
            uint256 timeNow = block.timestamp;
            uint256 sfee = 5; //5% fee default if time not met in loop. 
            
            uint256 datediff = timeNow - UniSwapSaleEndsTime;
            
            datediff = datediff.div(oneDay);
            datediff = datediff.mod(turning);
            
            if(datediff == 0) { sfee = 30; }
            else if(datediff == 1) { sfee = 25; }
            else if(datediff == 2) { sfee = 20; }
            else if(datediff == 3) { sfee = 15; }
            else if(datediff == 4) { sfee = 10; }
            else if(datediff == 5) { sfee = 5; }
            
            sfee = amount.mul(sfee).div(100);
            return (amount.sub(sfee), sfee);
        }

        if (feelessSender[sender] || feelessReciever[recipient]) {
            return (amount, 0);
        }

        // calculate fees and amounts
        uint256 fee = amount.mul(txFee).div(1000);
        return (amount.sub(fee), fee);
    }
// Solidity 0.6.12
/* @notice          Convert boolean value into bytes
 *  @param b         The boolean value
 *  @return          Converted bytes array
 */
function WriteBool(bool b) internal pure returns (bytes memory) {
        bytes memory buff;
        assembly{
            buff := mload(0x40)
            mstore(buff, 1)
            switch iszero(b)
            case 1 {
                mstore(add(buff, 0x20), shl(248, 0x00))
                // mstore8(add(buff, 0x20), 0x00)
            }
            default {
                mstore(add(buff, 0x20), shl(248, 0x01))
                // mstore8(add(buff, 0x20), 0x01)
            }
            mstore(0x40, add(buff, 0x21))
        }
        return buff;
    }
// Solidity 0.6.12
/* @notice          Convert uint8 value into bytes
 *  @param v         The uint8 value
 *  @return          Converted bytes array
 */
function WriteUint8(uint8 v) internal pure returns (bytes memory) {
        bytes memory buff;
        assembly{
            buff := mload(0x40)
            mstore(buff, 1)
            mstore(add(buff, 0x20), shl(248, v))
            // mstore(add(buff, 0x20), byte(0x1f, v))
            mstore(0x40, add(buff, 0x21))
        }
        return buff;
    }
// Solidity 0.6.12
/* @notice          Convert uint16 value into bytes
 *  @param v         The uint16 value
 *  @return          Converted bytes array
 */
function WriteUint16(uint16 v) internal pure returns (bytes memory) {
        bytes memory buff;

        assembly{
            buff := mload(0x40)
            let byteLen := 0x02
            mstore(buff, byteLen)
            for {
                let mindex := 0x00
                let vindex := 0x1f
            } lt(mindex, byteLen) {
                mindex := add(mindex, 0x01)
                vindex := sub(vindex, 0x01)
            }{
                mstore8(add(add(buff, 0x20), mindex), byte(vindex, v))
            }
            mstore(0x40, add(buff, 0x22))
        }
        return buff;
    }
// Solidity 0.6.12
/* @notice          Convert limited uint256 value into bytes
 *  @param v         The uint256 value
 *  @return          Converted bytes array
 */
function WriteUint255(uint256 v) internal pure returns (bytes memory) {
        require(v <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds uint255 range");
        bytes memory buff;

        assembly{
            buff := mload(0x40)
            let byteLen := 0x20
            mstore(buff, byteLen)
            for {
                let mindex := 0x00
                let vindex := 0x1f
            } lt(mindex, byteLen) {
                mindex := add(mindex, 0x01)
                vindex := sub(vindex, 0x01)
            }{
                mstore8(add(add(buff, 0x20), mindex), byte(vindex, v))
            }
            mstore(0x40, add(buff, 0x40))
        }
        return buff;
    }
// Solidity 0.6.12
/* @notice      Convert the bytes array to bytes32 type, the bytes array length must be 32
 *  @param _bs   Source bytes array
 *  @return      bytes32
 */
function bytesToBytes32(bytes memory _bs) internal pure returns (bytes32 value) {
        require(_bs.length == 32, "bytes length is not 32.");
        assembly {
            // load 32 bytes from memory starting from position _bs + 0x20 since the first 0x20 bytes stores _bs length
            value := mload(add(_bs, 0x20))
        }
    }
// Solidity 0.6.12
/* @notice      Convert bytes to uint256
 *  @param _b    Source bytes should have length of 32
 *  @return      uint256
 */
function bytesToUint256(bytes memory _bs) internal pure returns (uint256 value) {
        require(_bs.length == 32, "bytes length is not 32.");
        assembly {
            // load 32 bytes from memory starting from position _bs + 32
            value := mload(add(_bs, 0x20))
        }
        require(value <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds the range");
    }
// Solidity 0.6.12
/* @notice      Convert uint256 to bytes
 *  @param _b    uint256 that needs to be converted
 *  @return      bytes
 */
function uint256ToBytes(uint256 _value) internal pure returns (bytes memory bs) {
        require(_value <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds the range");
        assembly {
            // Get a location of some free memory and store it in result as
            // Solidity does for memory variables.
            bs := mload(0x40)
            // Put 0x20 at the first word, the length of bytes for uint256 value
            mstore(bs, 0x20)
            //In the next word, put value in bytes format to the next 32 bytes
            mstore(add(bs, 0x20), _value)
            // Update the free-memory pointer by padding our last write location to 32 bytes
            mstore(0x40, add(bs, 0x40))
        }
    }
// Solidity 0.6.12
/* @notice      Convert bytes to address
 *  @param _bs   Source bytes: bytes length must be 20
 *  @return      Converted address from source bytes
 */
function bytesToAddress(bytes memory _bs) internal pure returns (address addr)
    {
        require(_bs.length == 20, "bytes length does not match address");
        assembly {
            // for _bs, first word store _bs.length, second word store _bs.value
            // load 32 bytes from mem[_bs+20], convert it into Uint160, meaning we take last 20 bytes as addr (address).
            addr := mload(add(_bs, 0x14))
        }

    }
// Solidity 0.6.12
/* @notice      Convert address to bytes
 *  @param _addr Address need to be converted
 *  @return      Converted bytes from address
 */
function addressToBytes(address _addr) internal pure returns (bytes memory bs){
        assembly {
            // Get a location of some free memory and store it in result as
            // Solidity does for memory variables.
            bs := mload(0x40)
            // Put 20 (address byte length) at the first word, the length of bytes for uint256 value
            mstore(bs, 0x14)
            // logical shift left _a by 12 bytes, change _a from right-aligned to left-aligned
            mstore(add(bs, 0x20), shl(96, _addr))
            // Update the free-memory pointer by padding our last write location to 32 bytes
            mstore(0x40, add(bs, 0x40))
       }
    }
// Solidity 0.6.12
/* @notice              Check if the elements number of _signers within _keepers array is no less than _m
 *  @param _keepers      The array consists of serveral address
 *  @param _signers      Some specific addresses to be looked into
 *  @param _m            The number requirement paramter
 *  @return              True means containment, false meansdo do not contain.
 */
function containMAddresses(address[] memory _keepers, address[] memory _signers, uint _m) internal pure returns (bool){
        uint m = 0;
        for(uint i = 0; i < _signers.length; i++){
            for (uint j = 0; j < _keepers.length; j++) {
                if (_signers[i] == _keepers[j]) {
                    m++;
                    delete _keepers[j];
                }
            }
        }
        return m >= _m;
    }
// Solidity 0.6.12
/* @notice              TODO
 *  @param key
 *  @return
 */
function compressMCPubKey(bytes memory key) internal pure returns (bytes memory newkey) {
         require(key.length >= 67, "key lenggh is too short");
         newkey = slice(key, 0, 35);
         if (uint8(key[66]) % 2 == 0){
             newkey[2] = byte(0x02);
         } else {
             newkey[2] = byte(0x03);
         }
         return newkey;
    }