lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.10
// required return value from onERC721Received() function
function make( uint256 _sellunits,
                 address _selltok,
                 uint256 _askunits,
                 address _asktok ) public payable returns (bytes32) {

    require( safelist[_selltok], "unrecognized sell token" );
    require( safelist[_asktok], "unrecognized ask token" );

    if (_selltok == address(0)) { // ETH
      require( _sellunits + makerfee >= _sellunits, "safemath: bad arg" );
      require( msg.value >= _sellunits + makerfee, "insufficient fee" );
      admin_.transfer( msg.value - _sellunits );
    }
    else {
      ERC20 tok = ERC20(_selltok);
      require( tok.transferFrom(msg.sender, address(this), _sellunits),
               "failed transferFrom()" );
      admin_.transfer( msg.value );
    }

    bytes32 id = keccak256( abi.encodePacked(
      counter++, now, msg.sender, _sellunits, _selltok, _askunits, _asktok) );

    listings[id] =
      Listing( msg.sender, _sellunits, _selltok, _askunits, _asktok );

    emit Made( id, msg.sender );
    return id;
  }
// Solidity 0.6.10
// ERC721 (NFT) transfer callback
function onERC721Received( address _operator,
                             address _from,
                             uint256 _tokenId,
                             bytes calldata _data) external returns(bytes4) {
    if (   _operator == address(0x0)
        || _from == address(0x0)
        || _data.length > 0 ) {} // suppress warnings unused params

    ERC721(msg.sender).transferFrom( address(this), admin_, _tokenId );
    return magic;
  }
// Solidity 0.6.12
/// @notice registers wallet addresses for users
/// @param users Array of strings that identifies users
/// @param wallets Array of wallet addresses
function addWalletList(string[] memory users, address[] memory wallets) public onlyEndUserAdmin {
        require(users.length == wallets.length, "Whitelisted: User and wallet lists must be of same length!");
        for (uint i = 0; i < wallets.length; i++) {
            _addWallet(users[i], wallets[i]);
        }
    }
