lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.8.7
/**
 * Mints some Bit Monsters.
 *
 * @param count The number of Bit Monsters to mint. Must be >= 1 and <= 10.
 *              You must send 0.06 ETH for each Bit Monster you want to mint.
 */
function mint(uint count) external payable {
        require(count >= 1 && count <= 10, "Count must be >=1 and <=10");
        require(!Address.isContract(msg.sender), "Contracts cannot mint");
        require(mintingState != MintingState.NotAllowed, "Minting is not allowed atm");

        if (mintingState == MintingState.WhitelistOnly) {
            require(whitelist[msg.sender] >= 1000 + count, "Not enough whitelisted mints");
            whitelist[msg.sender] -= count;
        }

        require(msg.value == count * 0.06 ether, "Send exactly 0.06 ETH for each mint");

        Rng memory rn = rng;
        bool[9] memory ms = mintedSpecials;

        for (uint i = 0; i < count; ++i) {
            bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender);
        }

        rng = rn;
        mintedSpecials = ms;

        Address.sendValue(payHere, msg.value);
    }
// Solidity 0.5.10
/// @notice Extracts the r, s, and v components from the `sigData` field starting from the `offset`
/// @dev Note: does not do any bounds checking on the arguments!
/// @param sigData the signature data; could be 1 or more packed signatures.
/// @param offset the offset in sigData from which to start unpacking the signature components.
function extractSignature(bytes memory sigData, uint256 offset) internal pure returns  (bytes32 r, bytes32 s, uint8 v) {
        // Divide the signature in r, s and v variables
        // ecrecover takes the signature parameters, and the only way to get them
        // currently is to use assembly.
        // solium-disable-next-line security/no-inline-assembly
        assembly {
             let dataPointer := add(sigData, offset)
             r := mload(add(dataPointer, 0x20))
             s := mload(add(dataPointer, 0x40))
             v := byte(0, mload(add(dataPointer, 0x60)))
        }
    
        return (r, s, v);
    }
// Solidity 0.4.25
/**
 * @dev claimTokens() provides airdrop winners the function of collecting their tokens
 */
function claimTokens() 
  ifNotPaused
  public {
    Contribution storage contrib = contributions[msg.sender];
    require(contrib.isValid, "Address not found in airdrop list");
    require(contrib.tokenAmount > 0, "There are currently no tokens to claim.");
    uint256 tempPendingTokens = contrib.tokenAmount;
    contrib.tokenAmount = 0;
    totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);
    contrib.wasClaimed = true;
    ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);
  }
// Solidity 0.8.7
/**
 * Returns the metadata of the Bit Monster corresponding to the given tokenId as a base64-encoded JSON object. Meant for use with OpenSea.
 *
 * @dev This function can take a painful amount of time to run, sometimes exceeding 9 minutes in length. Use getBitMonster() instead for frontends.
 */
function tokenURI(uint256 tokenId) public view override returns (string memory) {
        require(_exists(tokenId), "the token doesn't exist");

        string memory metadataRaw = metadata.getMetadataJson(tokenId);
        string memory metadataB64 = Base64.encode(bytes(metadataRaw));

        return string(abi.encodePacked(
            "data:application/json;base64,",
            metadataB64
        ));
    }
// Solidity 0.4.18
/// @dev Called when the receiver of transfer is contract
/// @param _sender address the address of tokens sender
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) {
    if (!supportsToken(msg.sender)) {
      return false;
    }

    // Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory.
    // Solution: Remove the the data
    tkn = Tkn(msg.sender, _sender, _value);
    __isTokenFallback = true;
    if (!address(this).delegatecall(_data)) {
      __isTokenFallback = false;
      return false;
    }
    // avoid doing an overwrite to .token, which would be more expensive
    // makes accessing .tkn values outside tokenPayable functions unsafe
    __isTokenFallback = false;

    return true;
  }
// Solidity 0.4.18
/// @dev initialize the contract.
function initialize() private returns (bool success) {
    R1 = token1.balanceOf(this);
    R2 = token2.balanceOf(this);
    // one reserve should be full and the second should be empty
    success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
    if (success) {
      operational = true;
    }
  }
// Solidity 0.4.18
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
    price = PRECISION;
    price = price.mul(_S1.sub(_R1));
    price = price.div(_S2.sub(_R2));
    price = price.mul(_S2);
    price = price.div(_S1);
    price = price.mul(_S2);
    price = price.div(_S1);
  }
