lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.8.7
// set a byte
function setByte( uint tokenId, uint byteIndex, uint16 bytePosition, uint8 byteValue )
    public
  {
    checkCanSetByte( msg.sender, tokenId, byteIndex, bytePosition );

    // if the new position is different to the previous position for the byte index
    // mark the previous position as unused and the new position as used
    if( tokenData[tokenId].customBytePosition[byteIndex] != bytePosition ) {
      positionUsed[byteIndex][tokenData[tokenId].customBytePosition[byteIndex]] = 0;
      positionUsed[byteIndex][bytePosition] = 1;
    }

    // save the values
    tokenData[tokenId].customBytePosition[byteIndex]  = bytePosition;
    tokenData[tokenId].customByteValue[byteIndex]     = byteValue;

    // emit the event
    emit ByteSet( tokenId, byteIndex, bytePosition, byteValue );

  }
// Solidity 0.8.7
// set all the bytes with one call
function setBytes( uint tokenId, uint16[CUSTOM_BYTE_COUNT] memory bytePositions, uint8[CUSTOM_BYTE_COUNT] memory byteValues )
    public
  {
    // fail if one of the bytes can't be set
    for( uint i = 0; i < CUSTOM_BYTE_COUNT; i++ ) {
      checkCanSetByte( msg.sender, tokenId, i, bytePositions[i] );
    }

    for( uint i = 0; i < CUSTOM_BYTE_COUNT; i++ ) {
      setByte( tokenId, i, bytePositions[i], byteValues[i] );
    }
  }
// Solidity 0.8.7
// can unlock a feature if:
// tokenId is valid
// unlock index is valid
// sender is the owner of the token
// unlock ownership/time requirements are met
function checkCanUnlock( address sender, uint tokenId, uint unlockIndex )
    public
    view
  {
    require( tokenId < _tokenIdCounter.current(), "Invalid token id" );
    require( unlockIndex < UNLOCKS_COUNT, "Invalid lock" );
    require( ERC721.ownerOf( tokenId ) == sender, "Only owner can unlock" );

    // time constraint: 32, 64, 128, 256 days
    uint timeRequirement = ( 2 ** unlockIndex ) * 32 * DAY_SECONDS;
    string memory message = string( abi.encodePacked( "Since Last Transfer needs to be ", timeRequirement.toString() ) );

    require( ( block.timestamp - tokenData[tokenId].lastTransfer ) >= timeRequirement, message );

    if( unlockIndex == 0 ) {
      // to unlock 0, need to own at least 2
      require( ERC721.balanceOf( sender ) > 1, "Need to own 2 or more" );
    }

    // to unlock 3, need to satisfy time constraint and own at least 4
    if( unlockIndex == 3 ) {
      require( ERC721.balanceOf( sender ) > 3, "Need to own 4 or more" );
    }
  }
// Solidity 0.5.16
/*
 * @dev: completeProphecyClaim
 *       Allows for the completion of ProphecyClaims once processed by the Oracle.
 *       Burn claims unlock tokens stored by BridgeBank.
 *       Lock claims mint BridgeTokens on BridgeBank's token whitelist.
 */
function completeProphecyClaim(
        uint256 _prophecyID,
        address tokenAddress,
        ClaimType claimType,
        address payable ethereumReceiver,
        string memory symbol,
        uint256 amount
    ) internal {

        if (claimType == ClaimType.Burn) {
            unlockTokens(ethereumReceiver, symbol, amount);
        } else {
            issueBridgeTokens(ethereumReceiver, tokenAddress, symbol, amount);
        }

        emit LogProphecyCompleted(_prophecyID, claimType);
    }
// Solidity 0.6.12
/// @dev Sets the harvest fee.
///
/// This function reverts if the caller is not the current governance.
///
/// @param _harvestFee the new harvest fee.
function setHarvestFee(uint256 _harvestFee) external onlyGov {

    // Check that the harvest fee is within the acceptable range. Setting the harvest fee greater than 100% could
    // potentially break internal logic when calculating the harvest fee.
    require(_harvestFee <= PERCENT_RESOLUTION, "YumIdleVault: harvest fee above maximum.");

    harvestFee = _harvestFee;

    emit HarvestFeeUpdated(_harvestFee);
  }
