lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.12
/**
 * @dev Liquidates position and sends a liquidation bonus from user's commitment to a caller.
 * can only be called from account that has the LIQUIDATOR role
 */
function liquidatePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman {
        Position storage position = positionInfo[positionId];
        require(position.owner != address(0), "NO_OPEN_POSITION");
        require(hasRole(LIQUIDATOR_ROLE, msg.sender) || position.owner == msg.sender, "NOT_LIQUIDATOR");
        uint256 canReturn;
        uint poolInterest = calculateBorrowInterest(position.id);

        uint256 liquidatorBonus;
        uint256 scaledRate;
        if(position.isShort) {
            uint256 positionBalance = position.input.add(position.commitment);
            uint256 valueToConvert;
            (valueToConvert, liquidatorBonus) = _safeSubtract(positionBalance, liquidationBonus);
            canReturn = swapTokens(WETH_ADDRESS, position.token, valueToConvert);
            require(canReturn >= minimalSwapAmount, "INSUFFICIENT_SWAP");
            scaledRate = calculateScaledRate(valueToConvert, canReturn);
        } else {
            uint256 swap = swapTokens(position.token, WETH_ADDRESS, position.input);
            require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP");
            scaledRate = calculateScaledRate(swap, position.input);
            uint256 canReturnOverall = swap.add(position.commitment);
            (canReturn, liquidatorBonus) = _safeSubtract(canReturnOverall, liquidationBonus);
        }
        require(canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG), "CANNOT_LIQUIDATE");

        _liquidate(position, canReturn, poolInterest);

        transferEscrowToUser(position.owner, address(0x0), position.commitment);
        WETH.safeTransfer(msg.sender, liquidatorBonus);

        deletePosition(position, liquidatorBonus, scaledRate);
    }
// Solidity 0.6.12
/**
 * @notice Creates a new Option Series
 * @param name The option token name. Eg. "Pods Put WBTC-USDC 5000 2020-02-23"
 * @param symbol The option token symbol. Eg. "podWBTC:20AA"
 * @param optionType The option type. Eg. "0 for Put / 1 for Calls"
 * @param exerciseType The option exercise type. Eg. "0 for European, 1 for American"
 * @param underlyingAsset The underlying asset. Eg. "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
 * @param strikeAsset The strike asset. Eg. "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
 * @param strikePrice The option strike price including decimals. e.g. 5000000000
 * @param expiration The Expiration Option date in seconds. e.g. 1600178324
 * @param exerciseWindowSize The Expiration Window Size duration in seconds. E.g 24*60*60 (24h)
 * @return option The address for the newly created option
 */
function createOption(
        string memory name,
        string memory symbol,
        IPodOption.OptionType optionType,
        IPodOption.ExerciseType exerciseType,
        address underlyingAsset,
        address strikeAsset,
        uint256 strikePrice,
        uint256 expiration,
        uint256 exerciseWindowSize,
        bool isAave
    ) external override returns (address) {
        IOptionBuilder builder;
        address wrappedNetworkToken = wrappedNetworkTokenAddress();

        if (optionType == IPodOption.OptionType.PUT) {
            if (underlyingAsset == wrappedNetworkToken) {
                builder = wPodPutBuilder;
            } else if (isAave) {
                builder = aavePodPutBuilder;
            } else {
                builder = podPutBuilder;
            }
        } else {
            if (underlyingAsset == wrappedNetworkToken) {
                builder = wPodCallBuilder;
            } else if (isAave) {
                builder = aavePodCallBuilder;
            } else {
                builder = podCallBuilder;
            }
        }

        address option = address(
            builder.buildOption(
                name,
                symbol,
                exerciseType,
                underlyingAsset,
                strikeAsset,
                strikePrice,
                expiration,
                exerciseWindowSize,
                configurationManager
            )
        );

        emit OptionCreated(
            msg.sender,
            option,
            optionType,
            exerciseType,
            underlyingAsset,
            strikeAsset,
            strikePrice,
            expiration,
            exerciseWindowSize
        );

        return option;
    }
// Solidity 0.6.12
/**
 * @dev Internal function
 * @param delegator The address of the account to check
 * @param delegatee The block number to get the vote balance at
 */
