lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.25
/**
 * @notice Update the Synthetix Drawing Rights exchange rate based on other rates already updated.
 */
function updateXDRRate(uint timeSent)
        internal
    {
        uint total = 0;

        for (uint i = 0; i < xdrParticipants.length; i++) {
            total = rates(xdrParticipants[i]).add(total);
        }

        // Set the rate and update time
        _setRate("XDR", total, timeSent);

        // Emit our updated event separate to the others to save
        // moving data around between arrays.
        bytes32[] memory eventCurrencyCode = new bytes32[](1);
        eventCurrencyCode[0] = "XDR";

        uint[] memory eventRate = new uint[](1);
        eventRate[0] = rates("XDR");

        emit RatesUpdated(eventCurrencyCode, eventRate);
    }
// Solidity 0.4.25
/**
 * @notice Retrieve the last update time for a specific currency
 */
function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys)
        public
        view
        returns (uint[])
    {
        uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);

        for (uint i = 0; i < currencyKeys.length; i++) {
            lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]);
        }

        return lastUpdateTimes;
    }
// Solidity 0.4.25
/**
 * @notice ERC223 transferFrom function
 */
function transferFrom(address from, address to, uint value, bytes data)
        public
        optionalProxy
        returns (bool)
    {
        require(from != 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef, "The fee address is not allowed");

        // Skip allowance update in case of infinite allowance
        if (tokenState.allowance(from, messageSender) != uint(-1)) {
            // Reduce the allowance by the amount we're transferring.
            // The safeSub call will handle an insufficient allowance.
            tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
        }

        return super._internalTransfer(from, to, value, data);
    }
// Solidity 0.4.25
/**
 * @notice ERC223 transfer function. Does not conform with the ERC223 spec, as:
 *         - Transaction doesn't revert if the recipient doesn't implement tokenFallback()
 *         - Emits a standard ERC20 event without the bytes data parameter so as not to confuse
 *           tooling such as Etherscan.
 */
function transfer(address to, uint value, bytes data)
        public
        optionalProxy
        returns (bool)
    {
        // Ensure they're not trying to exceed their locked amount
        require(value <= transferableSynthetix(messageSender), "Insufficient balance");

        // Perform the transfer: if there is a problem an exception will be thrown in this call.
        _transfer_byProxy(messageSender, to, value, data);

        return true;
    }
// Solidity 0.4.25
/**
 * @notice Issue synths against the sender's SNX.
 * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0.
 * @param currencyKey The currency you wish to issue synths in, for example sUSD or sAUD
 * @param amount The amount of synths you wish to issue with a base of UNIT
 */
function issueSynths(bytes32 currencyKey, uint amount)
        public
        optionalProxy
        // No need to check if price is stale, as it is checked in issuableSynths.
    {
        require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large");

        // Keep track of the debt they're about to create
        _addToDebtRegister(currencyKey, amount);

        // Create their synths
        synths[currencyKey].issue(messageSender, amount);

        // Store their locked SNX amount to determine their fee % for the period
        _appendAccountIssuanceRecord();
    }
// Solidity 0.4.25
/**
 * @notice Issue the maximum amount of Synths possible against the sender's SNX.
 * @dev Issuance is only allowed if the synthetix price isn't stale.
 * @param currencyKey The currency you wish to issue synths in, for example sUSD or sAUD
 */
function issueMaxSynths(bytes32 currencyKey)
        external
        optionalProxy
    {
        // Figure out the maximum we can issue in that currency
        uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey);

        // Keep track of the debt they're about to create
        _addToDebtRegister(currencyKey, maxIssuable);

        // Create their synths
        synths[currencyKey].issue(messageSender, maxIssuable);

        // Store their locked SNX amount to determine their fee % for the period
        _appendAccountIssuanceRecord();
    }
// Solidity 0.4.25
/**
 * @notice Burn synths to clear issued synths/free SNX.
 * @param currencyKey The currency you're specifying to burn
 * @param amount The amount (in UNIT base) you wish to burn
 * @dev The amount to burn is debased to XDR's
 */