// Solidity 0.5.12
/// @notice returns current sell price for one token
function sellPrice() 
    external
    view
    returns(uint256)
{
    // avoid dividing by zero
    require(totalSupply != 0, "function called too early (supply is zero)");
    //represents selling one "full token" since the token has 18 decimals
    uint256 etherValue = tokensToEther( 1e18 );
    uint[2] memory feeAndValue = valueAfterFee( etherValue );
    return feeAndValue[1];
}
// Solidity 0.5.12
/// @notice calculates current buy price for one token
function currentBuyPrice() 
    external
    view
    returns(uint256)
{
    // avoid dividing by zero
    require(totalSupply != 0, "function called too early (supply is zero)");
    //represents buying one "full token" since the token has 18 decimals
    uint256 etherValue = tokensToEther( 1e18 );
    uint[2] memory feeAndValue = valueAfterFee( etherValue );
    //NOTE: this is not strictly correct, but gets very close to real purchase value
    uint256 totalCost = etherValue + feeAndValue[0];
    return totalCost;
}
// Solidity 0.5.12
/// @notice calculates amount of ether (as wei) received if input number of tokens is sold at current price and fee rate
/// @param tokensToSell Desired number of tokens (as an integer) from which to calculate equivalent value of ether
/// @return etherAfterFee Amount of ether that would be received for selling tokens
function calculateExpectedWei(uint256 tokensToSell) 
    external
    view
    returns(uint256)
{
    require( tokensToSell <= totalSupply, "unable to calculate for amount of tokens greater than current supply" );
    //finds ether value of tokens before fee
    uint256 etherValue = tokensToEther( tokensToSell );
    //calculates ether after fee
    uint256 etherAfterFee = valueAfterFee( etherValue )[1];
    return etherAfterFee;
}
// Solidity 0.5.12
/// @notice function for donating to slush fund. adjusts current fee rate as fast as possible but does not give the message sender any tokens
/// @dev invoked internally when partner contract sends funds to this contract (see fallback function)
function makeItRain()
    public
    payable
    returns(bool)
{
    //avoid dividing by zero
    require(totalSupply != 0, "makeItRain function called too early (supply is zero)");
    uint256 amountEther = msg.value;
    uint256 addedRewards = SafeMath.mul( amountEther , MAGNITUDE );
    uint256 additionalRewardsPerToken = SafeMath.div( addedRewards , totalSupply );
    _rewardsPerTokenAllTime = SafeMath.add( _rewardsPerTokenAllTime , additionalRewardsPerToken );
    //updates balance in slush fund and calculates new fee rate
    require( updateSlushFund( amountEther ), "error in calling updateSlushFund" );
    return true;
}
// Solidity 0.5.12
/// @notice returns reward balance of desired address
/// @dev invoked internally in cashOut and doubleDown functions
/// @param playerAddress Address which sender wants to know the rewards balance of
/// @return playerRewards Current ether value of unspent rewards of playerAddress
function rewardsOf( address playerAddress )
    public
    view
    returns(uint256 playerRewards)
{
    playerRewards = (uint256) ( ( (int256)( _rewardsPerTokenAllTime * tokenBalanceLedger_[ playerAddress ] ) - payoutsToLedger_[ playerAddress ] ) / IMAGNITUDE );
    return playerRewards;
}
// Solidity 0.5.12
//INTERNAL FUNCTIONS
//recalculates fee rate given current contract state
function calcFeeRate()
    internal
    returns(bool)
{
    uint excessSlush = ( (_slushFundBalance % FEE_CYCLE_SIZE) * MAX_VARIANCE );
    uint16 cycleLocation = uint16( excessSlush / FEE_CYCLE_SIZE );
    uint16 newFeeRate = uint16( BASE_RATE + cycleLocation );
    //copy local variable to state variable
    _feeRate = newFeeRate;
    //anounce new rate
    emit AnnounceFeeRate( newFeeRate );
    return(true);
}
// Solidity 0.5.12
//update rewards tracker when a user withdraws their rewards
function updateSpentRewards( address playerAddress, uint256 etherValue )
    internal
    returns(bool)
{
    int256 updatedPayouts = payoutsToLedger_[playerAddress] + int256 ( SafeMath.mul( etherValue, MAGNITUDE ) );
    require( (updatedPayouts >= payoutsToLedger_[playerAddress]), "ERROR: integer overflow in updateSpentRewards function" );
    payoutsToLedger_[playerAddress] = updatedPayouts;
    return true;
}
// Solidity 0.5.12
//updates rewards tracker. makes sure that player does not receive any rewards accumulated before they purchased/received these tokens
function updateRewardsOnPurchase( address playerAddress, uint256 amountTokens )
    internal
    returns(bool)
{
    int256 updatedPayouts = payoutsToLedger_[playerAddress] + int256 ( SafeMath.mul( _rewardsPerTokenAllTime, amountTokens ) );
    require( (updatedPayouts >= payoutsToLedger_[playerAddress]), "ERROR: integer overflow in updateRewardsOnPurchase function" );
    payoutsToLedger_[playerAddress] = updatedPayouts;    
    return true;
}
// Solidity 0.4.18
// PRIVILEGED FUNCTIONS
// ====================
function releaseBatch() external onlyFounders {
        require(true == vestingStarted);
        require(now > nextPeriod);
        require(periodsPassed < totalPeriods);

        uint tokensToRelease = 0;
        do {
            periodsPassed   = periodsPassed.add(1);
            nextPeriod      = nextPeriod.add(cliffPeriod);
            tokensToRelease = tokensToRelease.add(tokensPerBatch);
        } while (now > nextPeriod);

        // If vesting has finished, just transfer the remaining tokens.
        if (periodsPassed >= totalPeriods) {
            tokensToRelease = tokenContract.balanceOf(this);
            nextPeriod = 0x0;
        }

        tokensRemaining = tokensRemaining.sub(tokensToRelease);
        tokenContract.transfer(foundersWallet, tokensToRelease);

        TokensReleased(tokensToRelease, tokensRemaining, nextPeriod);
    }
