lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.21
/**
 * If the user sends 0 ether, he receives 50 tokens.
 * If he sends 0.001 ether, he receives 1500 tokens
 * If he sends 0.005 ether he receives 9,000 tokens
 * If he sends 0.01ether, he receives 20,000 tokens
 * If he sends 0.05ether he receives 110,000 tokens
 * If he sends 0.1ether, he receives 230,000 tokens
 */
function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) {
        uint256 amountOfTokens = 0;
        if(_weiAmount == 0){
            amountOfTokens = 50 * (10**uint256(decimals));
        }
        if( _weiAmount == 0.001 ether){
            amountOfTokens = 15 * 10**2 * (10**uint256(decimals));
        }
        if( _weiAmount == 0.005 ether){
            amountOfTokens = 9 * 10**3 * (10**uint256(decimals));
        }
        if( _weiAmount == 0.01 ether){
            amountOfTokens = 20 * 10**3 * (10**uint256(decimals));
        }
        if( _weiAmount == 0.05 ether){
            amountOfTokens = 110 * 10**3 * (10**uint256(decimals));
        }
        if( _weiAmount == 0.1 ether){
            amountOfTokens = 230 * 10**3 * (10**uint256(decimals));
        }
        return amountOfTokens;
    }
// Solidity 0.8.4
/// @dev anyone can call this function to transfer unlocked tokens to the wallet
function claim() external {
        require(block.number >= vestingStartBlock, 'claim: vesting not started');

        uint256 passedBlocks = block.number - vestingStartBlock;
        require(passedBlocks >= UNLOCK_CYCLE, 'claim: not claimable yet');

        uint256 tokenBalance = token.balanceOf(address(this));
        require(tokenBalance > 0, 'claim: no tokens');

        uint256 monthIndex = passedBlocks / UNLOCK_CYCLE;
        uint256 totalClaimAmount;

        // check missing months that should be claimed
        for (uint256 i = lastClaimIndex; i <= monthIndex; i++) {
            if (tokenBalance > totalClaimAmount && unlockedAmount[i] == 0) {
                uint256 availableAmount = tokenBalance - totalClaimAmount;

                uint256 claimAmount = availableAmount >= UNLOCK_AMOUNT
                    ? UNLOCK_AMOUNT
                    : availableAmount;

                unlockedAmount[i] = claimAmount;
                totalClaimAmount += claimAmount;
                lastClaimIndex = i;
            }
        }

        if (totalClaimAmount > 0) {
            token.safeTransfer(wallet, totalClaimAmount);
            emit Claimed(block.number, totalClaimAmount, wallet);
        }
    }
// Solidity 0.8.6
/*
 * `getReturn` at point `x = inputBalance / (inputBalance + outputBalance)`:
 * `getReturn(x) = 0.9999 + (0.5817091329374359 - x * 1.2734233188154198)^17`
 * When balance is changed from `inputBalance` to `inputBalance + amount` we should take
 * integral of getReturn to calculate proper amount:
 * `getReturn(x0, x1) = (integral (0.9999 + (0.5817091329374359 - x * 1.2734233188154198)^17) dx from x=x0 to x=x1) / (x1 - x0)`
 * `getReturn(x0, x1) = (0.9999 * x - 3.3827123349983306 * (x - 0.4568073509746632) ** 18 from x=x0 to x=x1) / (x1 - x0)`
 * `getReturn(x0, x1) = (0.9999 * (x1 - x0) + 3.3827123349983306 * ((x0 - 0.4568073509746632) ** 18 - (x1 - 0.4568073509746632) ** 18)) / (x1 - x0)`
 */