function burnSynths(bytes32 currencyKey, uint amount)
        external
        optionalProxy
        // No need to check for stale rates as effectiveValue checks rates
    {
        // How much debt do they have?
        uint debtToRemove = effectiveValue(currencyKey, amount, "XDR");
        uint existingDebt = debtBalanceOf(messageSender, "XDR");
        
        uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey);

        require(existingDebt > 0, "No debt to forgive");

        // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just
        // clear their debt and leave them be.
        uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove;

        // Remove their debt from the ledger
        _removeFromDebtRegister(amountToRemove, existingDebt);

        uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount;

        // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths).
        synths[currencyKey].burn(messageSender, amountToBurn);

        // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period
        _appendAccountIssuanceRecord();
    }
// Solidity 0.4.25
/**
 * @notice Find the oldest debtEntryIndex for the corresponding closingDebtIndex
 * @param account users account
 * @param closingDebtIndex the last periods debt index on close
 */
function applicableIssuanceData(address account, uint closingDebtIndex)
        external
        view
        returns (uint, uint)
    {
        IssuanceData[FEE_PERIOD_LENGTH] memory issuanceData = accountIssuanceLedger[account];
        
        // We want to use the user's debtEntryIndex at when the period closed
        // Find the oldest debtEntryIndex for the corresponding closingDebtIndex
        for (uint i = 0; i < FEE_PERIOD_LENGTH; i++) {
            if (closingDebtIndex >= issuanceData[i].debtEntryIndex) {
                return (issuanceData[i].debtPercentage, issuanceData[i].debtEntryIndex);
            }
        }
    }
// Solidity 0.4.25
/**
 * @notice Logs an accounts issuance data in the current fee period which is then stored historically
 * @param account Message.Senders account address
 * @param debtRatio Debt of this account as a percentage of the global debt.
 * @param debtEntryIndex The index in the global debt ledger. synthetix.synthetixState().issuanceData(account)
 * @param currentPeriodStartDebtIndex The startingDebtIndex of the current fee period
 * @dev onlyFeePool to call me on synthetix.issue() & synthetix.burn() calls to store the locked SNX
 * per fee period so we know to allocate the correct proportions of fees and rewards per period
 accountIssuanceLedger[account][0] has the latest locked amount for the current period. This can be update as many time
 accountIssuanceLedger[account][1-2] has the last locked amount for a previous period they minted or burned
 */
function appendAccountIssuanceRecord(address account, uint debtRatio, uint debtEntryIndex, uint currentPeriodStartDebtIndex)
        external
        onlyFeePool
    {
        // Is the current debtEntryIndex within this fee period
        if (accountIssuanceLedger[account][0].debtEntryIndex < currentPeriodStartDebtIndex) {
             // If its older then shift the previous IssuanceData entries periods down to make room for the new one.
            issuanceDataIndexOrder(account);
        }
        
        // Always store the latest IssuanceData entry at [0]
        accountIssuanceLedger[account][0].debtPercentage = debtRatio;
        accountIssuanceLedger[account][0].debtEntryIndex = debtEntryIndex;
    }
// Solidity 0.4.25
/**
 * @notice Pushes down the entire array of debt ratios per fee period
 */
function issuanceDataIndexOrder(address account)
        private
    {
        for (uint i = FEE_PERIOD_LENGTH - 2; i < FEE_PERIOD_LENGTH; i--) {
            uint next = i + 1;
            accountIssuanceLedger[account][next].debtPercentage = accountIssuanceLedger[account][i].debtPercentage;
            accountIssuanceLedger[account][next].debtEntryIndex = accountIssuanceLedger[account][i].debtEntryIndex;
        }
    }
// Solidity 0.4.25
/**
 * @notice Import issuer data from synthetixState.issuerData on FeePeriodClose() block #
 * @dev Only callable by the contract owner, and only for 6 weeks after deployment.
 * @param accounts Array of issuing addresses
 * @param ratios Array of debt ratios
 * @param periodToInsert The Fee Period to insert the historical records into
 * @param feePeriodCloseIndex An accounts debtEntryIndex is valid when within the fee peroid,
 * since the input ratio will be an average of the pervious periods it just needs to be
 * > recentFeePeriods[periodToInsert].startingDebtIndex
 * < recentFeePeriods[periodToInsert - 1].startingDebtIndex
 */