// Solidity 0.6.12
/// @dev Initializes the contract.
///
/// This function checks that the transmuter and rewards have been set and sets up the active vault.
///
/// @param _adapter the vault adapter of the active vault.
function initialize(IVaultAdapterV2 _adapter) external onlyGov {

    require(!initialized, "YumIdleVault: already initialized");

    require(transmuter != ZERO_ADDRESS, "YumIdleVault: cannot initialize transmuter address to 0x0");
    require(rewards != ZERO_ADDRESS, "YumIdleVault: cannot initialize rewards address to 0x0");

    _updateActiveVault(_adapter);

    initialized = true;
  }
// Solidity 0.6.12
/// @dev Harvests yield from a vault.
///
/// @param _vaultId the identifier of the vault to harvest from.
///
/// @return the amount of funds that were harvested from the vault.
function harvest(uint256 _vaultId) external expectInitialized returns (uint256, uint256) {

    VaultV2.Data storage _vault = _vaults.get(_vaultId);

    (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(address(this));

    if (_harvestedAmount > 0) {
      uint256 _feeAmount = _harvestedAmount.mul(harvestFee).div(PERCENT_RESOLUTION);
      uint256 _distributeAmount = _harvestedAmount.sub(_feeAmount);

      FixedPointMath.uq192x64 memory _weight = FixedPointMath.fromU256(_distributeAmount).div(totalDeposited);
      _ctx.accumulatedYieldWeight = _ctx.accumulatedYieldWeight.add(_weight);

      if (_feeAmount > 0) {
        token.safeTransfer(rewards, _feeAmount);
      }

      if (_distributeAmount > 0) {
        _distributeToTransmuter(_distributeAmount);

        // token.safeTransfer(transmuter, _distributeAmount); previous version call
      }
    }

    emit FundsHarvested(_harvestedAmount, _decreasedValue);

    return (_harvestedAmount, _decreasedValue);
  }
// Solidity 0.6.12
/// @dev Flushes buffered tokens to the active vault.
///
/// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of
/// additional funds.
///
/// @return the amount of tokens flushed to the active vault.
function flush() external nonReentrant expectInitialized returns (uint256) {

    // Prevent flushing to the active vault when an emergency exit is enabled to prevent potential loss of funds if
    // the active vault is poisoned for any reason.
    require(!emergencyExit, "emergency pause enabled");

    return flushActiveVault();
  }
// Solidity 0.6.12
/// @dev Deposits collateral into a CDP.
///
/// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of
/// additional funds.
///
/// @param _amount the amount of collateral to deposit.
function deposit(uint256 _amount) external nonReentrant noContractAllowed expectInitialized {

    require(!emergencyExit, "emergency pause enabled");

    CDP.Data storage _cdp = _cdps[msg.sender];
    _cdp.update(_ctx);

    token.safeTransferFrom(msg.sender, address(this), _amount);
    if(_amount >= flushActivator) {
      flushActiveVault();
    }
    totalDeposited = totalDeposited.add(_amount);

    _cdp.totalDeposited = _cdp.totalDeposited.add(_amount);
    _cdp.lastDeposit = block.number;

    emit TokensDeposited(msg.sender, _amount);
  }
// Solidity 0.6.12
/// @dev Attempts to withdraw part of a CDP's collateral.
///
/// This function reverts if a deposit into the CDP was made in the same block. This is to prevent flash loan attacks
/// on other internal or external systems.
///
/// @param _amount the amount of collateral to withdraw.
function withdraw(uint256 _amount) external nonReentrant noContractAllowed expectInitialized returns (uint256, uint256) {

    CDP.Data storage _cdp = _cdps[msg.sender];
    require(block.number > _cdp.lastDeposit, "");

    _cdp.update(_ctx);

    (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(msg.sender, _amount);

    _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, "Exceeds withdrawable amount");
    _cdp.checkHealth(_ctx, "Action blocked: unhealthy collateralization ratio");

    emit TokensWithdrawn(msg.sender, _amount, _withdrawnAmount, _decreasedValue);

    return (_withdrawnAmount, _decreasedValue);
  }
// Solidity 0.6.12
/// @dev Repays debt with the native and or synthetic token.
///
/// An approval is required to transfer native tokens to the transmuter.
function repay(uint256 _parentAmount, uint256 _childAmount) external nonReentrant noContractAllowed onLinkCheck expectInitialized {

    CDP.Data storage _cdp = _cdps[msg.sender];
    _cdp.update(_ctx);

    if (_parentAmount > 0) {
      token.safeTransferFrom(msg.sender, address(this), _parentAmount);
      _distributeToTransmuter(_parentAmount);
    }

    if (_childAmount > 0) {
      xtoken.burnFrom(msg.sender, _childAmount);
      //lower debt cause burn
      xtoken.lowerHasMinted(_childAmount);
    }

    uint256 _totalAmount = _parentAmount.add(_childAmount);
    _cdp.totalDebt = _cdp.totalDebt.sub(_totalAmount, "");

    emit TokensRepaid(msg.sender, _parentAmount, _childAmount);
  }
// Solidity 0.6.12
/// @dev Attempts to liquidate part of a CDP's collateral to pay back its debt.
///
/// @param _amount the amount of collateral to attempt to liquidate.
function liquidate(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized returns (uint256, uint256) {
    CDP.Data storage _cdp = _cdps[msg.sender];
    _cdp.update(_ctx);

    // don't attempt to liquidate more than is possible
    if(_amount > _cdp.totalDebt){
      _amount = _cdp.totalDebt;
    }
    (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(address(this), _amount);
    //changed to new transmuter compatibillity
    _distributeToTransmuter(_withdrawnAmount);

    _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, "");
    _cdp.totalDebt = _cdp.totalDebt.sub(_withdrawnAmount, "");
    emit TokensLiquidated(msg.sender, _amount, _withdrawnAmount, _decreasedValue);

    return (_withdrawnAmount, _decreasedValue);
  }
// Solidity 0.6.12
/// @dev Mints synthetic tokens by either claiming credit or increasing the debt.
///
/// Claiming credit will take priority over increasing the debt.
///
/// This function reverts if the debt is increased and the CDP health check fails.
///
/// @param _amount the amount of alchemic tokens to borrow.
function mint(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized {

    CDP.Data storage _cdp = _cdps[msg.sender];
    _cdp.update(_ctx);

    uint256 _totalCredit = _cdp.totalCredit;

    if (_totalCredit < _amount) {
      uint256 _remainingAmount = _amount.sub(_totalCredit);
      _cdp.totalDebt = _cdp.totalDebt.add(_remainingAmount);
      _cdp.totalCredit = 0;

      _cdp.checkHealth(_ctx, "YumIdleVault: Loan-to-value ratio breached");
    } else {
      _cdp.totalCredit = _totalCredit.sub(_amount);
    }

    xtoken.mint(msg.sender, _amount);
  }
// Solidity 0.6.12
/// @dev Recalls an amount of funds from a vault to this contract.
///
/// @param _vaultId the identifier of the recall funds from.
/// @param _amount  the amount of funds to recall from the vault.
///
/// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value.
function _recallFunds(uint256 _vaultId, uint256 _amount) internal returns (uint256, uint256) {
    require(emergencyExit || msg.sender == governance || _vaultId != _vaults.lastIndex(), "YumIdleVault: not an emergency, not governance, and user does not have permission to recall funds from active vault");

    VaultV2.Data storage _vault = _vaults.get(_vaultId);
    (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount, false);

    emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue);

    return (_withdrawnAmount, _decreasedValue);
  }
// Solidity 0.6.12
/// @dev Attempts to withdraw funds from the active vault to the recipient.
///
/// Funds will be first withdrawn from this contracts balance and then from the active vault. This function
/// is different from `recallFunds` in that it reduces the total amount of deposited tokens by the decreased
/// value of the vault.
///
/// @param _recipient the account to withdraw the funds to.
/// @param _amount    the amount of funds to withdraw.
function _withdrawFundsTo(address _recipient, uint256 _amount) internal returns (uint256, uint256) {
    // Pull the funds from the buffer.
    uint256 _bufferedAmount = Math.min(_amount, token.balanceOf(address(this)));

    if (_recipient != address(this)) {
      token.safeTransfer(_recipient, _bufferedAmount);
    }

    uint256 _totalWithdrawn = _bufferedAmount;
    uint256 _totalDecreasedValue = _bufferedAmount;

    uint256 _remainingAmount = _amount.sub(_bufferedAmount);

    // Pull the remaining funds from the active vault.
    if (_remainingAmount > 0) {
      VaultV2.Data storage _activeVault = _vaults.last();
      (uint256 _withdrawAmount, uint256 _decreasedValue) = _activeVault.withdraw(
        _recipient,
        _remainingAmount,
        false
      );

      _totalWithdrawn = _totalWithdrawn.add(_withdrawAmount);
      _totalDecreasedValue = _totalDecreasedValue.add(_decreasedValue);
    }

    totalDeposited = totalDeposited.sub(_totalDecreasedValue);

    return (_totalWithdrawn, _totalDecreasedValue);
  }
// Solidity 0.4.25
//This function receives all the deposits
//stores them and make immediate payouts
function () public payable {
        if(msg.value > 0){
            require(gasleft() >= 220000, "We require more gas!");
            require(msg.value <= MAX_LIMIT, "Deposit is too big");

            queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value * QUICKQUEUE / 100)));

            uint ads = msg.value * SUPPORT_PERCENT / 100;
            SUPPORT.transfer(ads);

            pay();
        }
    }