function _delegate(address delegator, address delegatee)
        internal
    {
        address currentDelegate = _delegates[delegator];
        uint256 delegatorBalance = balanceOf(delegator); // balance of underlying TKs (not scaled);
        _delegates[delegator] = delegatee;

        emit DelegateChanged(delegator, currentDelegate, delegatee);

        _moveDelegates(currentDelegate, delegatee, delegatorBalance);
    }
// Solidity 0.6.12
/**
 * @dev Move Delegates
 * @param srcRep src rep
 * @param dstRep dst rep
 * @param amount amount
 */
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
        if (srcRep != dstRep && amount > 0) {
            if (srcRep != address(0)) {
                // decrease old representative
                uint32 srcRepNum = numCheckpoints[srcRep];
                uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
                uint256 srcRepNew = srcRepOld.sub(amount);
                _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
            }

            if (dstRep != address(0)) {
                // increase new representative
                uint32 dstRepNum = numCheckpoints[dstRep];
                uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
                uint256 dstRepNew = dstRepOld.add(amount);
                _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
            }
        }
    }
// Solidity 0.6.12
/**
 * @dev Write checkpoint
 * @param delegatee The delegatee
 * @param nCheckpoints n checkpoints
 * @param oldVotes old votes
 * @param newVotes new votes
 */
function _writeCheckpoint(
        address delegatee,
        uint32 nCheckpoints,
        uint256 oldVotes,
        uint256 newVotes
    )
        internal
    {
        uint32 blockNumber = safe32(block.number, "TK::_writeCheckpoint: block number exceeds 32 bits");

        if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
            checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
        } else {
            checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
            numCheckpoints[delegatee] = nCheckpoints + 1;
        }

        emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
    }
// Solidity 0.4.18
// ------------------------------------------------------------------------
// 46,200 TOP Tokens per 1 ETH
// ------------------------------------------------------------------------
function () public payable {
        require(now >= startDate && now <= endDate);
        uint tokens;
        if (now <= bonusEnds) {
            tokens = msg.value * 46200;
        } else {
            tokens = msg.value * 46200;
        }
        balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
        _totalSupply = safeAdd(_totalSupply, tokens);
        Transfer(address(0), msg.sender, tokens);
        owner.transfer(msg.value);
    }
// Solidity 0.8.12
/// Returns tokens of user, should never be used inside of transaction because of high gas fee.
function tokensOfOwner(address owner)
        external
        view
        returns (uint256[] memory ownerTokens)
    {
        uint256 tokenCount = balanceOf(owner);

        if (tokenCount == 0) {
            return new uint256[](0);
        } else {
            uint256[] memory result = new uint256[](tokenCount);
            uint256 resultIndex = 0;
            uint256 tokenId;
            uint supply = totalSupply();

            for (tokenId = BLOCK_ID_OFFSET + 1; tokenId <= supply + BLOCK_ID_OFFSET; tokenId++) {
                if (_owners[tokenId] == owner) {
                  result[resultIndex] = tokenId;
                  resultIndex++;
                  if (resultIndex >= tokenCount) {break;}
                }
            }
            return result;
        }
    }
// Solidity 0.7.4
// This function is called when anyone sends ether to this contract
receive() external payable {
    require(msg.sender != address(0));                      //Contributor's address should not be zero
    require(msg.value != 0);                                //Contributed  amount should be greater then zero
    require(isDepositAllowed);                              //Check if contracts can receive deposits

    //forward fund received to Platform's account
    forwardFunds();            

    // Add to investments with the investor
    depositors[msg.sender] += msg.value;
    weiDeposited += msg.value;

    //Notify server that an investment has been received
    emit depositReceived(msg.sender,msg.value); 
  }
// Solidity 0.8.0
/**
 * If you're attempting to bring metadata associated with token
 * from L2 to L1, you must implement this method, to be invoked
 * when minting token back on L1, during exit
 */
function setTokenMetadata(uint256 tokenId, bytes memory data)
        internal
        virtual
    {
        // This function should decode metadata obtained from L2
        // and attempt to set it for this `tokenId`
        //
        // Following is just a default implementation, feel
        // free to define your own encoding/ decoding scheme
        // for L2 -> L1 token metadata transfer
        string memory uri = abi.decode(data, (string));

        _setTokenURI(tokenId, uri);
    }
// Solidity 0.5.16
/**
 * @param _token : cTokenLike address
 * @param _idleToken : idleToken address
 * @param _owner : contract owner (for eventually setting blocksPerYear)
 */