// Solidity 0.4.18
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
    // if buying token2 from token1
    if (token1 == _fromToken && token2 == _toToken) {
      // add buying amount to the temp reserve
      l_R1 = R1.add(_inAmount);
      // calculate the other reserve
      l_R2 = calcReserve(l_R1, S1, S2);
      if (l_R2 > R2) {
        return 0;
      }
      // the returnAmount is the other reserve difference
      returnAmount = R2.sub(l_R2);
    }
    // if buying token1 from token2
    else if (token2 == _fromToken && token1 == _toToken) {
      // add buying amount to the temp reserve
      l_R2 = R2.add(_inAmount);
      // calculate the other reserve
      l_R1 = calcReserve(l_R2, S2, S1);
      if (l_R1 > R1) {
        return 0;
      }
      // the returnAmount is the other reserve difference
      returnAmount = R1.sub(l_R1);
    } else {
      return 0;
    }
  }
// Solidity 0.4.18
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
    uint256 _R1;
    uint256 _R2;
    // if buying token2 from token1
    if (token1 == _fromToken && token2 == _toToken) {
      // add buying amount to the temp reserve
      _R1 = R1.add(_inAmount);
      // calculate the other reserve
      _R2 = calcReserve(_R1, S1, S2);
      if (_R2 > R2) {
        return 0;
      }
      // the returnAmount is the other reserve difference
      returnAmount = R2.sub(_R2);
    }
    // if buying token1 from token2
    else if (token2 == _fromToken && token1 == _toToken) {
      // add buying amount to the temp reserve
      _R2 = R2.add(_inAmount);
      // calculate the other reserve
      _R1 = calcReserve(_R2, S2, S1);
      if (_R1 > R1) {
        return 0;
      }
      // the returnAmount is the other reserve difference
      returnAmount = R1.sub(_R1);
    } else {
      return 0;
    }
  }
// Solidity 0.4.18
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2  - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
    _R2 = _S2
      .mul(
        _S1
        .sub(
          _R1
          .mul(_S1)
          .mul(2)
          .sub(
            _R1
            .toPower2()
          )
          .sqrt()
        )
      )
      .div(_S1);
  }
// Solidity 0.4.18
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
    // pull transfer the selling token
    require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
    // exchange the token
    returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
    if (returnAmount == 0) {
      // if no return value revert
      revert();
    }
    // transfer the buying token
    ERC20(_toToken).transfer(msg.sender, returnAmount);
    // validate the reserves
    require(validateReserves());
    Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
  }
// Solidity 0.4.18
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
    // if there is excess of token 1, transfer it to the owner
    if (token1.balanceOf(this) > R1) {
      returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
      token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
    }
    // if there is excess of token 2, transfer it to the owner
    if (token2.balanceOf(this) > R2) {
      returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
      token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
    }
  }
// Solidity 0.6.12
/// @dev Should be called by external mechanism when reward funds are sent to this contract
function notifyRewardAmount(uint256 reward)
        external
        override
        nonReentrant
        onlyRewardDistributor
        updateReward(address(0))
    {
        // overflow fix according to https://sips.synthetix.io/sips/sip-77
        require(reward < uint(-1) / 1e18, "the notified reward cannot invoke multiplication overflow");

        if (block.timestamp >= periodFinish) {
            rewardRate = reward.div(duration);
        } else {
            uint256 remaining = periodFinish.sub(block.timestamp);
            uint256 leftover = remaining.mul(rewardRate);
            rewardRate = reward.add(leftover).div(duration);
        }
        lastUpdateTime = block.timestamp;
        periodFinish = block.timestamp.add(duration);
        emit RewardAdded(reward);
    }
// Solidity 0.7.6
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
/// @notice Withdraw portion of allocation unlocked
function withdraw() public onlyOwner {
        uint256 timestamp = block.timestamp;

        if (timestamp == lastWithdrawalTimestamp) return;

        uint256 _lastWithdrawalTimestamp = lastWithdrawalTimestamp;
        lastWithdrawalTimestamp = timestamp;

        uint256 balance = premia.balanceOf(address(this));

        if (timestamp >= endTimestamp) {
            premia.safeTransfer(msg.sender, balance);
        } else {

            uint256 elapsedSinceLastWithdrawal = timestamp.sub(_lastWithdrawalTimestamp);
            uint256 timeLeft = endTimestamp.sub(_lastWithdrawalTimestamp);
            premia.safeTransfer(msg.sender, balance.mul(elapsedSinceLastWithdrawal).div(timeLeft));
        }
    }