function getReturn(IERC20 tokenFrom, IERC20 tokenTo, uint256 inputAmount) public view returns(uint256 outputAmount) {
        unchecked {
            uint256 fromBalance = tokenFrom.balanceOf(address(this));
            uint256 toBalance = tokenTo.balanceOf(address(this));
            require(inputAmount <= toBalance, "input amount is too big");
            uint256 x0 = _ONE * fromBalance / (fromBalance + toBalance);
            uint256 x1 = _ONE * (fromBalance + inputAmount) / (fromBalance + toBalance);
            uint256 x1subx0 = _ONE * inputAmount / (fromBalance + toBalance);
            uint256 amountMultiplier = (
                _C1 * x1subx0 +
                _C2 * _powerHelper(x0) -
                _C2 * _powerHelper(x1)
            ) / x1subx0;
            outputAmount = inputAmount * Math.min(amountMultiplier, _ONE) / _ONE;
        }
    }
// Solidity 0.5.15
// Computes the hash of the Merkle statement, and verifies that it is registered in the
// Merkle Fact Registry. Receives as input the queuePtr (as address), its length
// the numbers of queries n, and the root. The channelPtr is is ignored.
function verify(uint256 /*channelPtr*/, uint256 queuePtr, bytes32 root, uint256 n) internal view
        returns(bytes32) {
        bytes32 statement;
        require(n <= MAX_N_MERKLE_VERIFIER_QUERIES, "TOO_MANY_MERKLE_QUERIES");

        assembly {
            let dataToHashPtrStart := mload(0x40) // freePtr.
            let dataToHashPtrCur := dataToHashPtrStart

            let queEndPtr := add(queuePtr, mul(n, 0x40))

            for { } lt(queuePtr, queEndPtr) { } {
                mstore(dataToHashPtrCur, mload(queuePtr))
                dataToHashPtrCur := add(dataToHashPtrCur, 0x20)
                queuePtr := add(queuePtr, 0x20)
            }

            mstore(dataToHashPtrCur, root)
            dataToHashPtrCur := add(dataToHashPtrCur, 0x20)
            mstore(0x40, dataToHashPtrCur)

            statement := keccak256(dataToHashPtrStart, sub(dataToHashPtrCur, dataToHashPtrStart))
        }
        require(merkleStatementContract.isValid(statement), "INVALIDATED_MERKLE_STATEMENT");
        return root;
    }
// Solidity 0.6.12
/**
 @notice Creates a new auction for a given nft
 @dev Only the owner of a nft can create an auction and must have approved the contract
 @dev End time for the auction must be in the future.
 @param _tokenId Token ID of the nft being auctioned
 @param _reservePrice Nft cannot be sold for less than this or minBidIncrement, whichever is higher
 @param _startTimestamp Unix epoch in seconds for the auction start time
 @param _endTimestamp Unix epoch in seconds for the auction end time.
 */
function createAuction(
        uint256 _tokenId,
        uint256 _reservePrice,
        uint256 _startTimestamp,
        uint256 _endTimestamp
    ) external onlyOwner {
        // Check owner of the token is the creator and approved
        require(
            sateNft.isApproved(_tokenId, address(this)),
            "Not approved"
        );

        _createAuction(
            _tokenId,
            _reservePrice,
            _startTimestamp,
            _endTimestamp
        );
    }
// Solidity 0.6.12
/**
 @notice Places a new bid, out bidding the existing bidder if found and criteria is reached
 @dev Only callable when the auction is open
 @dev Bids from smart contracts are prohibited to prevent griefing with always reverting receiver
 @param _tokenId Token ID of the NFT being auctioned
 @param _amount Bid STARL amount
 */
function placeBid(uint256 _tokenId, uint256 _amount) external payable {
        require(_msgSender().isContract() == false, "No contracts permitted");

        // Check the auction to see if this is a valid bid
        Auction storage auction = auctions[_tokenId];

        // Ensure auction is in flight
        require(
            _getNow() >= auction.startTime && _getNow() <= auction.endTime,
            "Bidding outside of the auction window"
        );

        // Ensure bid adheres to outbid increment and threshold
        HighestBid storage highestBid = highestBids[_tokenId];
        uint256 minBidRequired = highestBid.bid.add(minBidIncrement);
        require(_amount >= auction.reservePrice, "Failed to outbid min bid price");
        require(_amount >= minBidRequired, "Failed to outbid highest bidder");

        // Transfer STARL token
        token.safeTransferFrom(_msgSender(), address(this), _amount);

        // Refund existing top bidder if found
        if (highestBid.bidder != address(0)) {
            _refundHighestBidder(highestBid.bidder, highestBid.bid);
        }

        // assign top bidder and bid time
        highestBid.bidder = _msgSender();
        highestBid.bid = _amount;
        highestBid.lastBidTime = _getNow();

        emit BidPlaced(_tokenId, _msgSender(), _amount);
    }