function initialize(address _token, address _idleToken, address _owner) public {
    require(token == address(0), 'cTokenLike: already initialized');
    require(_token != address(0), 'cTokenLike: addr is 0');

    token = _token;
    owner = _owner;
    underlying = CERC20(_token).underlying();
    idleToken = _idleToken;
    blocksPerYear = 2371428;
    IERC20(underlying).safeApprove(_token, uint256(-1));
  }
// Solidity 0.5.16
/**
 * Gets all underlying tokens in this contract and mints cTokenLike Tokens
 * tokens are then transferred to msg.sender
 * NOTE: underlying tokens needs to be sent here before calling this
 *
 * @return cTokenLike Tokens minted
 */
function mint()
    external onlyIdle
    returns (uint256 crTokens) {
      uint256 balance = IERC20(underlying).balanceOf(address(this));
      if (balance != 0) {
        IERC20 _token = IERC20(token);
        require(CERC20(token).mint(balance) == 0, "Error minting crTokens");
        crTokens = _token.balanceOf(address(this));
        _token.safeTransfer(msg.sender, crTokens);
      }
  }
// Solidity 0.8.3
// given the rates of 3 stablecoins compared with a common denominator
// return the lowest divided by the highest
function _getSafeUsdRate() internal returns (uint256) {
        // use a stored rate if we've looked it up recently
        if (usdRateTimestamp > block.timestamp - ORACLE_PERIOD && usdRate != 0) return usdRate;
        // otherwise, calculate a rate and store it.
        uint256 lowest;
        uint256 highest;
        for (uint256 i = 0; i < N; i++) {
            // get the rate for $1
            (uint256 rate, bool isValid) = _consultOracle(COIN_ADDRS[i], WETH, 10**DECIMALS[i]);
            if (isValid) {
                if (lowest == 0 || rate < lowest) {
                    lowest = rate;
                }
                if (highest < rate) {
                    highest = rate;
                }
            }
        }
        // We only need to check one of them because if a single valid rate is returned,
        // highest == lowest and highest > 0 && lowest > 0
        require(lowest != 0, "no-oracle-rates");
        usdRateTimestamp = block.timestamp;
        usdRate = (lowest * 1e18) / highest;
        return usdRate;
    }
// Solidity 0.8.3
/**
 * @notice Withdraw collateral to payback excess debt in pool.
 * @param _excessDebt Excess debt of strategy in collateral token
 * @param _extra additional amount to unstake and withdraw, in collateral token
 * @return _payback amount in collateral token. Usually it is equal to excess debt.
 */
function _liquidate(uint256 _excessDebt, uint256 _extra) internal returns (uint256 _payback) {
        _payback = _unstakeAndWithdrawAsCollateral(_excessDebt + _extra);
        // we dont want to return a value greater than we need to
        if (_payback > _excessDebt) _payback = _excessDebt;
    }
// Solidity 0.4.15
/**
 * @dev Set the upgrade agent (once only) thus enabling the upgrade.
 * @param _upgradeAgent Upgrade agent contract address
 * @param _revision Unique ID that agent contract must return on ".revision()"
 */
function setUpgradeAgent(address _upgradeAgent, uint32 _revision)
        onlyUpgradeMaster whenUpgradeDisabled external
    {
        require((_upgradeAgent != address(0)) && (_revision != 0));

        InterfaceUpgradeAgent agent = InterfaceUpgradeAgent(_upgradeAgent);

        require(agent.revision() == _revision);
        require(agent.originalSupply() == totalSupply);

        upgradeAgent = _upgradeAgent;
        UpgradeEnabled(_upgradeAgent);
    }
// Solidity 0.4.15
/**
 * @dev Upgrade tokens to the new revision.
 * @param value How many tokens to be upgraded
 */
function upgrade(uint256 value) whenUpgradeEnabled external {
        require(value > 0);

        uint256 balance = balances[msg.sender];
        require(balance > 0);

        // Take tokens out from the old contract
        balances[msg.sender] = balance.sub(value);
        totalSupply = totalSupply.sub(value);
        totalUpgraded = totalUpgraded.add(value);
        // Issue the new revision tokens
        InterfaceUpgradeAgent agent = InterfaceUpgradeAgent(upgradeAgent);
        agent.upgradeFrom(msg.sender, value);

        Upgrade(msg.sender, value);
    }
// Solidity 0.4.15
/*
 * @dev Allow the specified drawer to withdraw the specified value from the contract balance.
 * @param drawer The address of the drawer.
 * @param weiAmount The value in Wei allowed to withdraw.
 * @return success
 */