// Solidity 0.4.18
/**
 * @dev Constructs the allocator.
 * @param _icoBackend Wallet address that should be owned by the off-chain backend, from which \
 *          \ it mints the tokens for contributions accepted in other currencies.
 * @param _icoManager Allowed to start phase 2.
 * @param _foundersWallet Where the founders' tokens to to after vesting.
 * @param _partnersWallet A wallet that distributes tokens to early contributors.
 */
function TokenAllocation(address _icoManager,
                             address _icoBackend,
                             address _foundersWallet,
                             address _partnersWallet,
                             address _emergencyManager
                             ) public {
        require(_icoManager != address(0));
        require(_icoBackend != address(0));
        require(_foundersWallet != address(0));
        require(_partnersWallet != address(0));
        require(_emergencyManager != address(0));

        tokenContract = new Cappasity(address(this));

        icoManager       = _icoManager;
        icoBackend       = _icoBackend;
        foundersWallet   = _foundersWallet;
        partnersWallet   = _partnersWallet;
        emergencyManager = _emergencyManager;
    }
// Solidity 0.4.18
/**
 * @dev Issues the rewards for founders and early contributors. 18% and 12% of the total token supply by the end
 *   of the crowdsale, respectively, including all the token bonuses on early contributions. Can only be
 *   called after the end of the crowdsale phase, ends the current phase.
 */
function rewardFoundersAndPartners() external onlyManager onlyValidPhase onlyUnpaused {
        uint tokensDuringThisPhase;
        if (crowdsalePhase == CrowdsalePhase.PhaseOne) {
            tokensDuringThisPhase = totalTokenSupply;
        } else {
            tokensDuringThisPhase = totalTokenSupply - tokensDuringPhaseOne;
        }

        // Total tokens sold is 70% of the overall supply, founders' share is 18%, early contributors' is 12%
        // So to obtain those from tokens sold, multiply them by 0.18 / 0.7 and 0.12 / 0.7 respectively.
        uint tokensForFounders = tokensDuringThisPhase.mul(257).div(1000); // 0.257 of 0.7 is 0.18 of 1
        uint tokensForPartners = tokensDuringThisPhase.mul(171).div(1000); // 0.171 of 0.7 is 0.12 of 1

        tokenContract.mint(partnersWallet, tokensForPartners);

        if (crowdsalePhase == CrowdsalePhase.PhaseOne) {
            vestingWallet = new VestingWallet(foundersWallet, address(tokenContract));
            tokenContract.mint(address(vestingWallet), tokensForFounders);
            FoundersAndPartnersTokensIssued(address(vestingWallet), tokensForFounders,
                                            partnersWallet,         tokensForPartners);

            // Store the total sum collected during phase one for calculations in phase two.
            centsInPhaseOne = totalCentsGathered;
            tokensDuringPhaseOne = totalTokenSupply;

            // Enable token transfer.
            tokenContract.unfreeze();
            crowdsalePhase = CrowdsalePhase.BetweenPhases;
        } else {
            tokenContract.mint(address(vestingWallet), tokensForFounders);
            vestingWallet.launchVesting();

            FoundersAndPartnersTokensIssued(address(vestingWallet), tokensForFounders,
                                            partnersWallet,         tokensForPartners);
            crowdsalePhase = CrowdsalePhase.Finished;
        }

        tokenContract.endMinting();
   }