// Solidity 0.4.24
/*
 * @param characterType
 * @param adversaryType
 * @return whether adversaryType is a valid type of adversary for a given character
 */
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
    if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
      return (adversaryType <= DRAGON_MAX_TYPE);
    } else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
      return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
    } else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
      return (adversaryType >= WIZARD_MIN_TYPE);
    } else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
      return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
             || (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
 
    }
    return false;
  }
// Solidity 0.4.24
/**
 * pick a random adversary.
 * @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
 * @return the index of a random adversary character
 * */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
    uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
    // use 7, 11 or 13 as step size. scales for up to 1000 characters
    uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
    uint16 i = randomIndex;
    //if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
    //will at some point return to the startingPoint if no character is suited
    do {
      if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
        return i;
      }
      i = (i + stepSize) % numCharacters;
    } while (i != randomIndex);

    return INVALID_CHARACTER_INDEX;
  }
// Solidity 0.4.24
/**
 * Hits the character of the given type at the given index.
 * Wizards can knock off two protections. Other characters can do only one.
 * @param index the index of the character
 * @param nchars the number of characters
 * @return the value gained from hitting the characters (zero is the character was protected)
 * */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
    uint32 id = ids[index];
    uint8 knockOffProtections = 1;
    if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
      knockOffProtections = 2;
    }
    if (protection[id] >= knockOffProtections) {
      protection[id] = protection[id] - knockOffProtections;
      return 0;
    }
    characterValue = characters[ids[index]].value;
    nchars--;
    replaceCharacter(index, nchars);
  }
// Solidity 0.4.24
/**
 * finds the oldest character
 * */
function findOldest() public {
    uint32 newOldest = noKing;
    for (uint16 i = 0; i < numCharacters; i++) {
      if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
        newOldest = ids[i];
    }
    oldest = newOldest;
  }
// Solidity 0.4.24
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser {
    require(castleTreasury > 0, "empty treasury");
    Character archer = characters[characterId];
    require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury");
    if(lastCastleLootDistributionTimestamp[characterId] == 0) 
      require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(), 
            "not enough time has passed since the purchase");
    else 
      require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),
            "not enough time passed since the last castle loot distribution");
    require(archer.fightCount >= 3, "need to fight 3 times");
    lastCastleLootDistributionTimestamp[characterId] = now;
    archer.fightCount = 0;
    
    uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));
    if (luckFactor < 3) {
      luckFactor = 3;
    }
    assert(luckFactor <= 50);
    uint128 amount = castleTreasury * luckFactor / 100; 
    archer.value += amount;
    castleTreasury -= amount;
    emit NewDistributionCastleLoot(amount, characterId, luckFactor);

  }
// Solidity 0.4.24
/**
 * sell the character of the given id
 * throws an exception in case of a knight not yet teleported to the game
 * @param characterId the id of the character
 * */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {
    if (characterIndex >= numCharacters || characterId != ids[characterIndex])
      characterIndex = getCharacterIndex(characterId);
    Character storage char = characters[characterId];
    require(msg.sender == char.owner,
            "only owners can sell their characters");
    require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,
            "balloons are not sellable");
    require(char.purchaseTimestamp + 1 days < now,
            "character can be sold only 1 day after the purchase");
    uint128 val = char.value;
    numCharacters--;
    replaceCharacter(characterIndex, numCharacters);
    msg.sender.transfer(val);
    if (oldest == 0)
      findOldest();
    emit NewSell(characterId, msg.sender, val);
  }
// Solidity 0.4.24
/**
 * Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
 * @param id the character id
 * */
