lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.5.10
// Notes:
// - This function does not track if real IERC20 balance has changed. Needs to blindly "trust" DaiProxy.
function onFundingReceived(address lender, uint256 amount)
        external
        onlyCreated
        onlyProxy
        returns (bool)
    {
        if (isAuctionExpired()) {
            if (auctionBalance < minAmount) {
                setState(LoanState.FAILED_TO_FUND);
                emit FailedToFund(address(this), lender, amount);
                return false;
            } else {
                require(setSuccessfulAuction(), "error while transitioning to successful auction");
                emit FailedToFund(address(this), lender, amount);
                return false;
            }
        }
        uint256 interest = getInterestRate();
        lenderPosition[lender].bidAmount = lenderPosition[lender].bidAmount.add(amount);
        auctionBalance = auctionBalance.add(amount);

        lastFundedTimestamp = block.timestamp;

        if (auctionBalance >= minAmount && !minimumReached) {
            minimumReached = true;
            emit Funded(address(this), lender, amount, interest, lastFundedTimestamp);
            emit MinimumFundingReached(address(this), auctionBalance, interest);
        } else {
            emit Funded(address(this), lender, amount, interest, lastFundedTimestamp);
        }

        if (auctionBalance == maxAmount) {
            require(setSuccessfulAuction(), "error while transitioning to successful auction");
            emit FullyFunded(
                address(this),
                borrowerDebt,
                auctionBalance,
                interest,
                lastFundedTimestamp
            );
        }
        return true;
    }
// Solidity 0.6.6
/// @notice Calculates the gas cost for transaction
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
        address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();

        if (_gasCost != 0) {
            uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
            _gasCost = wmul(_gasCost, price);

            gasCost = _gasCost;
        }

        // fee can't go over 20% of the whole amount
        if (gasCost > (_amount / 5)) {
            gasCost = _amount / 5;
        }

        if (_tokenAddr == ETH_ADDR) {
            WALLET_ADDR.transfer(gasCost);
        } else {
            ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost);
        }
    }
// Solidity 0.7.3
// bytes b must be hp encoded
function _getNibbleArray(bytes memory b)
        internal
        pure
        returns (bytes memory)
    {
        bytes memory nibbles = "";
        if (b.length > 0) {
            uint8 offset;
            uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b));
            if (hpNibble == 1 || hpNibble == 3) {
                nibbles = new bytes(b.length * 2 - 1);
                bytes1 oddNibble = _getNthNibbleOfBytes(1, b);
                nibbles[0] = oddNibble;
                offset = 1;
            } else {
                nibbles = new bytes(b.length * 2 - 2);
                offset = 0;
            }

            for (uint256 i = offset; i < nibbles.length; i++) {
                nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b);
            }
        }
        return nibbles;
    }
// Solidity 0.8.4
// withdrawBalance
//  -   Withdraws balance to contract owner
//  -   Automatic withdrawal of donation 
function withdrawBalance() public onlyOwner {
        // Get the total balance
        uint256 balance = address(this).balance;

        // Get share to send to donation wallet (10 % charity donation)
        uint256 donationShare = balance.mul(donationPercentage).div(100);
        uint256 ownerShare = balance.sub(donationShare);
        
        // Transfer respective amounts
        payable(msg.sender).transfer(ownerShare);
        payable(donationWallet).transfer(donationShare);
    }
// Solidity 0.8.4
// Mint boy
//  -   Mints lostboys by quantities
function mintBoy(uint numberOfBoys) public payable  {
        require(mintingActive, "Minting is not activated yet.");
        require(numberOfBoys > 0, "Why are you minting less than zero boys.");
        require(
            totalSupply().add(numberOfBoys) <= MAX_LOSTBOYS,
            'Only 10,000 boys are available'
        );
        require(numberOfBoys <= maxBoysPerMint, "Cannot mint this number of boys in one go !");
        require(lostBoyPrice.mul(numberOfBoys) <= msg.value, 'Ethereum sent is not sufficient.');

        for(uint i = 0; i < numberOfBoys; i++) {
            uint mintIndex = totalSupply();
            if (totalSupply() < MAX_LOSTBOYS) {
                _safeMint(msg.sender, mintIndex);
            }
        }
    }