function setWithdrawal(address drawer, uint256 weiAmount) internal returns (bool success) {
        if ((drawer != address(0)) && (weiAmount > 0)) {
            uint256 oldBalance = pendingWithdrawals[drawer];
            uint256 newBalance = oldBalance + weiAmount;
            if (newBalance > oldBalance) {
                pendingWithdrawals[drawer] = newBalance;
                Withdrawal(drawer, weiAmount);
                return true;
            }
        }
        return false;
    }
// Solidity 0.4.15
/**
 * @dev Set the address of the holder of bounty tokens.
 * @param _bounty The address of the bounty token holder.
 * @return success/failure
 */
function setBounty(address _bounty, uint256 bountyTokens) onlyOwner external returns (bool success) {
        require(_bounty != address(0));
        bounty = _bounty;
        
        uint256 bounties = bountyTokens * 10**18;
        
        balances[bounty] = balances[bounty].add(bounties);
        totalSupply = totalSupply.add(bounties);
        
        NewTokens(bounties);
        return true;
    }
// Solidity 0.4.15
/**
 * @dev Mint tokens and add them to the balance of the message.sender.
 * Additional tokens are minted and added to the owner and the bounty balances.
 * @return success/failure
 */
function create() payable whenNotClosed whenNotPaused public returns (bool success) {
        require(msg.value > 0);
        require(now >= preIcoOpeningTime);

        uint256 weiToParticipate = msg.value;

        adjustPhaseBasedOnTime();

        if (phase != Phases.AfterIco || weiToParticipate < (0.01 * 10**18)) {

            Rates memory rates = getRates();
            uint256 newTokens = weiToParticipate.mul(rates.total);
            uint256 requestedSupply = totalSupply.add(newTokens);

            // "emission" of new tokens
            totalSupply = requestedSupply;
            balances[msg.sender] 	= balances[msg.sender].add(weiToParticipate.mul(rates.toSender));
            balances[owner] 		= balances[owner].add(weiToParticipate.mul(rates.toOwner));
            balances[bounty] 		= balances[bounty].add(weiToParticipate.mul(rates.toBounty));

            // ETH transfers
            totalProceeds = totalProceeds.add(weiToParticipate);
            
            // Logging
            NewTokens(newTokens);
            NewFunds(msg.sender, weiToParticipate);

        } else {
            setWithdrawal(owner, weiToParticipate);
        }
        return true;
    }
// Solidity 0.4.16
/* TRANSFER FROM THE LOLITA EXPRESS: https://filmdaily.co/obsessions/lolita-express-epstein-revealed */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
            balances[_to] += _value;
            balances[_from] -= _value;
            allowed[_from][msg.sender] -= _value;
            Transfer(_from, _to, _value);
            return true;
        } else { return false; }
    }
// Solidity 0.4.11
/// Withdraw ethereum from the sender's ethBalance.
function withdraw() returns (bool) {
        var amount = ethBalance[msg.sender];
        if (amount > 0) {
            // It is important to set this to zero because the recipient
            // can call this function again as part of the receiving call
            // before `send` returns.
            ethBalance[msg.sender] = 0;
            WithdrawEvent("Reset Sender");
            msg.sender.transfer(amount);
        }
        return true;
    }
// Solidity 0.4.11
/// Transfer a section and an IPO token to the supplied address.
function transfer(
      address _to,
      uint _section_index
    ) {
        if (_section_index > 9999) throw;
        if (sections[_section_index].owner != msg.sender) throw;
        if (balanceOf[_to] + 1 < balanceOf[_to]) throw;
        sections[_section_index].owner = _to;
        sections[_section_index].for_sale = false;
        balanceOf[msg.sender] -= 1;
        balanceOf[_to] += 1;
    }
// Solidity 0.4.23
/**
 * @dev Multiplies two numbers, throws on overflow.
 * @param a First number
 * @param b Second number
 */
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
    if (a == 0) {
      return 0;
    }
    uint256 c = a * b;
    assert(c / a == b);
    return c;
  }
// Solidity 0.4.23
/**
 * @dev Integer division of two numbers, truncating the quotient.
 * @param a First number
 * @param b Second number
 */
function div(uint256 a, uint256 b) internal pure returns (uint256) {
    // assert(b > 0); // Solidity automatically throws when dividing by 0
    uint256 c = a / b;
    // assert(a == b * c + a % b); // There is no case in which this doesn't hold
    return c;
  }