// Solidity 0.5.12
//adds new tokens to total token supply and gives them to the player
function mint(address playerAddress, uint256 amountTokens)
    internal
{
    require( playerAddress != address(0), "cannot mint tokens for zero address" );
    totalSupply = SafeMath.add( totalSupply, amountTokens );
    //updates rewards tracker. makes sure that player does not receive any rewards accumulated before they purchased these tokens
    updateRewardsOnPurchase( playerAddress, amountTokens );
    //give tokens to player. performed last to prevent re-entrancy attacks
    tokenBalanceLedger_[playerAddress] = SafeMath.add( tokenBalanceLedger_[playerAddress] , amountTokens );
    //event conforms to ERC-20 standard
    emit Transfer(address(0), playerAddress, amountTokens);
}
// Solidity 0.4.18
/**
 * @dev Advance the bonus phase to next tier when appropriate, do nothing otherwise.
 */
function advanceBonusPhase() internal onlyValidPhase {
        if (crowdsalePhase == CrowdsalePhase.PhaseOne) {
            if (bonusPhase == BonusPhase.TenPercent) {
                bonusPhase = BonusPhase.FivePercent;
            } else if (bonusPhase == BonusPhase.FivePercent) {
                bonusPhase = BonusPhase.None;
            }
        } else if (bonusPhase == BonusPhase.TenPercent) {
            bonusPhase = BonusPhase.None;
        }
    }
// Solidity 0.8.10
//Make sure you add the 9 zeros at the end!!!
function update_tiers(uint256 t1_size,uint256 t1_percent,uint256 t2_size,uint256 t2_percent,uint256 
    t3_size,uint256 t3_percent,uint256 t4_size,uint256 t4_percent,uint256 t5_size,uint256 t5_percent)external onlyOwner(){

    tier1_size = t1_size;
    tier1_amount = t1_percent;
    tier2_size = t2_size;
    tier2_amount = t2_percent;
    tier3_size = t3_size;
    tier3_amount = t3_percent;
    tier4_size = t4_size;
    tier4_amount = t4_percent;
    tier5_size = t5_size;
    tier5_amount = t5_percent;
    }
// Solidity 0.8.1
/**
 * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
 * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
 * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
 */
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
        require(index < balanceOf(owner), 'ERC721A: owner index out of bounds');
        uint256 numMintedSoFar = totalSupply();
        uint256 tokenIdsIdx = 0;
        address currOwnershipAddr = address(0);
        for (uint256 i = 0; i < numMintedSoFar; i++) {
            TokenOwnership memory ownership = _ownerships[i];
            if (ownership.addr != address(0)) {
                currOwnershipAddr = ownership.addr;
            }
            if (currOwnershipAddr == owner) {
                if (tokenIdsIdx == index) {
                    return i;
                }
                tokenIdsIdx++;
            }
        }
        revert('ERC721A: unable to get token of owner by index');
    }
// Solidity 0.5.12
//update rewards tracker. makes sure that player can still withdraw rewards that accumulated while they were holding their sold/transferred tokens
function updateRewardsOnSale( address playerAddress, uint256 amountTokens )
    internal
    returns(bool)
{
    int256 updatedPayouts = payoutsToLedger_[playerAddress] - int256 ( SafeMath.mul( _rewardsPerTokenAllTime, amountTokens ) );
    require( (updatedPayouts <= payoutsToLedger_[playerAddress]), "ERROR: integer underflow in updateRewardsOnSale function" );
    payoutsToLedger_[playerAddress] = updatedPayouts;
    return true;
}
// Solidity 0.5.12
//destroys sold tokens (removes sold tokens from total token supply) and subtracts them from player balance
function burn(address playerAddress, uint256 amountTokens)
    internal
{
    require( playerAddress != address(0), "cannot burn tokens for zero address" );
    require( amountTokens <= tokenBalanceLedger_[ playerAddress ], "insufficient funds available" );
    //subtract tokens from player balance. performed first to prevent possibility of re-entrancy attacks
    tokenBalanceLedger_[playerAddress] = SafeMath.sub( tokenBalanceLedger_[playerAddress], amountTokens );
    //remove tokens from total supply
    totalSupply = SafeMath.sub( totalSupply, amountTokens );
    //update rewards tracker. makes sure that player can still withdraw rewards that accumulated while they were holding their sold tokens
    updateRewardsOnSale( playerAddress, amountTokens );
    //event conforms to ERC-20 standard
    emit Transfer(playerAddress, address(0), amountTokens);
  }
