lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.25
/**
 * @notice Remove a single value from an array by iterating through until it is found.
 * @param entry The entry to find
 * @param array The array to mutate
 * @return bool Whether or not the entry was found and removed
 */
function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) {
        for (uint i = 0; i < array.length; i++) {
            if (array[i] == entry) {
                delete array[i];

                // Copy the last key into the place of the one we just deleted
                // If there's only one key, this is array[0] = array[0].
                // If we're deleting the last one, it's also a NOOP in the same way.
                array[i] = array[array.length - 1];

                // Decrease the size of the array by one.
                array.length--;

                return true;
            }
        }
        return false;
    }
// Solidity 0.4.25
/**
 * @notice Remove a pricing aggregator for the given key
 * @param currencyKey THe currency key to remove an aggregator for
 */
function removeAggregator(bytes32 currencyKey) external onlyOwner {
        address aggregator = aggregators[currencyKey];
        require(aggregator != address(0), "No aggregator exists for key");
        delete aggregators[currencyKey];

        bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys);

        if (wasRemoved) {
            emit AggregatorRemoved(currencyKey, aggregator);
        }
    }
// Solidity 0.4.25
/**
 * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency
 * @param sourceCurrencyKey The currency the amount is specified in
 * @param sourceAmount The source amount, specified in UNIT base
 * @param destinationCurrencyKey The destination currency
 */
function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey)
        public
        view
        rateNotStale(sourceCurrencyKey)
        rateNotStale(destinationCurrencyKey)
        returns (uint)
    {
        // If there's no change in the currency, then just return the amount they gave us
        if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;

        // Calculate the effective value by going from source -> USD -> destination
        return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey))
            .divideDecimalRound(rateForCurrency(destinationCurrencyKey));
    }
// Solidity 0.4.25
/**
 * @notice Retrieve the rates for a list of currencies
 */
function ratesForCurrencies(bytes32[] currencyKeys)
        public
        view
        returns (uint[])
    {
        uint[] memory _localRates = new uint[](currencyKeys.length);

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

        return _localRates;
    }
// Solidity 0.4.25
/**
 * @notice Retrieve the rates and isAnyStale for a list of currencies
 */
function ratesAndStaleForCurrencies(bytes32[] currencyKeys)
        public
        view
        returns (uint[], bool)
    {
        uint[] memory _localRates = new uint[](currencyKeys.length);

        bool anyRateStale = false;
        uint period = rateStalePeriod;
        for (uint i = 0; i < currencyKeys.length; i++) {
            RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]);
            _localRates[i] = uint256(rateAndUpdateTime.rate);
            if (!anyRateStale) {
                anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now);
            }
        }

        return (_localRates, anyRateStale);
    }
// Solidity 0.4.25
/**
 * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period.
 */
function anyRateIsStale(bytes32[] currencyKeys)
        external
        view
        returns (bool)
    {
        // Loop through each key and check whether the data point is stale.
        uint256 i = 0;

        while (i < currencyKeys.length) {
            // sUSD is a special case and is never false
            if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) {
                return true;
            }
            i += 1;
        }

        return false;
    }
// Solidity 0.4.25
/**
 * @notice Add an associated Synth contract to the Synthetix system
 * @dev Only the contract owner may call this.
 */
function addSynth(Synth synth)
        external
        optionalProxy_onlyOwner
    {
        bytes32 currencyKey = synth.currencyKey();

        require(synths[currencyKey] == Synth(0), "Synth already exists");
        require(synthsByAddress[synth] == bytes32(0), "Synth address already exists");

        availableSynths.push(synth);
        synths[currencyKey] = synth;
        synthsByAddress[synth] = currencyKey;
    }
// Solidity 0.4.25
/**
 * @notice Total amount of synths issued by the system, priced in currencyKey
 * @param currencyKey The currency to value the synths in
 */