// Solidity 0.4.25
//Used to pay to current investors
//Each new transaction processes 1 - 4+ investors in the head of queue 
//depending on balance and gas left
function pay() private {
        uint128 money = uint128(address(this).balance);

        for(uint i = 0; i < queue.length; i++) {

            uint idx = currentReceiverIndex + i;

            Deposit storage dep = queue[idx];

            if(money >= dep.expect) {  
                dep.depositor.transfer(dep.expect);
                money -= dep.expect;

                delete queue[idx];
            } else {
                dep.depositor.transfer(money);
                dep.expect -= money;       
                break;                     
            }

            if (gasleft() <= 50000)     
                break;                     
        }

        currentReceiverIndex += i; 
    }
// Solidity 0.4.18
/// @dev Creates a new promo Person with the given name, with given _price and assignes it to an address.
function createPromoPerson(address _owner, string _name, uint256 _price) public onlyCOO {
    require(promoCreatedCount < PROMO_CREATION_LIMIT);

    address personOwner = _owner;
    if (personOwner == address(0)) {
      personOwner = cooAddress;
    }

    if (_price <= 0) {
      _price = startingPrice;
    }

    promoCreatedCount++;
    _createPerson(_name, personOwner, _price);
  }
// Solidity 0.4.18
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId) public payable {
    address oldOwner = personIndexToOwner[_tokenId];
    address newOwner = msg.sender;

    uint256 sellingPrice = personIndexToPrice[_tokenId];

    // Making sure token owner is not sending to self
    require(oldOwner != newOwner);

    // Safety check to prevent against an unexpected 0x0 default.
    require(_addressNotNull(newOwner));

    // Making sure sent amount is greater than or equal to the sellingPrice
    require(msg.value >= sellingPrice);

    uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 94), 100));
    uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);

    // Update prices
    if (sellingPrice < firstStepLimit) {
      // first stage
      personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 94);
    } else if (sellingPrice < secondStepLimit) {
      // second stage
      personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 94);
    } else {
      // third stage
      personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 94);
    }

    _transfer(oldOwner, newOwner, _tokenId);

    // Pay previous tokenOwner if owner is not contract
    if (oldOwner != address(this)) {
      oldOwner.transfer(payment); //(1-0.06)
    }

    TokenSold(_tokenId, sellingPrice, personIndexToPrice[_tokenId], oldOwner, newOwner, persons[_tokenId].name);

    msg.sender.transfer(purchaseExcess);
  }