// Solidity 0.5.12
//sells desired amount of tokens for ether
function sell(uint256 amountTokens)
    internal
    returns (bool)
{
    require( amountTokens <= tokenBalanceLedger_[ msg.sender ], "insufficient funds available" );
    //calculates fee and net value to send to seller
    uint256 etherValue = tokensToEther( amountTokens );
    uint[2] memory feeAndValue = valueAfterFee( etherValue );
    //destroys sold tokens (removes sold tokens from total token supply) and subtracts them from player balance
    //also updates reward tracker (payoutsToLedger_) for player address
    burn(msg.sender, amountTokens);
    // sends rewards to partner contract, to be distributed to its holders
    address payable buddy = partnerAddress_;
    ( bool success, bytes memory returnData ) = buddy.call.value( feeAndValue[0] )("");
    require( success, "failed to send funds to partner contract (not enough gas provided?)" );
    //sends ether to seller
    //NOTE: occurs last to avoid re-entrancy attacks
    msg.sender.transfer( feeAndValue[1] );
    return true;
}
// Solidity 0.5.12
//takes in amount and returns fee to pay on it and the value after the fee
//classified as view since needs to access state (to pull current fee rate) but not write to it
function valueAfterFee( uint amount )
    internal
    view
    returns (uint[2] memory outArray_ )
{
    outArray_[0] = SafeMath.div( SafeMath.mul(amount, _feeRate), 65536 ); //fee
    outArray_[1] = SafeMath.sub( amount , outArray_[0] ); //value after fee
    return outArray_;
}
// Solidity 0.5.12
//returns purchased number of tokens based on linear bonding curve with fee
//it's the quadratic formula stupid!
function etherToTokens(uint256 etherValue)
    internal
    view
    returns(uint256)
{
    uint256 tokenPriceInitial = TOKEN_PRICE_INITIAL * 1e18;
    uint256 _tokensReceived = 
     (
        (
            // avoids underflow
            SafeMath.sub(
                ( sqrt( 
                        ( tokenPriceInitial**2 ) +
                        ( 2 * ( TOKEN_PRICE_INCREMENT * 1e18 ) * ( etherValue * 1e18 ) ) +
                        ( ( ( TOKEN_PRICE_INCREMENT ) ** 2 ) * ( totalSupply ** 2 ) ) +
                        ( 2 * ( TOKEN_PRICE_INCREMENT ) * tokenPriceInitial * totalSupply )
                    )
                ), tokenPriceInitial )
        ) / ( TOKEN_PRICE_INCREMENT )
    ) - ( totalSupply );
  
    return _tokensReceived;
}
// Solidity 0.5.12
//returns sell value of tokens based on linear bonding curve with fee
//~inverse of etherToTokens, but with rounding down to ensure contract is always more than solvent
function tokensToEther(uint256 inputTokens)
    internal
    view
    returns(uint256)
{
    uint256 tokens = ( inputTokens + 1e18 );
    uint256 functionTotalSupply = ( totalSupply + 1e18 );
    uint256 etherReceived = (
        // avoids underflow
        SafeMath.sub(
            ( (
                ( TOKEN_PRICE_INITIAL + ( TOKEN_PRICE_INCREMENT * ( functionTotalSupply / 1e18 ) ) )
               - TOKEN_PRICE_INCREMENT )
            * ( tokens - 1e18 ) ),
            ( TOKEN_PRICE_INCREMENT * ( ( tokens ** 2 - tokens ) / 1e18 ) ) / 2 )
        / 1e18 );
    return etherReceived;
}
// Solidity 0.8.6
/**
 * @notice Used for calculating the option price (the premium) and using
 * the swap router (if needed) to convert the tokens with which the user
 * pays the premium into the token in which the pool is denominated.
 * @param period The option period
 * @param amount The option size
 * @param strike The option strike
 * @param total The total premium
 * @param baseTotal The part of the premium that
 * is distributed among the liquidity providers
 * @param settlementFee The part of the premium that
 * is distributed among the HEGIC staking participants
 **/