function importIssuerData(address[] accounts, uint[] ratios, uint periodToInsert, uint feePeriodCloseIndex)
        external
        onlyOwner
        onlyDuringSetup
    {
        require(accounts.length == ratios.length, "Length mismatch");

        for (uint i = 0; i < accounts.length; i++) {
            accountIssuanceLedger[accounts[i]][periodToInsert].debtPercentage = ratios[i];
            accountIssuanceLedger[accounts[i]][periodToInsert].debtEntryIndex = feePeriodCloseIndex;
            emit IssuanceDebtRatioEntry(accounts[i], ratios[i], feePeriodCloseIndex);
        }
    }
// Solidity 0.4.25
/**
 * @notice The RewardsDistribution contract informs us how many SNX rewards are sent to RewardEscrow to be claimed.
 */
function setRewardsToDistribute(uint amount)
        external
    {
        require(messageSender == rewardsAuthority || msg.sender == rewardsAuthority, "Caller is not rewardsAuthority");
        // Add the amount of SNX rewards to distribute on top of any rolling unclaimed amount
        _recentFeePeriodsStorage(0).rewardsToDistribute = _recentFeePeriodsStorage(0).rewardsToDistribute.add(amount);
    }
// Solidity 0.4.25
/**
 * @notice Admin function to import the FeePeriod data from the previous contract
 */
function importFeePeriod(
        uint feePeriodIndex, uint feePeriodId, uint startingDebtIndex, uint startTime,
        uint feesToDistribute, uint feesClaimed, uint rewardsToDistribute, uint rewardsClaimed)
        public
        optionalProxy_onlyOwner
        onlyDuringSetup
    {        
        require (startingDebtIndex <= synthetixState.debtLedgerLength(), "Cannot import bad data");

        _recentFeePeriods[_currentFeePeriod.add(feePeriodIndex).mod(FEE_PERIOD_LENGTH)] = FeePeriod({
            feePeriodId: uint64(feePeriodId),
            startingDebtIndex: uint64(startingDebtIndex),
            startTime: uint64(startTime),
            feesToDistribute: feesToDistribute,
            feesClaimed: feesClaimed,
            rewardsToDistribute: rewardsToDistribute,
            rewardsClaimed: rewardsClaimed
        });
    }
// Solidity 0.4.25
/**
 * @notice Send the rewards to claiming address - will be locked in rewardEscrow.
 * @param account The address to send the fees to.
 * @param snxAmount The amount of SNX.
 */
function _payRewards(address account, uint snxAmount)
        internal
        notFeeAddress(account)
    {
        require(account != address(0), "Account can't be 0");
        require(account != address(this), "Can't send rewards to fee pool");
        require(account != address(proxy), "Can't send rewards to proxy");
        require(account != address(synthetix), "Can't send rewards to synthetix");

        // Record vesting entry for claiming address and amount
        // SNX already minted to rewardEscrow balance
        rewardEscrow.appendVestingEntry(account, snxAmount);
    }
// Solidity 0.4.25
/**
 * @notice Calculate the fee charged on top of a value being sent via an exchange
 * @return Return the fee charged
 */
function exchangeFeeIncurred(uint value)
        public
        view
        returns (uint)
    {
        return value.multiplyDecimal(exchangeFeeRate);

        // Exchanges less than the reciprocal of exchangeFeeRate should be completely eaten up by fees.
        // This is on the basis that exchanges less than this value will result in a nil fee.
        // Probably too insignificant to worry about, but the following code will achieve it.
        //      if (fee == 0 && exchangeFeeRate != 0) {
        //          return _value;
        //      }
        //      return fee;
    }
// Solidity 0.4.25
/**
 * @notice The total fees available in the system to be withdrawn, priced in currencyKey currency
 * @param currencyKey The currency you want to price the fees in
 */
function totalFeesAvailable(bytes32 currencyKey)
        external
        view
        returns (uint)
    {
        uint totalFees = 0;

        // Fees in fee period [0] are not yet available for withdrawal
        for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
            totalFees = totalFees.add(_recentFeePeriodsStorage(i).feesToDistribute);
            totalFees = totalFees.sub(_recentFeePeriodsStorage(i).feesClaimed);
        }

        return synthetix.effectiveValue("XDR", totalFees, currencyKey);
    }