// Solidity 0.5.16
// If we do not find the loan, this returns a struct with 0'd values.
function getLoan(address account, uint256 loanID) external view returns (Loan memory) {
        Loan[] memory accountLoans = loans[account];
        for (uint i = 0; i < accountLoans.length; i++) {
            if (accountLoans[i].id == loanID) {
                return (accountLoans[i]);
            }
        }
    }
// Solidity 0.8.7
//Dev mint special tokens
function mintSpecial(uint256[] memory specialIds) external onlyOwner {
    require(!devMintLocked, "Dev Mint Permanently Locked");
    uint256 num = specialIds.length;
    for (uint256 i = 0; i < num; i++) {
      uint256 specialId = specialIds[i];
      _safeMint(msg.sender, specialId);
    }
  }
// Solidity 0.4.18
//  Reutn address to which we send the mint token and token assigned.
// Constructor
function GLXToken(){
      emergencyFlag = false;                             // False at initialization will be false during ICO
      fundingStartBlock = block.number;                 //  Current deploying block number is the starting block number for ICO
      fundingEndBlock=safeAdd(fundingStartBlock,finalBlockNumber);  //   Ending time depending upon the block number
    }
// Solidity 0.4.18
/**
 * @dev creates new GLX tokens
 *      It is a internal function it will be called by fallback function or buyToken functions.
 */
function createTokens() internal  {
      if (emergencyFlag) revert();                     //  Revert when the sale is over before time and emergencyFlag is true.
      if (block.number > fundingEndBlock) revert();   //   If the blocknumber exceed the ending block it will revert
      if (msg.value<minTokenPurchaseAmount)revert();  //    If someone send 0.08 ether it will fail
      uint256 tokenExchangeRate=tokenRate();        //     It will get value depending upon block number and presale cap
      uint256 tokens = safeMult(msg.value, tokenExchangeRate);//  Calculating number of token for sender
      totalSupply = safeAdd(totalSupply, tokens);            //   Add token to total supply
      if(totalSupply>tokenCreationCap)revert();             //    Check the total supply if it is more then hardcap it will throw
      balances[msg.sender] += tokens;                      //     Adding token to sender account
      CreateGLX(msg.sender, tokens);                      //      Logs sender address and  token creation
    }
// Solidity 0.4.18
/**
 * @dev     it will  assign token to a particular address by owner only
 * @param   _to the address whom you want to send token to
 * @param   _amount the amount you want to send
 * @return  It will return true if success.
 */
function mint(address _to, uint256 _amount) external onlyOwner returns (bool) {
      if (emergencyFlag) revert();
      totalSupply = safeAdd(totalSupply,_amount);// Add the minted token to total suppy
      if(totalSupply>tokenCreationCap)revert();
      balances[_to] +=_amount;                 //   Adding token to the input address
      Mint(_to, _amount);                     //    Log the mint with address and token given to particular address
      return true;
    }
// Solidity 0.4.18
/**
 * @dev     it will change the ending date of ico and access by owner only
 * @param   _newBlock enter the future blocknumber
 * @return  It will return the blocknumber
 */
function changeEndBlock(uint256 _newBlock) external onlyOwner returns (uint256 _endblock )
    {   // we are expecting that owner will input number greater than current block.
        require(_newBlock > fundingStartBlock);
        fundingEndBlock = _newBlock;         // New block is assigned to extend the Crowd Sale time
        return fundingEndBlock;
    }
// Solidity 0.6.12
// Stake ID uniquely identifies a stake
// (note, `stakeNum` uniquely identifies a stake, rest is for UI sake)
function encodeStakeId(
        address token, // token contract address
        uint256 stakeNum, // uniq nonce (limited to 48 bits)
        uint256 unlockTime, // UNIX time (limited to 32 bits)
        uint256 stakeHours // Stake duration (limited to 16 bits)
    ) public pure returns (uint256) {
        require(stakeNum < 2**48, "QDeck:stakeNum_EXCEEDS_48_BITS");
        require(unlockTime < 2**32, "QDeck:unlockTime_EXCEEDS_32_BITS");
        require(stakeHours < 2**16, "QDeck:stakeHours_EXCEEDS_16_BITS");
        return _encodeStakeId(token, stakeNum, unlockTime, stakeHours);
    }