function totalIssuedSynths(bytes32 currencyKey)
        public
        view
        returns (uint)
    {
        uint total = 0;
        uint currencyRate = exchangeRates.rateForCurrency(currencyKey);

        (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys());
        require(!anyRateStale, "Rates are stale");

        for (uint i = 0; i < availableSynths.length; i++) {
            // What's the total issued value of that synth in the destination currency?
            // Note: We're not using our effectiveValue function because we don't want to go get the
            //       rate for the destination currency and check if it's stale repeatedly on every
            //       iteration of the loop
            uint synthValue = availableSynths[i].totalSupply()
                .multiplyDecimalRound(rates[i]);
            total = total.add(synthValue);
        }

        return total.divideDecimalRound(currencyRate);
    }
// Solidity 0.4.25
/**
 * @notice Determine the effective fee rate for the exchange, taking into considering swing trading
 */
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
        public
        view
        returns (uint)
    {
        // Get the base exchange fee rate
        uint exchangeFeeRate = feePool.exchangeFeeRate();

        uint multiplier = 1;

        // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD.
        // Note: this assumes shorts begin with 'i' and longs with 's'.
        if (
            (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x69) ||
            (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != "sUSD" && destinationCurrencyKey[0] == 0x73)
        ) {
            // If so then double the exchange fee multipler
            multiplier = 2;
        }

        return exchangeFeeRate.mul(multiplier);
    }
// Solidity 0.4.25
/**
 * @notice ERC20 transfer function.
 */
function transfer(address to, uint value)
        public
        optionalProxy
        returns (bool)
    {
        // Ensure they're not trying to exceed their staked SNX amount
        require(value <= transferableSynthetix(messageSender), "Cannot transfer staked or escrowed SNX");

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

        return true;
    }
// Solidity 0.8.9
// mint the reserve tokens for later airdroping
function mintReserve( uint _mType, address _to, string memory _uri ) public onlyRole(MINTER_ROLE) {

        // Mint reserve supply
        uint quantity = _reservedSupply[_mType];
        require( quantity > 0, "M10: already minted" );               

        _mintTokens( _mType, quantity, _to, _uri, true );

        // erase the reserve
        _reservedSupply[_mType] = 0;
    }
// Solidity 0.4.25
/**
 * @notice Function that allows you to exchange synths you hold in one flavour for another.
 * @param sourceCurrencyKey The source currency you wish to exchange from
 * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange
 * @param destinationCurrencyKey The destination currency you wish to obtain.
 * @return Boolean that indicates whether the transfer succeeded or failed.
 */
function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey)
        external
        optionalProxy
        // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us.
        returns (bool)
    {
        require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth");
        require(sourceAmount > 0, "Zero amount");

        // verify gas price limit
        validateGasPrice(tx.gasprice);

        //  If the oracle has set protectionCircuit to true then burn the synths
        if (protectionCircuit) {
            synths[sourceCurrencyKey].burn(messageSender, sourceAmount);
            return true;
        } else {
            // Pass it along, defaulting to the sender as the recipient.
            return _internalExchange(
                messageSender,
                sourceCurrencyKey,
                sourceAmount,
                destinationCurrencyKey,
                messageSender,
                true // Charge fee on the exchange
            );
        }
    }
// Solidity 0.4.25
/**
 * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency
 * @dev Only the synth contract can call this function
 * @param from The address to exchange / burn synth from
 * @param sourceCurrencyKey The source currency you wish to exchange from
 * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange
 * @param destinationCurrencyKey The destination currency you wish to obtain.
 * @param destinationAddress Where the result should go.
 * @return Boolean that indicates whether the transfer succeeded or failed.
 */
function synthInitiatedExchange(
        address from,
        bytes32 sourceCurrencyKey,
        uint sourceAmount,
        bytes32 destinationCurrencyKey,
        address destinationAddress
    )
        external
        optionalProxy
        returns (bool)
    {
        require(synthsByAddress[messageSender] != bytes32(0), "Only synth allowed");
        require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth");
        require(sourceAmount > 0, "Zero amount");

        // Pass it along
        return _internalExchange(
            from,
            sourceCurrencyKey,
            sourceAmount,
            destinationCurrencyKey,
            destinationAddress,
            false
        );
    }