// Solidity 0.4.25
/**
 * @notice The total SNX rewards available in the system to be withdrawn
 */
function totalRewardsAvailable()
        external
        view
        returns (uint)
    {
        uint totalRewards = 0;

        // Rewards in fee period [0] are not yet available for withdrawal
        for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
            totalRewards = totalRewards.add(_recentFeePeriodsStorage(i).rewardsToDistribute);
            totalRewards = totalRewards.sub(_recentFeePeriodsStorage(i).rewardsClaimed);
        }

        return totalRewards;
    }
// Solidity 0.4.25
/**
 * @notice The fees available to be withdrawn by a specific account, priced in currencyKey currency
 * @dev Returns two amounts, one for fees and one for SNX rewards
 * @param currencyKey The currency you want to price the fees in
 */
function feesAvailable(address account, bytes32 currencyKey)
        public
        view
        returns (uint, uint)
    {
        // Add up the fees
        uint[2][FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account);

        uint totalFees = 0;
        uint totalRewards = 0;

        // Fees & Rewards in fee period [0] are not yet available for withdrawal
        for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
            totalFees = totalFees.add(userFees[i][0]);
            totalRewards = totalRewards.add(userFees[i][1]);
        }

        // And convert totalFees to their desired currency
        // Return totalRewards as is in SNX amount
        return (
            synthetix.effectiveValue("XDR", totalFees, currencyKey),
            totalRewards
        );
    }
// Solidity 0.4.25
/**
 * @notice Check if a particular address is able to claim fees right now
 * @param account The address you want to query for
 */
function isFeesClaimable(address account)
        public
        view
        returns (bool)
    {
        // Threshold is calculated from ratio % above the target ratio (issuanceRatio).
        //  0  <  10%:   Claimable
        // 10% > above:  Unable to claim
        uint ratio = synthetix.collateralisationRatio(account);
        uint targetRatio = synthetixState.issuanceRatio();

        // Claimable if collateral ratio below target ratio
        if (ratio < targetRatio) {
            return true;
        }

        // Calculate the threshold for collateral ratio before fees can't be claimed.
        uint ratio_threshold = targetRatio.multiplyDecimal(SafeDecimalMath.unit().add(targetThreshold));

        // Not claimable if collateral ratio above threshold
        if (ratio > ratio_threshold) {
            return false;
        }

        return true;
    }
// Solidity 0.4.25
/**
 * @notice ownershipPercentage is a high precision decimals uint based on
 * wallet's debtPercentage. Gives a precise amount of the feesToDistribute
 * for fees in the period. Precision factor is removed before results are
 * returned.
 * @dev The reported fees owing for the current period [0] are just a
 * running balance until the fee period closes
 */
function _feesAndRewardsFromPeriod(uint period, uint ownershipPercentage, uint debtEntryIndex)
        view
        internal
        returns (uint, uint)
    {
        // If it's zero, they haven't issued, and they have no fees OR rewards.
        if (ownershipPercentage == 0) return (0, 0);

        uint debtOwnershipForPeriod = ownershipPercentage;

        // If period has closed we want to calculate debtPercentage for the period
        if (period > 0) {
            uint closingDebtIndex = uint256(_recentFeePeriodsStorage(period - 1).startingDebtIndex).sub(1);
            debtOwnershipForPeriod = _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex);
        }

        // Calculate their percentage of the fees / rewards in this period
        // This is a high precision integer.
        uint feesFromPeriod = _recentFeePeriodsStorage(period).feesToDistribute
            .multiplyDecimal(debtOwnershipForPeriod);

        uint rewardsFromPeriod = _recentFeePeriodsStorage(period).rewardsToDistribute
            .multiplyDecimal(debtOwnershipForPeriod);

        return (
            feesFromPeriod.preciseDecimalToDecimal(),
            rewardsFromPeriod.preciseDecimalToDecimal()
        );
    }
// Solidity 0.5.17
/**
 * @notice A method to add a bearer to a role
 * @param _account The account to add as a bearer.
 * @param _role The role to add the bearer to.
 */