// Solidity 0.8.4
// mintBoyAsMember
//  -   Mints lostboy as whitelisted member
function mintBoyAsMember(uint numberOfBoys) public payable {
        require(isPresaleActive, "Presale is not active yet.");
        require(numberOfBoys > 0, "Why are you minting less than zero boys.");
        require(_whiteListedMembers[msg.sender] == MemberClaimStatus.Listed, "You are not a whitelisted member !");
        require(_whiteListMints[msg.sender].add(numberOfBoys) <= MAX_PRESALE_BOYS_PER_ADDRESS, "You are minting more than your allowed presale boys!");
        require(totalSupply().add(numberOfBoys) <= MAX_LOSTBOYS, "Only 10,000 boys are available");
        require(numberOfBoys <= maxBoysPerPresaleMint, "Cannot mint this number of presale boys in one go !");
        require(lostBoyPrice.mul(numberOfBoys) <= msg.value, 'Ethereum sent is not sufficient.');
        
        for(uint i = 0; i < numberOfBoys; i++) {
            uint mintIndex = totalSupply();
            if (totalSupply() < MAX_LOSTBOYS) {
                _safeMint(msg.sender, mintIndex);
                _whiteListMints[msg.sender] = _whiteListMints[msg.sender].add(1);
            }
        }
    }
// Solidity 0.7.6
/// @notice Disable internal _transfer function
function transferFrom(address from, address to, uint256 tokenId) public override(ERC721, IERC721) onlyManager {
        // Disable internal _transfer function for ERC721 - do nth, must use safeTransferFrom to transfer token
        _transfer(from, to, tokenId);
    }
// Solidity 0.7.6
/// @notice Mint a new token of `productId` and `serialNumber` and assigned to `to`
/// @dev Only `_manager` can mint
function mintItem(uint256 productId, uint256 serialNumber, address to) external override onlyManager returns (uint256) {

        /// increase counter by one
        _tokenCounter.increment();

        uint256 newTokenId;
        // retry if token clash. given it 10 retries, but shouldn't happen.
        for (uint i = 0; i < 10; i++) {
            newTokenId = _generateHash(name(), _tokenCounter.current());
            if (!_exists(newTokenId)) {
                break;
            }
        }

        /// call erc721 safe mint function
        _safeMint(to, newTokenId);

        /// link token Id to product index
        _productIds[newTokenId] = productId;
        /// set serial number of an item
        _serialNumbers[newTokenId] = serialNumber;
        /// emit token mint event
        emit TokenMinted(newTokenId, productId, to);

        return newTokenId;
    }
// Solidity 0.5.17
/**
 * @dev Safely transfers the ownership of a given token ID to another address
 * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
 * which is called upon a safe transfer, and return the magic value
 * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
 * the transfer is reverted.
 * Requires the _msgSender() to be the owner, approved, or operator
 * @param from current owner of the token
 * @param to address to receive the ownership of the given token ID
 * @param tokenId uint256 ID of the token to be transferred
 * @param _data bytes data to send along with a safe transfer check
 */
function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public {
        require(
            _isApprovedOrOwner(_msgSender(), tokenId),
            "ERC721: transfer caller is not owner nor approved"
        );
        _safeTransferFrom(from, to, tokenId, _data);
    }
// Solidity 0.4.18
// member function to mint time based vesting tokens to a beneficiary
function mintTokensWithTimeBasedVesting(address beneficiary, uint256 tokens, uint256 start, uint256 cliff, uint256 duration) public onlyOwner {
    require(beneficiary != 0x0);
    require(tokens > 0);

    vesting[beneficiary] = new TokenVesting(beneficiary, start, cliff, duration, false);
    require(token.mint(address(vesting[beneficiary]), tokens));

    HOSTTimeVestingTokensMinted(beneficiary, tokens, start, cliff, duration);
  }
// Solidity 0.5.17
// Function to withdraw or send Ether from Contract owner's account to a specified account.
function TransferToGsContractFromOwnerAccount(address payable receiver, uint amount) public {
        require(msg.sender == owner, "You're not owner of the account"); // Only the Owner of this contract can run this function.
        require(amount < address(this).balance, "Insufficient balance.");
        receiver.transfer(amount);
        emit GdpSentFromAccount(msg.sender, receiver, amount);
    }