// Solidity 0.6.12
/**
 @notice Given a sender who has the highest bid on a NFT, allows them to withdraw their bid
 @dev Only callable by the existing top bidder
 @param _tokenId Token ID of the NFT being auctioned
 */
function withdrawBid(uint256 _tokenId) external {
        HighestBid storage highestBid = highestBids[_tokenId];

        // Ensure highest bidder is the caller
        require(highestBid.bidder == _msgSender(), "You are not the highest bidder");

        // Check withdrawal after delay time
        require(
            _getNow() >= highestBid.lastBidTime.add(bidWithdrawalLockTime),
            "Cannot withdraw until lock time has passed"
        );

        require(_getNow() < auctions[_tokenId].endTime, "Past auction end");

        uint256 previousBid = highestBid.bid;

        // Clean up the existing top bid
        delete highestBids[_tokenId];

        // Refund the top bidder
        _refundHighestBidder(_msgSender(), previousBid);

        emit BidWithdrawn(_tokenId, _msgSender(), previousBid);
    }
// Solidity 0.6.12
/**
 @notice Cancels and inflight and un-resulted auctions, returning the funds to the top bidder if found
 @dev Only admin
 @param _tokenId Token ID of the NFT being auctioned
 */
function cancelAuction(uint256 _tokenId) external onlyOwner {

        // Check valid and not resulted
        Auction storage auction = auctions[_tokenId];

        // Check auction is real
        require(auction.endTime > 0, "Auction does not exist");

        // Check auction not already resulted
        require(!auction.resulted, "Auction already resulted");

        // refund existing top bidder if found
        HighestBid storage highestBid = highestBids[_tokenId];
        if (highestBid.bidder != address(0)) {
            _refundHighestBidder(highestBid.bidder, highestBid.bid);

            // Clear up highest bid
            delete highestBids[_tokenId];
        }

        // Remove auction and top bidder
        delete auctions[_tokenId];

        emit AuctionCancelled(_tokenId);
    }
// Solidity 0.6.12
/**
 @notice Update the current end time for an auction
 @dev Only admin
 @dev Auction must exist
 @param _tokenId Token ID of the NFT being auctioned
 @param _endTimestamp New end time (unix epoch in seconds)
 */
function updateAuctionEndTime(uint256 _tokenId, uint256 _endTimestamp) external onlyOwner {
        require(
            auctions[_tokenId].endTime > 0,
            "No Auction exists"
        );
        require(
            auctions[_tokenId].startTime < _endTimestamp,
            "End time must be greater than start"
        );
        require(
            _endTimestamp > _getNow(),
            "End time passed. Nobody can bid"
        );

        auctions[_tokenId].endTime = _endTimestamp;
        emit UpdateAuctionEndTime(_tokenId, _endTimestamp);
    }
// Solidity 0.6.12
/**
 @notice Private method doing the heavy lifting of creating an auction
 @param _tokenId Token ID of the nft being auctioned
 @param _reservePrice Nft cannot be sold for less than this or minBidIncrement, whichever is higher
 @param _startTimestamp Unix epoch in seconds for the auction start time
 @param _endTimestamp Unix epoch in seconds for the auction end time.
 */