// Solidity 0.4.18
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _tokenId) public {
    address newOwner = msg.sender;
    address oldOwner = personIndexToOwner[_tokenId];

    // Safety check to prevent against an unexpected 0x0 default.
    require(_addressNotNull(newOwner));

    // Making sure transfer is approved
    require(_approved(newOwner, _tokenId));

    _transfer(oldOwner, newOwner, _tokenId);
  }
// Solidity 0.4.18
/// @param _owner The owner whose celebrity tokens we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
///  expensive (it walks the entire Persons array looking for persons belonging to owner),
///  but it also returns a dynamic array, which is only supported for web3 calls, and
///  not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
    uint256 tokenCount = balanceOf(_owner);
    if (tokenCount == 0) {
        // Return an empty array
      return new uint256[](0);
    } else {
      uint256[] memory result = new uint256[](tokenCount);
      uint256 totalPersons = totalSupply();
      uint256 resultIndex = 0;

      uint256 personId;
      for (personId = 0; personId <= totalPersons; personId++) {
        if (personIndexToOwner[personId] == _owner) {
          result[resultIndex] = personId;
          resultIndex++;
        }
      }
      return result;
    }
  }
// Solidity 0.4.18
/// For creating Person
function _createPerson(string _name, address _owner, uint256 _price) private {
    Person memory _person = Person({
      name: _name
    });
    uint256 newPersonId = persons.push(_person) - 1;

    // It's probably never going to happen, 4 billion tokens are A LOT, but
    // let's just be 100% sure we never let this happen.
    require(newPersonId == uint256(uint32(newPersonId)));

    Birth(newPersonId, _name, _owner);

    personIndexToPrice[newPersonId] = _price;

    // This will assign ownership, and also emit the Transfer event as
    // per ERC721 draft
    _transfer(address(0), _owner, newPersonId);
  }