// 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 amount The amount of synths you wish to issue with a base of UNIT
 */
function issueSynths(uint amount)
        public
        optionalProxy
        // No need to check if price is stale, as it is checked in issuableSynths.
    {
        bytes32 currencyKey = "sUSD";

        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.
 */
function issueMaxSynths()
        external
        optionalProxy
    {
        bytes32 currencyKey = "sUSD";

        // 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 amount The amount (in UNIT base) you wish to burn
 * @dev The amount to burn is debased to XDR's
 */
function burnSynths(uint amount)
        external
        optionalProxy
        // No need to check for stale rates as effectiveValue checks rates
    {
        bytes32 currencyKey = "sUSD";

        // 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 The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs.
 * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue.
 */
function maxIssuableSynths(address issuer, bytes32 currencyKey)
        public
        view
        // We don't need to check stale rates here as effectiveValue will do it for us.
        returns (uint)
    {
        // What is the value of their SNX balance in the destination currency?
        uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey);

        // They're allowed to issue up to issuanceRatio of that value
        return destinationValue.multiplyDecimal(synthetixState.issuanceRatio());
    }
// Solidity 0.4.25
/**
 * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function
 * will tell you how many synths a user has to give back to the system in order to unlock their original
 * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price
 * the debt in sUSD, XDR, or any other synth you wish.
 */
function debtBalanceOf(address issuer, bytes32 currencyKey)
        public
        view
        // Don't need to check for stale rates here because totalIssuedSynths will do it for us
        returns (uint)
    {
        // What was their initial debt ownership?
        uint initialDebtOwnership;
        uint debtEntryIndex;
        (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer);

        // If it's zero, they haven't issued, and they have no debt.
        if (initialDebtOwnership == 0) return 0;

        // Figure out the global debt percentage delta from when they entered the system.
        // This is a high precision integer of 27 (1e27) decimals.
        uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry()
            .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex))
            .multiplyDecimalRoundPrecise(initialDebtOwnership);

        // What's the total value of the system in their requested currency?
        uint totalSystemValue = totalIssuedSynths(currencyKey);

        // Their debt balance is their portion of the total system value.
        uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal()
            .multiplyDecimalRoundPrecise(currentDebtOwnership);

        // Convert back into 18 decimals (1e18)
        return highPrecisionBalance.preciseDecimalToDecimal();
    }
// Solidity 0.4.25
/**
 * @notice The remaining synths an issuer can issue against their total synthetix balance.
 * @param issuer The account that intends to issue
 * @param currencyKey The currency to price issuable value in
 */
function remainingIssuableSynths(address issuer, bytes32 currencyKey)
        public
        view
        // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us.
        returns (uint)
    {
        uint alreadyIssued = debtBalanceOf(issuer, currencyKey);
        uint max = maxIssuableSynths(issuer, currencyKey);

        if (alreadyIssued >= max) {
            return 0;
        } else {
            return max.sub(alreadyIssued);
        }
    }
// Solidity 0.4.25
/**
 * @notice The total SNX owned by this account, both escrowed and unescrowed,
 * against which synths can be issued.
 * This includes those already being used as collateral (locked), and those
 * available for further issuance (unlocked).
 */
function collateral(address account)
        public
        view
        returns (uint)
    {
        uint balance = tokenState.balanceOf(account);

        if (escrow != address(0)) {
            balance = balance.add(escrow.balanceOf(account));
        }

        if (rewardEscrow != address(0)) {
            balance = balance.add(rewardEscrow.balanceOf(account));
        }

        return balance;
    }
// Solidity 0.4.25
/**
 * @notice The number of SNX that are free to be transferred for an account.
 * @dev Escrowed SNX are not transferable, so they are not included
 * in this calculation.
 * @notice SNX rate not stale is checked within debtBalanceOf
 */