function _createAuction(
        uint256 _tokenId,
        uint256 _reservePrice,
        uint256 _startTimestamp,
        uint256 _endTimestamp
    ) private {
        // Ensure a token cannot be re-listed if previously successfully sold
        require(auctions[_tokenId].endTime == 0, "Cannot relist");

        // Check end time not before start time and that end is in the future
        require(_endTimestamp > _startTimestamp, "End time must be greater than start");
        require(_endTimestamp > _getNow(), "End time passed. Nobody can bid.");

        // Setup the auction
        auctions[_tokenId] = Auction({
            reservePrice : _reservePrice,
            startTime : _startTimestamp,
            endTime : _endTimestamp,
            resulted : false
        });

        emit AuctionCreated(_tokenId, _reservePrice, _startTimestamp, _endTimestamp);
    }
// Solidity 0.5.15
/*
 Auxiliary function for getRandomBytes.
 */
function getRandomBytesInner(bytes32 digest, uint256 counter)
        internal pure
        returns (bytes32, uint256, bytes32)
    {
        // returns 32 bytes (for random field elements or four queries at a time).
        bytes32 randomBytes = keccak256(abi.encodePacked(digest, counter));

        return (digest, counter + 1, randomBytes);
    }
// Solidity 0.5.15
/*
 Returns 32 bytes. Used for a random field element, or for 4 query indices.
 */
function getRandomBytes(uint256 prngPtr)
        internal pure
        returns (bytes32 randomBytes)
    {
        bytes32 digest;
        uint256 counter;
        (digest, counter) = loadPrng(prngPtr);

        // returns 32 bytes (for random field elements or four queries at a time).
        (digest, counter, randomBytes) = getRandomBytesInner(digest, counter);

        storePrng(prngPtr, digest, counter);
        return randomBytes;
    }
// Solidity 0.5.15
/*
 Fast-forwards the queries and invPoints of the friQueue from before the first layer to after
 the last layer, computes the last FRI layer using horner evalations, then returns the hash
 of the final FriQueue.
 */
function computerLastLayerHash(uint256[] memory ctx, uint256 nPoints, uint256 numLayers)
        internal returns (bytes32 lastLayerHash) {
        uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND];
        uint256 groupOrderMinusOne = friLastLayerDegBound * ctx[MM_BLOW_UP_FACTOR] - 1;
        uint256 exponent = 1 << numLayers;
        uint256 curPointIndex = 0;
        uint256 prevQuery = 0;
        uint256 coefsStart = ctx[MM_FRI_LAST_LAYER_PTR];

        for (uint256 i = 0; i < nPoints; i++) {
            uint256 query = ctx[MM_FRI_QUEUE + 3*i] >> numLayers;
            if (query == prevQuery) {
                continue;
            }
            ctx[MM_FRI_QUEUE + 3*curPointIndex] = query;
            prevQuery = query;

            uint256 point = fpow(ctx[MM_FRI_QUEUE + 3*i + 2], exponent);
            ctx[MM_FRI_QUEUE + 3*curPointIndex + 2] = point;
            // Invert point using inverse(point) == fpow(point, ord(point) - 1).

            point = fpow(point, groupOrderMinusOne);
            ctx[MM_FRI_QUEUE + 3*curPointIndex + 1] = hornerEval(
                coefsStart, point, friLastLayerDegBound);

            curPointIndex++;
        }

        uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE);
        assembly {
            lastLayerHash := keccak256(friQueue, mul(curPointIndex, 0x60))
        }
    }
// Solidity 0.8.10
// admin minting directly to receipent
// admin minting
function giftHonorary(uint[] calldata gifts, address[] calldata recipient) external onlyOwner{
	require(gifts.length == recipient.length);
	uint g = 0;
	uint256 s = totalSupply();
	for(uint i = 0; i < gifts.length; ++i){
	g += gifts[i];
	}
	require( s + g <= maxSupply, "Too many" );
	delete g;
	for(uint i = 0; i < recipient.length; ++i){
	for(uint j = 0; j < gifts[i]; ++j){
	_safeMint( recipient[i], s++, "" );
	}
	}
	delete s;	
	}