// Solidity 0.4.10
//
// Token Creation/Destruction Functions
//
// For a holder to buy an offer of tokens
function purchase()
        payable
        canEnter
        returns (bool)
    {
        Holder holder = holders[msg.sender];
        // offer must exist
        require(holder.offerAmount > 0);
        // offer not expired
        require(holder.offerExpiry > now);
        // correct payment has been sent
        require(msg.value == holder.offerAmount * TOKENPRICE);
        
        updateDividendsFor(holder);
                
        revoke(holder);
                
        totalSupply += holder.offerAmount;
        holder.tokenBalance += holder.offerAmount;
        TokensCreated(msg.sender, holder.offerAmount);
        
        delete holder.offerAmount;
        delete holder.offerExpiry;
        
        revote(holder);
        election();
        return true;
    }
// Solidity 0.4.10
// For holders to destroy tokens in return for ether during a redeeming
// round
function redeem(uint _amount)
        public
        canEnter
        isHolder(msg.sender)
        returns (bool)
    {
        uint redeemPrice;
        uint eth;
        
        Holder holder = holders[msg.sender];
        require(_amount <= holder.tokenBalance);
        
        updateDividendsFor(holder);
        
        revoke(holder);
        
        redeemPrice = fundBalance() / totalSupply;
        // prevent redeeming above token price which would allow an arbitrage
        // attack on the fund balance
        redeemPrice = redeemPrice < TOKENPRICE ? redeemPrice : TOKENPRICE;
        
        eth = _amount * redeemPrice;
        
        // will throw if either `amount` or `redeemPRice` are 0
        require(eth > 0);
        
        totalSupply -= _amount;
        holder.tokenBalance -= _amount;
        holder.etherBalance += eth;
        committedEther += eth;
        
        TokensDestroyed(msg.sender, _amount);
        revote(holder);
        election();
        return true;
    }
// Solidity 0.7.5
// ========== MODIFIERS ========== //
// ========== MUTATIVE FUNCTIONS ========== //
// ========== PRIVATE / INTERNAL ========== //
// ========== RESTRICTED FUNCTIONS ========== //
function setRewardTokens(address[] calldata _tokens, bool[] calldata _statuses)
    external
    onlyOwner {
        require(_tokens.length > 0, "please pass a positive number of reward tokens");
        require(_tokens.length == _statuses.length, "please pass same number of tokens and statuses");

        for (uint i = 0; i < _tokens.length; i++) {
            rewardsTokens[_tokens[i]] = _statuses[i];
        }

        emit LogSetRewardTokens(_tokens, _statuses);
    }
// Solidity 0.4.10
//
// Ballot functions
//
// To vote for a preferred Trustee.
function vote(address _candidate)
        public
        isHolder(msg.sender)
        isHolder(_candidate)
        returns (bool)
    {
        // Only prevent reentry not entry during panic
        require(!__reMutex);
        
        Holder holder = holders[msg.sender];
        revoke(holder);
        holder.votingFor = _candidate;
        revote(holder);
        election();
        return true;
    }
// Solidity 0.7.6
/**
 Get asset 1 twap price for the period of [now - secondsAgo, now]
 */
function getTWAP(int56[] memory prices, uint32 secondsAgo)
        internal
        pure
        returns (int128)
    {
        // Formula is
        // 1.0001 ^ (currentPrice - pastPrice) / secondsAgo
        if (secondsAgo == 0) {
            return ABDKMath64x64.fromInt(1);
        }
        int256 currentPrice = int256(prices[1]);
        int256 pastPrice = int256(prices[0]);

        int256 diff = currentPrice - pastPrice;
        uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff);

        int128 power = ABDKMath64x64.divu(10001, 10000);
        int128 _fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo));
        uint256 fraction = uint256(ABDKMath64x64.toUInt(_fraction));

        int128 twap = ABDKMath64x64.pow(power, fraction);

        // This is necessary because we cannot call .pow on unsigned integers
        // And thus when asset0Price > asset1Price we need to reverse the value
        twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap;
        return twap;
    }
// Solidity 0.7.6
/**
 * Helper function to calculate how much to swap to deposit / withdraw
 * In Uni Pool to satisfy the required buffer balance in xU3LP of 5%
 */