function transferableSynthetix(address account)
        public
        view
        rateNotStale("SNX") // SNX is not a synth so is not checked in totalIssuedSynths
        returns (uint)
    {
        // How many SNX do they have, excluding escrow?
        // Note: We're excluding escrow here because we're interested in their transferable amount
        // and escrowed SNX are not transferable.
        uint balance = tokenState.balanceOf(account);

        // How many of those will be locked by the amount they've issued?
        // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require
        // 100 SNX to be locked in their wallet to maintain their collateralisation ratio
        // The locked synthetix value can exceed their balance.
        uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio());

        // If we exceed the balance, no SNX are transferable, otherwise the difference is.
        if (lockedSynthetixValue >= balance) {
            return 0;
        } else {
            return balance.sub(lockedSynthetixValue);
        }
    }
// Solidity 0.4.25
/**
 * @notice Mints the inflationary SNX supply. The inflation shedule is
 * defined in the SupplySchedule contract.
 * The mint() function is publicly callable by anyone. The caller will
 receive a minter reward as specified in supplySchedule.minterReward().
 */
function mint()
        external
        returns (bool)
    {
        require(rewardsDistribution != address(0), "RewardsDistribution not set");

        uint supplyToMint = supplySchedule.mintableSupply();
        require(supplyToMint > 0, "No supply is mintable");

        // record minting event before mutation to token supply
        supplySchedule.recordMintEvent(supplyToMint);

        // Set minted SNX balance to RewardEscrow's balance
        // Minus the minterReward and set balance of minter to add reward
        uint minterReward = supplySchedule.minterReward();
        // Get the remainder
        uint amountToDistribute = supplyToMint.sub(minterReward);

        // Set the token balance to the RewardsDistribution contract
        tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute));
        emitTransfer(this, rewardsDistribution, amountToDistribute);

        // Kick off the distribution of rewards
        rewardsDistribution.distributeRewards(amountToDistribute);

        // Assign the minters reward.
        tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward));
        emitTransfer(this, msg.sender, minterReward);

        totalSupply = totalSupply.add(supplyToMint);

        return true;
    }
// Solidity 0.8.12
/**
 * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
 * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
 * hash matches the root of the tree. When processing the proof, the pairs
 * of leafs & pre-images are assumed to be sorted.
 *
 * _Available since v4.4._
 */
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            bytes32 proofElement = proof[i];
            if (computedHash <= proofElement) {
                // Hash(current computed hash + current element of the proof)
                computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
            } else {
                // Hash(current element of the proof + current computed hash)
                computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
            }
        }
        return computedHash;
    }
// Solidity 0.8.12
/**
 * @dev See {IERC721Enumerable-totalSupply}.
 */
function totalSupply() public view override returns (uint256) {
        // Counter underflow is impossible as _burnCounter cannot be incremented
        // more than _currentIndex times
        unchecked {
            return _currentIndex - _burnCounter;    
        }
    }
// Solidity 0.8.1
/**
 * check_availability() returns a bunch of pool info given a pool id
 * id                    swap pool id
 * this function returns 1. exchange_addrs that can be used to determine the index
 *                       2. remaining target tokens
 *                       3. if started
 *                       4. if ended
 *                       5. swapped amount of the query address
 *                       5. exchanged amount of each token
 **/
function check_availability (bytes32 id) external view 
        returns (address[] memory exchange_addrs, uint256 remaining, 
                 bool started, bool expired, bool unlocked, uint256 unlock_time,
                 uint256 swapped, uint128[] memory exchanged_tokens) {
        Pool storage pool = pool_by_id[id];
        return (
            pool.exchange_addrs,                                                // exchange_addrs 0x0 means destructed
            unbox(pool.packed2, 0, 128),                                        // remaining
            block.timestamp > unbox(pool.packed1, 200, 28) + base_time,         // started
            block.timestamp > unbox(pool.packed1, 228, 28) + base_time,         // expired
            block.timestamp > pool.unlock_time + base_time,                     // unlocked
            pool.unlock_time + base_time,                                       // unlock_time
            pool.swapped_map[msg.sender],                                       // swapped number 
            pool.exchanged_tokens                                               // exchanged tokens
        );
    }