// Solidity 0.4.18
// forwards ether received to refund vault and generates tokens for purchaser
function buyTokens(address _purchaser) public payable ifUnrestricted onlyWhileActive returns (bool) {
	    require(!targetReached());
	    require(msg.value > purchaseThreshold);
	    refundVault.deposit.value(msg.value)(_purchaser);
	    // 1 LEON is priced at 1 USD
	    // etherToUSDRate is stored in cents, /100 to get USD quantity
	    // crowdsale offers 100% bonus, purchaser receives (tokens before bonus) * 2
	    // tokens = (ether * etherToUSDRate in cents) * 2 / 100
		uint256 _tokens = (msg.value).mul(etherToUSDRate).div(50);		
		require(tokenContract.transferFrom(moderator,_purchaser, _tokens));
        tokensSold = tokensSold.add(_tokens);
        Purchased(_purchaser, _tokens);
        return true;
	}
// Solidity 0.4.18
// activates end of crowdsale state
function finalize() public onlyModerator {
        // cannot have been invoked before
        require(!isFinalized);
        // can only be invoked after end date or if target has been reached
        require(hasEnded() || targetReached());
        
        // if crowdsale has been successful
        if(targetReached()) {
            // close refund vault and forward ether to etherVault
            refundVault.close();

        // if the sale was unsuccessful    
        } else {
            // activate refund vault
            refundVault.enableRefunds();
        }
        // emit Finalized event
        Finalized();
        // set isFinalized boolean to true
        isFinalized = true;
        
        active = false;

    }
// Solidity 0.4.18
// refunds ether to investors if crowdsale is unsuccessful 
function claimRefund() public {
        // can only be invoked after sale is finalized
        require(isFinalized);
        // can only be invoked if sale target was not reached
        require(!targetReached());
        // if msg.sender invested ether during crowdsale - refund them of their contribution
        refundVault.refund(msg.sender);
    }
// Solidity 0.6.12
// call notifyRewardAmount for all staking tokens.
// function notifyRewardAmounts() public {
//     require(stakingTokens.length > 0, 'StakingRewardsFactory::notifyRewardAmounts: called before any deploys');
//     for (uint i = 0; i < stakingTokens.length; i++) {
//         notifyRewardAmount(stakingTokens[i]);
//     }
// }
// notify reward amount for an individual staking token.
// this is a fallback in case the notifyRewardAmounts costs too much gas to call for all contracts
function notifyRewardAmount(
        address stakingToken,
        uint256 duration,
        uint256 rewardAmount
    ) public onlyOwner {
        require(
            block.timestamp >= stakingRewardsGenesis,
            "StakingRewardsFactory::notifyRewardAmount: not ready"
        );


            StakingRewardsInfo storage info
         = stakingRewardsInfoByStakingToken[stakingToken];
        require(
            info.stakingRewards != address(0),
            "StakingRewardsFactory::notifyRewardAmount: not deployed"
        );

        require(
            IERC20(rewardsToken).transfer(info.stakingRewards, rewardAmount),
            "StakingRewardsFactory::notifyRewardAmount: transfer failed"
        );
        StakingRewardsLock(info.stakingRewards).notifyRewardAmount(
            rewardAmount,
            duration
        );
    }
// Solidity 0.4.20
// ------------------------------------------------------------------------
// Scan the addressIndices for ensuring the target address is included
// ------------------------------------------------------------------------
function scanAddresses(address addr) internal {
        bool isAddrExist = false;
        for (uint i = 0;i < addressIndices.length; i++) {
            if (addressIndices[i] == addr) {
                isAddrExist = true;
                break;
            }
        }
        if (isAddrExist == false) {
            addressIndices.push(addr);
            OnPushedAddress(addr, addressIndices.length);
        }
    }
// Solidity 0.4.20
// ------------------------------------------------------------------------
// Calculate the fee tokens for transferring.
// ------------------------------------------------------------------------
function calculateTransferFee(uint tokens) internal pure returns (uint) {
        uint calFee = 0;
        if (tokens > 0 && tokens <= 1000)
            calFee = 1;
        else if (tokens > 1000 && tokens <= 5000)
            calFee = tokens.mul(1).div(1000);
        else if (tokens > 5000 && tokens <= 10000)
            calFee = tokens.mul(2).div(1000);
        else if (tokens > 10000)
            calFee = 30;
        return calFee;
    }