function calculateSwapAmount(
        uint256 amount0ToMint,
        uint256 amount1ToMint,
        uint256 amount0Minted,
        uint256 amount1Minted,
        int128 liquidityRatio
    ) internal pure returns (uint256 swapAmount) {
        // formula: swapAmount =
        // (amount0ToMint * amount1Minted -
        //  amount1ToMint * amount0Minted) /
        // ((amount0Minted + amount1Minted) +
        //  liquidityRatio * (amount0ToMint + amount1ToMint))
        uint256 mul1 = amount0ToMint.mul(amount1Minted);
        uint256 mul2 = amount1ToMint.mul(amount0Minted);

        uint256 sub = subAbs(mul1, mul2);
        uint256 add1 = amount0Minted.add(amount1Minted);
        uint256 add2 =
            ABDKMath64x64.mulu(
                liquidityRatio,
                amount0ToMint.add(amount1ToMint)
            );
        uint256 add = add1.add(add2);

        // Some numbers are too big to fit in ABDK's div 128-bit representation
        // So calculate the root of the equation and then raise to the 2nd power
        uint128 subsqrt = ABDKMath64x64.sqrtu(sub);
        uint128 addsqrt = ABDKMath64x64.sqrtu(add);
        int128 nRatio = ABDKMath64x64.divu(subsqrt, addsqrt);
        int64 n = ABDKMath64x64.toInt(nRatio);
        swapAmount = uint256(n)**2;
    }
// Solidity 0.7.6
// comparator for 32-bit timestamps
// @return bool Whether a <= b
function lte(
        uint32 time,
        uint32 a,
        uint32 b
    ) internal pure returns (bool) {
        if (a <= time && b <= time) return a <= b;

        uint256 aAdjusted = a > time ? a : a + 2**32;
        uint256 bAdjusted = b > time ? b : b + 2**32;

        return aAdjusted <= bAdjusted;
    }
// Solidity 0.4.10
// Loops through holders to find the holder with most votes and declares
// them to be the Executive;
function election()
        internal
    {
        uint max;
        uint winner;
        uint votes;
        uint8 i;
        address addr;
        
        if (0 == totalSupply) return;
        
        while(++i != 0)
        {
            addr = holderIndex[i];
            if (addr != 0x0) {
                votes = holders[addr].votes;
                if (votes > max) {
                    max = votes;
                    winner = i;
                }
            }
        }
        trustee = holderIndex[winner];
        Trustee(trustee);
    }
// Solidity 0.8.0
/// @notice This mints a teddy.
/// @param recipient This is the address of the user who is minting the teddy.
/// @param voucher This is the unique NFTVoucher that is to be minted.
function mintNFT(address recipient, NFTVoucher calldata voucher) external payable returns (uint256) {
        address signer = _verify(voucher);
        require(voucher.tokenId > 0, "Invalid Token ID.");
        require(voucher.edition >= 1 && voucher.edition <= 5, "Invalid token data. (Edition must be between 1 and 5)");
        require(voucher.locked == true || (voucher.locked == false && voucher.edition == 1), "Only first edition NFT's can be minted unlocked.");
        require(owner() == signer, "This voucher is invalid.");
        require(msg.value == _safeParseInt(voucher.initialPrice), "Incorrect amount of ETH sent.");
        require(_editions[voucher.edition] < _maxSupply[voucher.edition], "No more NFT's available to be minted.");
        
        _setTokenLock(voucher.tokenId, voucher.locked);
        _incrementEditionCount(voucher.edition);
        _safeMint(recipient, voucher.tokenId);
        _setTokenURI(voucher.tokenId, voucher.uri);
        
        return voucher.tokenId;
    }
// Solidity 0.8.0
/// @notice When a user orders a custom NFT, the user works with our designer to build the perfect NFT.
/// Once happy with the product, the metadata is updated using this function and locked.
/// @param tokenId The Token ID to be updated
/// @param uri The new URI to be set on the token.
function updateMetadata(uint256 tokenId, string calldata uri) external onlyOwner {
        require(tokenId <= 100, "Customizations are only available for the first 100 tokens.");
        require(_locks[tokenId] != true, "The metadata for this token is locked.");
        _setTokenLock(tokenId, true);
        _setTokenURI(tokenId, uri);
    }
// Solidity 0.8.0
/// @notice Gets all the tokens that the address owns.
/// @param _owner The address of an owner you want to view tokens of.
function getTokenIds(address _owner) external view returns (uint[] memory) {
        uint[] memory _tokensOfOwner = new uint[](balanceOf(_owner));
        uint i;

        for (i = 0; i < balanceOf(_owner); i++) {
            _tokensOfOwner[i] = tokenOfOwnerByIndex(_owner, i);
        }

        return (_tokensOfOwner);
    }