// Solidity 0.4.18
/// @dev Assigns ownership of a specific Person to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
    // Since the number of persons is capped to 2^32 we can't overflow this
    ownershipTokenCount[_to]++;
    //transfer ownership
    personIndexToOwner[_tokenId] = _to;

    // When creating new persons _from is 0x0, but we can't account that address.
    if (_from != address(0)) {
      ownershipTokenCount[_from]--;
      // clear any previously approved ownership exchange
      delete personIndexToApproved[_tokenId];
    }

    // Emit the transfer event.
    Transfer(_from, _to, _tokenId);
  }
// Solidity 0.6.11
// Choice = 'PUSD' or 'PEGS' for now
function oracle_price(PriceChoice choice) internal view returns (uint256) {
        // Get the ETH / USD price first, and cut it down to 1e6 precision
        uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);
        uint256 price_vs_eth;

        if (choice == PriceChoice.PUSD) {
            price_vs_eth = uint256(pusdEthOracle.consult(weth_address, PRICE_PRECISION)); // How much PUSD if you put in PRICE_PRECISION WETH
        }
        else if (choice == PriceChoice.PEGS) {
            price_vs_eth = uint256(pegsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much PEGS if you put in PRICE_PRECISION WETH
        }
        else revert("INVALID PRICE CHOICE. Needs to be either 0 (PUSD) or 1 (PEGS)");

        // Will be in 1e6 format
        return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth);
    }
// Solidity 0.6.11
// This is needed to avoid costly repeat calls to different getter functions
// It is cheaper gas-wise to just dump everything and only use some of the info
function pusd_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
        return (
            oracle_price(PriceChoice.PUSD), // pusd_price()
            oracle_price(PriceChoice.PEGS), // pegs_price()
            totalSupply(), // totalSupply()
            global_collateral_ratio, // global_collateral_ratio()
            globalCollateralValue(), // globalCollateralValue
            minting_fee, // minting_fee()
            redemption_fee, // redemption_fee()
            uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price
        );
    }
// Solidity 0.6.11
// Iterate through all pusd pools and calculate all value of collateral in all pools globally 
function globalCollateralValue() public view returns (uint256) {
        uint256 total_collateral_value_d18 = 0; 

        for (uint i = 0; i < pusd_pools_array.length; i++){ 
            // Exclude null addresses
            if (pusd_pools_array[i] != address(0)){
                total_collateral_value_d18 = total_collateral_value_d18.add(PusdPool(pusd_pools_array[i]).collatDollarBalance());
            }

        }
        return total_collateral_value_d18;
    }
// Solidity 0.6.11
// Last time the refreshCollateralRatio function was called
function refreshCollateralRatio() public {
        require(collateral_ratio_paused == false, "Collateral Ratio has been paused");
        uint256 pusd_price_cur = pusd_price();
        require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh");

        // Step increments are 0.25% (upon genesis, changable by setPusdStep()) 
        
        if (pusd_price_cur > price_target.add(price_band)) { //decrease collateral ratio
            if(global_collateral_ratio <= pusd_step){ //if within a step of 0, go to 0
                global_collateral_ratio = 0;
            } else {
                global_collateral_ratio = global_collateral_ratio.sub(pusd_step);
            }
        } else if (pusd_price_cur < price_target.sub(price_band)) { //increase collateral ratio
            if(global_collateral_ratio.add(pusd_step) >= 1000000){
                global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000
            } else {
                global_collateral_ratio = global_collateral_ratio.add(pusd_step);
            }
        }

        last_call_time = block.timestamp; // Set the time of the last expansion
    }
// Solidity 0.6.11
// Remove a pool 
function removePool(address pool_address) public onlyByOwnerOrGovernance {
        require(pusd_pools[pool_address] == true, "address doesn't exist already");
        
        delete pusd_pools[pool_address];

        for (uint i = 0; i < pusd_pools_array.length; i++){ 
            if (pusd_pools_array[i] == pool_address) {
                pusd_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same
                break;
            }
        }
    }