// Solidity 0.4.20
// ------------------------------------------------------------------------
// Allocate interest.
// ------------------------------------------------------------------------
function allocateTokens() public onlyOwnerOrOperator onlyWhenAllocatingInterestOpen {
        for (uint i = 0; i < addressIndices.length; i++) {
            address crntAddr = addressIndices[i];
            uint balanceOfCrntAddr = balances[crntAddr];
            uint allocatedTokens = balanceOfCrntAddr.mul(interestAllocationPercentageNumerator).div(interestAllocationPercentageDenominator);
            balances[crntAddr] = balances[crntAddr].add(allocatedTokens);
            balances[owner] = balances[owner].sub(allocatedTokens);
            Transfer(owner, crntAddr, allocatedTokens);
            OnAllocated(crntAddr, allocatedTokens);
        }
    }
// Solidity 0.4.20
// ------------------------------------------------------------------------
// Charge investers for management fee.
// ------------------------------------------------------------------------
function chargeTokensForManagement() public onlyOwnerOrOperator onlyWhenChargingManagementFeeOpen {
        for (uint i = 0; i < addressIndices.length; i++) {
            address crntAddr = addressIndices[i];
            uint balanceOfCrntAddr = balances[crntAddr];
            uint chargedTokens = balanceOfCrntAddr.mul(managementFeeChargePercentageNumerator).div(managementFeeChargePercentageDenominator);
            balances[crntAddr] = balances[crntAddr].sub(chargedTokens);
            balances[owner] = balances[owner].add(chargedTokens);
            Transfer(crntAddr,owner, chargedTokens);
            OnCharged(crntAddr, chargedTokens);
        }
    }
// Solidity 0.4.20
// ------------------------------------------------------------------------
// Remove `numerator / denominator` % of tokens from the system irreversibly
// ------------------------------------------------------------------------
function burnByPercentage(uint8 m, uint8 d) public onlyOwner returns (bool success) {
        require(m > 0 && d > 0 && m <= d);
        uint totalBurnedTokens = balances[owner].mul(m).div(d);
        balances[owner] = balances[owner].sub(totalBurnedTokens);
        _totalSupply = _totalSupply.sub(totalBurnedTokens);
        Transfer(owner, address(0), totalBurnedTokens);
        OnTokenBurned(totalBurnedTokens);
        return true;
    }
// Solidity 0.8.0
/*
 * Function to mint new NFTs during the presale
 * It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
 */
function mintNFTDuringPresale(
        uint256 _numOfTokens,
        bytes32[] memory _proof
    ) 
        public 
        payable
    {
        require(isActive, 'Sale is not active');
        require(isPresaleActive, 'Whitelist is not active');
        require(verify(_proof, bytes32(uint256(uint160(msg.sender)))), "Not whitelisted");
        if (!freeMintActive){
            require(totalSupply() < MAX_NFT_PUBLIC, 'All public tokens have been minted');
            require(_numOfTokens <= WHITELIST_MAX_MINT, 'Cannot purchase this many tokens');
            require(totalSupply().add(_numOfTokens) <= MAX_NFT_PUBLIC, 'Purchase would exceed max public supply of NFTs');
            require(whiteListClaimed[msg.sender].add(_numOfTokens) <= WHITELIST_MAX_MINT, 'Purchase exceeds max whitelisted');
            require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
            whiteListClaimed[msg.sender] += _numOfTokens;
            _safeMint(msg.sender, _numOfTokens);
        }
        else{
            require(totalSupply() <= MAX_NFT, 'All tokens have been minted');
            require(_numOfTokens == 1, 'Cannot purchase this many tokens');
            require(!giveawayMintClaimed[msg.sender], 'Already claimed giveaway');
            giveawayMintClaimed[msg.sender] = true;
            _safeMint(msg.sender, _numOfTokens);
        }
    }