// Solidity 0.8.0
/// @notice This safely converts a string into an uint.
/// @param _a This is the string to be converted into a uint.
function _safeParseInt(string memory _a) private pure returns (uint _parsedInt) {
        bytes memory bresult = bytes(_a);
        uint mint = 0;
        bool decimals = false;
        for (uint i = 0; i < bresult.length; i++) {
            if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
                if (decimals) {
                   break;
                }
                mint *= 10;
                mint += uint(uint8(bresult[i])) - 48;
            } else if (uint(uint8(bresult[i])) == 46) {
                require(!decimals, 'More than one decimal encountered in string!');
                decimals = true;
            } else {
                revert("Non-numeral character encountered in string!");
            }
        }
        return mint;
    }
// Solidity 0.8.10
/**
 * @notice Make New 0xBatz 
 * @param amount Amount of 0xBatz to mint
 * @dev Utilize unchecked {} and calldata for gas savings.
 */
function mint(uint256 amount) public payable {
      require(mintEnabled, "Minting is disabled.");
      require(psupply + amount <= maxSupply - reserved, "Amount exceeds maximum supply of 0xBatz.");
      require(amount <= perMint, "Amount exceeds current maximum 0xBatz per mint.");
      require(price * amount <= msg.value, "Ether value sent is not correct.");
      uint16 supply = psupply;
      unchecked {
          for (uint16 i = 0; i < amount; i++) {
              _safeMint(msg.sender, supply++);
          }
      }
      psupply = supply;

      if (psupply == 666) {
        price = mintPrice;
        perMint = 10;
      }
  }
// Solidity 0.8.10
/**
 * @notice Send reserved 0xBatz 
 * @param _to address to send reserved nfts to.
 * @param _amount number of nfts to send 
 */
function fetchTeamReserved(address _to, uint16 _amount)
      public
      onlyOwner
  {
      require( _to !=  address(0), "Zero address error");
      require( _amount <= reserved, "Exceeds reserved babies supply");
      uint16 supply = psupply;
      unchecked {
        for (uint8 i = 0; i < _amount; i++) {
            _safeMint(_to, supply++);
        }
      }
      psupply = supply;
      reserved -= _amount;
  }
// Solidity 0.4.18
//////////////////////////////////////////////////
/// Begin Ulink token functionality
//////////////////////////////////////////////////
/// @dev Ulink token constructor
function Ulink() public
    {
        // Define owner
        owner = msg.sender;
        // Define initial owner supply. (ether here is used only to get the decimals right)
        uint _initOwnerSupply = 50000 ether;
        // One-time bulk mint given to owner
        bool _success = mint(msg.sender, _initOwnerSupply);
        // Abort if initial minting failed for whatever reason
        require(_success);

        ////////////////////////////////////
        // Set up state minting variables
        ////////////////////////////////////

        // Set last minted to current block.timestamp ('now')
        ownerTimeLastMinted = now;
        
        // 4100 minted tokens per day, 86400 seconds in a day
        ownerMintRate = calculateFraction(4100, 86400, decimals);
        
        // 5,000,000 targeted minted tokens per year via staking; 31,536,000 seconds per year
        globalMintRate = calculateFraction(5000000, 31536000, decimals);
    }
// Solidity 0.5.17
/**
 * @dev Sets or upgrades the RariGovernanceTokenDistributor of the RariFundToken. Caller must have the {MinterRole}.
 * @param newContract The address of the new RariGovernanceTokenDistributor contract.
 * @param force Boolean indicating if we should not revert on validation error.
 */
function setGovernanceTokenDistributor(address payable newContract, bool force) external onlyMinter {        
        if (!force && address(rariGovernanceTokenDistributor) != address(0)) {
            require(rariGovernanceTokenDistributor.disabled(), "The old governance token distributor contract has not been disabled. (Set `force` to true to avoid this error.)");
            require(newContract != address(0), "By default, the governance token distributor cannot be set to the zero address. (Set `force` to true to avoid this error.)");
        }

        rariGovernanceTokenDistributor = IRariGovernanceTokenDistributor(newContract);

        if (newContract != address(0)) {
            if (!force) require(block.number <= rariGovernanceTokenDistributor.distributionStartBlock(), "The distribution period has already started. (Set `force` to true to avoid this error.)");
            if (block.number < rariGovernanceTokenDistributor.distributionEndBlock()) rariGovernanceTokenDistributor.refreshDistributionSpeeds(IRariGovernanceTokenDistributor.RariPool.Yield);
        }

        emit GovernanceTokenDistributorSet(newContract);
    }