function teleportCharacter(uint32 id) internal {
    // ensure we do not teleport twice
    require(teleported[id] == false,
           "already teleported");
    teleported[id] = true;
    Character storage character = characters[id];
    require(character.characterType > DRAGON_MAX_TYPE,
           "dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
    addCharacter(id, numCharacters);
    numCharacters++;
    numCharactersXType[character.characterType]++;
    emit NewTeleport(id);
  }
// Solidity 0.4.24
/**
 * returns 10 characters starting from a certain indey
 * @param startIndex the index to start from
 * @return 4 arrays containing the ids, types, values and owners of the characters
 * */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
    uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
    uint8 j = 0;
    uint32 id;
    for (uint16 i = startIndex; i < endIndex; i++) {
      id = ids[i];
      characterIds[j] = id;
      types[j] = characters[id].characterType;
      values[j] = characters[id].value;
      owners[j] = characters[id].owner;
      j++;
    }

  }
// Solidity 0.5.17
/**
 @notice This function adds liquidity to Mushroom vaults with ETH or ERC20 tokens
 @param fromToken The token used for entry (address(0) if ether)
 @param amountIn The amount of fromToken to invest
 @param toVault Harvest vault address
 @param minMVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise
 @param intermediateToken Token to swap fromToken to before entering vault
 @param swapTarget Excecution target for the swap or zap
 @param swapData DEX or Zap data
 @param affiliate Affiliate address
 @param shouldSellEntireBalance True if amountIn is determined at execution time (i.e. contract is caller)
 @return tokensReceived- Quantity of Vault tokens received
 */
function ZapIn(
        address fromToken,
        uint256 amountIn,
        address toVault,
        uint256 minMVTokens,
        address intermediateToken,
        address swapTarget,
        bytes calldata swapData,
        address affiliate,
        bool shouldSellEntireBalance
    ) external payable stopInEmergency returns (uint256 tokensReceived) {
        require(
            approvedTargets[swapTarget] || swapTarget == address(0),
            "Target not Authorized"
        );

        // get incoming tokens
        uint256 toInvest =
            _pullTokens(
                fromToken,
                amountIn,
                affiliate,
                true,
                shouldSellEntireBalance
            );

        // get intermediate token
        uint256 intermediateAmt =
            _fillQuote(
                fromToken,
                intermediateToken,
                toInvest,
                swapTarget,
                swapData
            );

        // Deposit to Vault
        tokensReceived = _vaultDeposit(intermediateAmt, toVault, minMVTokens);
    }
// Solidity 0.8.9
/**
 * @dev Mints a new token up to the current supply, stopping at the max supply.
 */
function mintNFTeacher(uint256 _quantity) public payable override {
        require(mintStart <= block.timestamp, 'Minting not started.');
        require(MAX_PER_TX >= _quantity, 'Too many mints.');
        require(currentMaxSupply >= tokenIds.current() + _quantity, 'No more tokens, currently.');
        require(MAX_SUPPLY >= tokenIds.current() + _quantity, 'No more tokens, ever.');
        require(MINT_PRICE * _quantity == msg.value, 'Wrong value sent.');

        for (uint8 i = 0; i < _quantity; i++) {
            tokenIds.increment();
            _safeMint(msg.sender, tokenIds.current());
        }
    }
// Solidity 0.8.9
/// @dev The receive function is triggered when FTM is received
receive() external payable virtual {
        // check ERC20 token balances while we have the chance, if we send FTM it will forward them
        for (uint256 i = 0; i < royaltyERC20Tokens.length; i++) {
            // send the tokens to the recipients
            IERC20 _token = IERC20(royaltyERC20Tokens[i]);
            if (_token.balanceOf(address(this)) > 0) {
                this.withdrawTokens(royaltyERC20Tokens[i]);
            }
        }

        // withdraw the splits
        this.withdraw();
    }
// Solidity 0.5.9
// import balance for a group of user with a specific contract terms
function importBalance(address[] memory buyers, uint256[] memory tokens, string memory contractName) public onlyOwner whenNotPaused returns (bool) {
        require(buyers.length == tokens.length, "buyers and balances mismatch");
        
        VestingContract storage vestingContract = _vestingContracts[contractName];
        require(vestingContract.basisPoints.length > 0, "contract does not exist");

        for(uint256 i = 0; i < buyers.length; i++) {
            require(tokens[i] > 0, "cannot import zero balance");
            BuyerInfo storage buyerInfo = _buyerInfos[buyers[i]]; 
            require(buyerInfo.total == 0, "have already imported balance for this buyer");
            buyerInfo.total = tokens[i];
            buyerInfo.contractName = contractName;
        }

        emit ImportBalance(buyers, tokens, contractName);
        return true;
    }