function addBearer(address _account, uint256 _role)
    external
  {
    require(
      _role < roles.length,
      "Role doesn't exist."
    );
    require(
      hasRole(msg.sender, roles[_role].admin),
      "User can't add bearers."
    );
    require(
      !hasRole(_account, _role),
      "Account is bearer of role."
    );
    roles[_role].bearers[_account] = true;
    emit BearerAdded(_account, _role);
  }
// Solidity 0.5.17
/** @notice Initializes TWAP start point, starts countdown to first rebase
 *
 */
function init_twap()
        public
    {
        require(timeOfTWAPInit == 0, "already activated");
        (uint priceCumulative, uint32 blockTimestamp) =
           UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0);
        require(blockTimestamp > 0, "no trades");
        blockTimestampLast = blockTimestamp;
        priceCumulativeLast = priceCumulative;
        timeOfTWAPInit = blockTimestamp;
    }
// Solidity 0.5.17
/** @notice Activates rebasing
 *   @dev One way function, cannot be undone, callable by anyone
 */
function activate_rebasing()
        public
    {
        require(timeOfTWAPInit > 0, "twap wasnt intitiated, call init_twap()");
        // cannot enable prior to end of rebaseDelay
        require(now >= timeOfTWAPInit + rebaseDelay, "!end_delay");

        rebasingActive = false; // disable rebase, originally true;
    }
// Solidity 0.5.17
/**
 * @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
 *
 * @param amountIn input amount of the asset
 * @param reserveIn reserves of the asset being sold
 * @param reserveOut reserves if the asset being purchased
 */
function getAmountOut(
        uint amountIn,
        uint reserveIn,
        uint reserveOut
    )
        internal
        pure
        returns (uint amountOut)
    {
       require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
       require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
       uint amountInWithFee = amountIn.mul(997);
       uint numerator = amountInWithFee.mul(reserveOut);
       uint denominator = reserveIn.mul(1000).add(amountInWithFee);
       amountOut = numerator / denominator;
   }
// Solidity 0.5.17
/**
 * @notice Calculates TWAP from uniswap
 *
 * @dev When liquidity is low, this can be manipulated by an end of block -> next block
 *      attack. We delay the activation of rebases 12 hours after liquidity incentives
 *      to reduce this attack vector. Additional there is very little supply
 *      to be able to manipulate this during that time period of highest vuln.
 */
function getTWAP()
        internal
        returns (uint256)
    {
      (uint priceCumulative, uint32 blockTimestamp) =
         UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0);
       uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired

       // no period check as is done in isRebaseWindow

       // overflow is desired, casting never truncates
        // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
        FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed));

        priceCumulativeLast = priceCumulative;
        blockTimestampLast = blockTimestamp;

        return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18));
    }
// Solidity 0.5.17
/**
 * @notice Calculates current TWAP from uniswap
 *
 */
function getCurrentTWAP()
        public
        view
        returns (uint256)
    {
      (uint priceCumulative, uint32 blockTimestamp) =
         UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0);
       uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired

       // no period check as is done in isRebaseWindow

       // overflow is desired, casting never truncates
        // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
        FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed));

        return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18));
    }
// Solidity 0.5.17
/**
 * @return Computes in % how far off market is from peg
 */
function computeOffPegPerc(uint256 rate)
        private
        view
        returns (uint256, bool)
    {
        if (withinDeviationThreshold(rate)) {
            return (0, false);
        }

        // indexDelta =  (rate - targetRate) / targetRate
        if (rate > targetRate) {
            return (rate.sub(targetRate).mul(10**18).div(targetRate), true);
        } else {
            return (targetRate.sub(rate).mul(10**18).div(targetRate), false);
        }
    }
// Solidity 0.4.25
// recommended fix for known attack on any ERC20
function safeApprove( address _spender,
                        uint256 _currentValue,
                        uint256 _value ) public
                        returns (bool success) {

    // If current allowance for _spender is equal to _currentValue, then
    // overwrite it with _value and return true, otherwise return false.

    if (allowances_[msg.sender][_spender] == _currentValue)
      return approve(_spender, _value);

    return false;
  }