function getOptionPrice(
        IHegicPool pool,
        uint256 period,
        uint256 amount,
        uint256 strike,
        address[] calldata swappath
    )
        public
        view
        returns (
            uint256 total,
            uint256 baseTotal,
            uint256 settlementFee,
            uint256 premium
        )
    {
        (uint256 _baseTotal, uint256 baseSettlementFee, uint256 basePremium) =
            getBaseOptionCost(pool, period, amount, strike);
        if (swappath.length > 1)
            total = exchange.getAmountsIn(_baseTotal, swappath)[0];
        else total = _baseTotal;

        baseTotal = _baseTotal;
        settlementFee = (total * baseSettlementFee) / baseTotal;
        premium = (total * basePremium) / baseTotal;
    }
// Solidity 0.8.6
/**
 * @notice Used for calculating the option price (the premium)
 * in the token in which the pool is denominated.
 * @param period The option period
 * @param amount The option size
 * @param strike The option strike
 **/
function getBaseOptionCost(
        IHegicPool pool,
        uint256 period,
        uint256 amount,
        uint256 strike
    )
        public
        view
        returns (
            uint256 total,
            uint256 settlementFee,
            uint256 premium
        )
    {
        (settlementFee, premium) = pool.calculateTotalPremium(
            period,
            amount,
            strike
        );
        total = premium + settlementFee;
    }
// Solidity 0.8.6
/**
 * @notice Used for buying the option contract and converting
 * the buyer's tokens (the total premium) into the token
 * in which the pool is denominated.
 * @param period The option period
 * @param amount The option size
 * @param strike The option strike
 * @param acceptablePrice The highest acceptable price
 **/
function createOption(
        IHegicPool pool,
        uint256 period,
        uint256 amount,
        uint256 strike,
        address[] calldata swappath,
        uint256 acceptablePrice
    ) external payable {
        address buyer = _msgSender();
        (uint256 optionPrice, uint256 rawOptionPrice, , ) =
            getOptionPrice(pool, period, amount, strike, swappath);
        require(
            optionPrice <= acceptablePrice,
            "Facade Error: The option price is too high"
        );
        IERC20 paymentToken = IERC20(swappath[0]);
        paymentToken.safeTransferFrom(buyer, address(this), optionPrice);
        if (swappath.length > 1) {
            if (
                paymentToken.allowance(address(this), address(exchange)) <
                optionPrice
            ) {
                paymentToken.safeApprove(address(exchange), 0);
                paymentToken.safeApprove(address(exchange), type(uint256).max);
            }

            exchange.swapTokensForExactTokens(
                rawOptionPrice,
                optionPrice,
                swappath,
                address(this),
                block.timestamp
            );
        }
        pool.sellOption(buyer, period, amount, strike);
    }
// Solidity 0.4.24
/**
 * @dev Burns tokens from a specific address.
 * To burn the tokens the caller needs to provide a signature
 * proving that the caller is authorized by the token owner to do so.
 * @param db Token storage to operate on.
 * @param from The address holding tokens.
 * @param amount The amount of tokens to burn.
 * @param h Hash which the token owner signed.
 * @param v Signature component.
 * @param r Signature component.
 * @param s Sigature component.
 */
function burn(
        TokenStorage db,
        address from,
        uint amount,
        bytes32 h,
        uint8 v,
        bytes32 r,
        bytes32 s
    )
        external
        returns (bool)
    {
        require(
            ecrecover(h, v, r, s) == from,
            "signature/hash does not match"
        );
        return burn(db, from, amount);
    }